context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: 474141 $ * $Date: 2006-11-12 21:43:37 -0700 (Sun, 12 Nov 2006) $ * * iBATIS.NET Data Mapper * Copyright (C) 2004 - Gilles Bayon * * * 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; using System.Collections; using System.Collections.Specialized; using System.Configuration; using System.Xml; using IBatisNet.Common.Logging.Impl; using ConfigurationException = IBatisNet.Common.Exceptions.ConfigurationException; namespace IBatisNet.Common.Logging { /// <summary> /// Used in an application's configuration file (App.Config or Web.Config) to configure the logging subsystem. /// </summary> /// <remarks> /// <example> /// An example configuration section that writes IBatisNet messages to the Console using the built-in Console Logger. /// <code lang="XML" escaped="true"> /// <configuration> /// <configSections> /// <sectionGroup name="iBATIS"> /// <section name="logging" type="IBatisNet.Common.Logging.ConfigurationSectionHandler, IBatisNet.Common" /> /// </sectionGroup> /// </configSections> /// <iBATIS> /// <logging> /// <logFactoryAdapter type="IBatisNet.Common.Logging.Impl.ConsoleOutLoggerFA, IBatisNet.Common"> /// <arg key="showLogName" value="true" /> /// <arg key="showDataTime" value="true" /> /// <arg key="level" value="ALL" /> /// <arg key="dateTimeFormat" value="yyyy/MM/dd HH:mm:ss:SSS" /> /// </logFactoryAdapter> /// </logging> /// </iBATIS> /// </configuration> /// </code> /// </example> /// <para> /// The following aliases are recognized for the type attribute of logFactoryAdapter: /// </para> /// <list type="table"> /// <item><term>CONSOLE</term><description>Alias for IBatisNet.Common.Logging.Impl.ConsoleOutLoggerFA, IBatisNet.Common</description></item> /// <item><term>TRACE</term><description>Alias for IBatisNet.Common.Logging.Impl.TraceLoggerFA, IBatisNet.Common</description></item> /// <item><term>NOOP</term><description>Alias IBatisNet.Common.Logging.Impl.NoOpLoggerFA, IBatisNet.Common</description></item> /// </list> /// </remarks> public class ConfigurationSectionHandler: IConfigurationSectionHandler { #region Fields private static readonly string LOGFACTORYADAPTER_ELEMENT = "logFactoryAdapter"; private static readonly string LOGFACTORYADAPTER_ELEMENT_TYPE_ATTRIB = "type"; private static readonly string ARGUMENT_ELEMENT = "arg"; private static readonly string ARGUMENT_ELEMENT_KEY_ATTRIB = "key"; private static readonly string ARGUMENT_ELEMENT_VALUE_ATTRIB = "value"; #endregion /// <summary> /// Constructor /// </summary> public ConfigurationSectionHandler() { } /// <summary> /// Retrieves the <see cref="Type" /> of the logger the use by looking at the logFactoryAdapter element /// of the logging configuration element. /// </summary> /// <param name="section"></param> /// <returns> /// A <see cref="LogSetting" /> object containing the specified type that implements /// <see cref="ILoggerFactoryAdapter" /> along with zero or more properties that will be /// passed to the logger factory adapter's constructor as an <see cref="IDictionary" />. /// </returns> private LogSetting ReadConfiguration( XmlNode section ) { XmlNode logFactoryElement = section.SelectSingleNode( LOGFACTORYADAPTER_ELEMENT ); string factoryTypeString = string.Empty; if ( logFactoryElement.Attributes[LOGFACTORYADAPTER_ELEMENT_TYPE_ATTRIB] != null ) factoryTypeString = logFactoryElement.Attributes[LOGFACTORYADAPTER_ELEMENT_TYPE_ATTRIB].Value; if ( factoryTypeString == string.Empty ) { throw new ConfigurationException ( "Required Attribute '" + LOGFACTORYADAPTER_ELEMENT_TYPE_ATTRIB + "' not found in element '" + LOGFACTORYADAPTER_ELEMENT + "'" ); } Type factoryType = null; try { if (String.Compare(factoryTypeString, "CONSOLE", true) == 0) { factoryType = typeof(ConsoleOutLoggerFA); } else if (String.Compare(factoryTypeString, "TRACE", true) == 0) { factoryType = typeof(TraceLoggerFA); } else if (String.Compare(factoryTypeString, "NOOP", true) == 0) { factoryType = typeof(NoOpLoggerFA); } else { factoryType = Type.GetType( factoryTypeString, true, false ); } } catch ( Exception e ) { throw new ConfigurationException ( "Unable to create type '" + factoryTypeString + "'" , e ); } XmlNodeList propertyNodes = logFactoryElement.SelectNodes( ARGUMENT_ELEMENT ); NameValueCollection properties = null; #if dotnet2 properties = new NameValueCollection(StringComparer.InvariantCultureIgnoreCase); #else properties = new NameValueCollection( null, new CaseInsensitiveComparer() ); #endif foreach ( XmlNode propertyNode in propertyNodes ) { string key = string.Empty; string itsValue = string.Empty; XmlAttribute keyAttrib = propertyNode.Attributes[ARGUMENT_ELEMENT_KEY_ATTRIB]; XmlAttribute valueAttrib = propertyNode.Attributes[ARGUMENT_ELEMENT_VALUE_ATTRIB]; if ( keyAttrib == null ) { throw new ConfigurationException ( "Required Attribute '" + ARGUMENT_ELEMENT_KEY_ATTRIB + "' not found in element '" + ARGUMENT_ELEMENT + "'" ); } else { key = keyAttrib.Value; } if ( valueAttrib != null ) { itsValue = valueAttrib.Value; } properties.Add( key, itsValue ); } return new LogSetting( factoryType, properties ); } #region IConfigurationSectionHandler Members /// <summary> /// Verifies that the logFactoryAdapter element appears once in the configuration section. /// </summary> /// <param name="parent">The parent of the current item.</param> /// <param name="configContext">Additional information about the configuration process.</param> /// <param name="section">The configuration section to apply an XPath query too.</param> /// <returns> /// A <see cref="LogSetting" /> object containing the specified logFactoryAdapter type /// along with user supplied configuration properties. /// </returns> public object Create(object parent, object configContext, XmlNode section) { int logFactoryElementsCount = section.SelectNodes( LOGFACTORYADAPTER_ELEMENT ).Count; if ( logFactoryElementsCount > 1 ) { throw new ConfigurationException( "Only one <logFactoryAdapter> element allowed" ); } else if ( logFactoryElementsCount == 1 ) { return ReadConfiguration( section ); } else { 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. using System.Collections.Generic; using System.Diagnostics; using System.Reflection.Internal; namespace System.Reflection.Metadata.Ecma335 { /// <summary> /// Provides extension methods for working with certain raw elements of the ECMA-335 metadata tables and heaps. /// </summary> public static class MetadataReaderExtensions { /// <summary> /// Returns the number of rows in the specified table. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception> public static int GetTableRowCount(this MetadataReader reader, TableIndex tableIndex) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } if ((int)tableIndex >= TableIndexExtensions.Count) { Throw.TableIndexOutOfRange(); } return reader.TableRowCounts[(int)tableIndex]; } /// <summary> /// Returns the size of a row in the specified table. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception> public static int GetTableRowSize(this MetadataReader reader, TableIndex tableIndex) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } switch (tableIndex) { case TableIndex.Module: return reader.ModuleTable.RowSize; case TableIndex.TypeRef: return reader.TypeRefTable.RowSize; case TableIndex.TypeDef: return reader.TypeDefTable.RowSize; case TableIndex.FieldPtr: return reader.FieldPtrTable.RowSize; case TableIndex.Field: return reader.FieldTable.RowSize; case TableIndex.MethodPtr: return reader.MethodPtrTable.RowSize; case TableIndex.MethodDef: return reader.MethodDefTable.RowSize; case TableIndex.ParamPtr: return reader.ParamPtrTable.RowSize; case TableIndex.Param: return reader.ParamTable.RowSize; case TableIndex.InterfaceImpl: return reader.InterfaceImplTable.RowSize; case TableIndex.MemberRef: return reader.MemberRefTable.RowSize; case TableIndex.Constant: return reader.ConstantTable.RowSize; case TableIndex.CustomAttribute: return reader.CustomAttributeTable.RowSize; case TableIndex.FieldMarshal: return reader.FieldMarshalTable.RowSize; case TableIndex.DeclSecurity: return reader.DeclSecurityTable.RowSize; case TableIndex.ClassLayout: return reader.ClassLayoutTable.RowSize; case TableIndex.FieldLayout: return reader.FieldLayoutTable.RowSize; case TableIndex.StandAloneSig: return reader.StandAloneSigTable.RowSize; case TableIndex.EventMap: return reader.EventMapTable.RowSize; case TableIndex.EventPtr: return reader.EventPtrTable.RowSize; case TableIndex.Event: return reader.EventTable.RowSize; case TableIndex.PropertyMap: return reader.PropertyMapTable.RowSize; case TableIndex.PropertyPtr: return reader.PropertyPtrTable.RowSize; case TableIndex.Property: return reader.PropertyTable.RowSize; case TableIndex.MethodSemantics: return reader.MethodSemanticsTable.RowSize; case TableIndex.MethodImpl: return reader.MethodImplTable.RowSize; case TableIndex.ModuleRef: return reader.ModuleRefTable.RowSize; case TableIndex.TypeSpec: return reader.TypeSpecTable.RowSize; case TableIndex.ImplMap: return reader.ImplMapTable.RowSize; case TableIndex.FieldRva: return reader.FieldRvaTable.RowSize; case TableIndex.EncLog: return reader.EncLogTable.RowSize; case TableIndex.EncMap: return reader.EncMapTable.RowSize; case TableIndex.Assembly: return reader.AssemblyTable.RowSize; case TableIndex.AssemblyProcessor: return reader.AssemblyProcessorTable.RowSize; case TableIndex.AssemblyOS: return reader.AssemblyOSTable.RowSize; case TableIndex.AssemblyRef: return reader.AssemblyRefTable.RowSize; case TableIndex.AssemblyRefProcessor: return reader.AssemblyRefProcessorTable.RowSize; case TableIndex.AssemblyRefOS: return reader.AssemblyRefOSTable.RowSize; case TableIndex.File: return reader.FileTable.RowSize; case TableIndex.ExportedType: return reader.ExportedTypeTable.RowSize; case TableIndex.ManifestResource: return reader.ManifestResourceTable.RowSize; case TableIndex.NestedClass: return reader.NestedClassTable.RowSize; case TableIndex.GenericParam: return reader.GenericParamTable.RowSize; case TableIndex.MethodSpec: return reader.MethodSpecTable.RowSize; case TableIndex.GenericParamConstraint: return reader.GenericParamConstraintTable.RowSize; // debug tables case TableIndex.Document: return reader.DocumentTable.RowSize; case TableIndex.MethodDebugInformation: return reader.MethodDebugInformationTable.RowSize; case TableIndex.LocalScope: return reader.LocalScopeTable.RowSize; case TableIndex.LocalVariable: return reader.LocalVariableTable.RowSize; case TableIndex.LocalConstant: return reader.LocalConstantTable.RowSize; case TableIndex.ImportScope: return reader.ImportScopeTable.RowSize; case TableIndex.StateMachineMethod: return reader.StateMachineMethodTable.RowSize; case TableIndex.CustomDebugInformation: return reader.CustomDebugInformationTable.RowSize; default: throw new ArgumentOutOfRangeException(nameof(tableIndex)); } } /// <summary> /// Returns the offset from the start of metadata to the specified table. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception> public static unsafe int GetTableMetadataOffset(this MetadataReader reader, TableIndex tableIndex) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return (int)(reader.GetTableMetadataBlock(tableIndex).Pointer - reader.Block.Pointer); } private static MemoryBlock GetTableMetadataBlock(this MetadataReader reader, TableIndex tableIndex) { Debug.Assert(reader != null); switch (tableIndex) { case TableIndex.Module: return reader.ModuleTable.Block; case TableIndex.TypeRef: return reader.TypeRefTable.Block; case TableIndex.TypeDef: return reader.TypeDefTable.Block; case TableIndex.FieldPtr: return reader.FieldPtrTable.Block; case TableIndex.Field: return reader.FieldTable.Block; case TableIndex.MethodPtr: return reader.MethodPtrTable.Block; case TableIndex.MethodDef: return reader.MethodDefTable.Block; case TableIndex.ParamPtr: return reader.ParamPtrTable.Block; case TableIndex.Param: return reader.ParamTable.Block; case TableIndex.InterfaceImpl: return reader.InterfaceImplTable.Block; case TableIndex.MemberRef: return reader.MemberRefTable.Block; case TableIndex.Constant: return reader.ConstantTable.Block; case TableIndex.CustomAttribute: return reader.CustomAttributeTable.Block; case TableIndex.FieldMarshal: return reader.FieldMarshalTable.Block; case TableIndex.DeclSecurity: return reader.DeclSecurityTable.Block; case TableIndex.ClassLayout: return reader.ClassLayoutTable.Block; case TableIndex.FieldLayout: return reader.FieldLayoutTable.Block; case TableIndex.StandAloneSig: return reader.StandAloneSigTable.Block; case TableIndex.EventMap: return reader.EventMapTable.Block; case TableIndex.EventPtr: return reader.EventPtrTable.Block; case TableIndex.Event: return reader.EventTable.Block; case TableIndex.PropertyMap: return reader.PropertyMapTable.Block; case TableIndex.PropertyPtr: return reader.PropertyPtrTable.Block; case TableIndex.Property: return reader.PropertyTable.Block; case TableIndex.MethodSemantics: return reader.MethodSemanticsTable.Block; case TableIndex.MethodImpl: return reader.MethodImplTable.Block; case TableIndex.ModuleRef: return reader.ModuleRefTable.Block; case TableIndex.TypeSpec: return reader.TypeSpecTable.Block; case TableIndex.ImplMap: return reader.ImplMapTable.Block; case TableIndex.FieldRva: return reader.FieldRvaTable.Block; case TableIndex.EncLog: return reader.EncLogTable.Block; case TableIndex.EncMap: return reader.EncMapTable.Block; case TableIndex.Assembly: return reader.AssemblyTable.Block; case TableIndex.AssemblyProcessor: return reader.AssemblyProcessorTable.Block; case TableIndex.AssemblyOS: return reader.AssemblyOSTable.Block; case TableIndex.AssemblyRef: return reader.AssemblyRefTable.Block; case TableIndex.AssemblyRefProcessor: return reader.AssemblyRefProcessorTable.Block; case TableIndex.AssemblyRefOS: return reader.AssemblyRefOSTable.Block; case TableIndex.File: return reader.FileTable.Block; case TableIndex.ExportedType: return reader.ExportedTypeTable.Block; case TableIndex.ManifestResource: return reader.ManifestResourceTable.Block; case TableIndex.NestedClass: return reader.NestedClassTable.Block; case TableIndex.GenericParam: return reader.GenericParamTable.Block; case TableIndex.MethodSpec: return reader.MethodSpecTable.Block; case TableIndex.GenericParamConstraint: return reader.GenericParamConstraintTable.Block; // debug tables case TableIndex.Document: return reader.DocumentTable.Block; case TableIndex.MethodDebugInformation: return reader.MethodDebugInformationTable.Block; case TableIndex.LocalScope: return reader.LocalScopeTable.Block; case TableIndex.LocalVariable: return reader.LocalVariableTable.Block; case TableIndex.LocalConstant: return reader.LocalConstantTable.Block; case TableIndex.ImportScope: return reader.ImportScopeTable.Block; case TableIndex.StateMachineMethod: return reader.StateMachineMethodTable.Block; case TableIndex.CustomDebugInformation: return reader.CustomDebugInformationTable.Block; default: throw new ArgumentOutOfRangeException(nameof(tableIndex)); } } /// <summary> /// Returns the size of the specified heap. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception> public static int GetHeapSize(this MetadataReader reader, HeapIndex heapIndex) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return reader.GetMetadataBlock(heapIndex).Length; } /// <summary> /// Returns the offset from the start of metadata to the specified heap. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception> public static unsafe int GetHeapMetadataOffset(this MetadataReader reader, HeapIndex heapIndex) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return (int)(reader.GetMetadataBlock(heapIndex).Pointer - reader.Block.Pointer); } /// <summary> /// Returns the size of the specified heap. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception> private static MemoryBlock GetMetadataBlock(this MetadataReader reader, HeapIndex heapIndex) { Debug.Assert(reader != null); switch (heapIndex) { case HeapIndex.UserString: return reader.UserStringStream.Block; case HeapIndex.String: return reader.StringStream.Block; case HeapIndex.Blob: return reader.BlobStream.Block; case HeapIndex.Guid: return reader.GuidStream.Block; default: throw new ArgumentOutOfRangeException(nameof(heapIndex)); } } /// <summary> /// Returns the a handle to the UserString that follows the given one in the UserString heap or a nil handle if it is the last one. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> public static UserStringHandle GetNextHandle(this MetadataReader reader, UserStringHandle handle) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return reader.UserStringStream.GetNextHandle(handle); } /// <summary> /// Returns the a handle to the Blob that follows the given one in the Blob heap or a nil handle if it is the last one. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> public static BlobHandle GetNextHandle(this MetadataReader reader, BlobHandle handle) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return reader.BlobStream.GetNextHandle(handle); } /// <summary> /// Returns the a handle to the String that follows the given one in the String heap or a nil handle if it is the last one. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> public static StringHandle GetNextHandle(this MetadataReader reader, StringHandle handle) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return reader.StringStream.GetNextHandle(handle); } /// <summary> /// Enumerates entries of EnC log. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> public static IEnumerable<EditAndContinueLogEntry> GetEditAndContinueLogEntries(this MetadataReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } for (int rid = 1; rid <= reader.EncLogTable.NumberOfRows; rid++) { yield return new EditAndContinueLogEntry( new EntityHandle(reader.EncLogTable.GetToken(rid)), reader.EncLogTable.GetFuncCode(rid)); } } /// <summary> /// Enumerates entries of EnC map. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> public static IEnumerable<EntityHandle> GetEditAndContinueMapEntries(this MetadataReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } for (int rid = 1; rid <= reader.EncMapTable.NumberOfRows; rid++) { yield return new EntityHandle(reader.EncMapTable.GetToken(rid)); } } /// <summary> /// Enumerate types that define one or more properties. /// </summary> /// <returns> /// The resulting sequence corresponds exactly to entries in PropertyMap table, /// i.e. n-th returned <see cref="TypeDefinitionHandle"/> is stored in n-th row of PropertyMap. /// </returns> public static IEnumerable<TypeDefinitionHandle> GetTypesWithProperties(this MetadataReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } for (int rid = 1; rid <= reader.PropertyMapTable.NumberOfRows; rid++) { yield return reader.PropertyMapTable.GetParentType(rid); } } /// <summary> /// Enumerate types that define one or more events. /// </summary> /// <returns> /// The resulting sequence corresponds exactly to entries in EventMap table, /// i.e. n-th returned <see cref="TypeDefinitionHandle"/> is stored in n-th row of EventMap. /// </returns> public static IEnumerable<TypeDefinitionHandle> GetTypesWithEvents(this MetadataReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } for (int rid = 1; rid <= reader.EventMapTable.NumberOfRows; rid++) { yield return reader.EventMapTable.GetParentType(rid); } } } }
using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Serialization.Objects; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Controllers { public sealed class AtomicConstrainedOperationsControllerTests : IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>> { private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext; private readonly OperationsFakers _fakers = new(); public AtomicConstrainedOperationsControllerTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext) { _testContext = testContext; testContext.UseController<CreateMusicTrackOperationsController>(); } [Fact] public async Task Can_create_resources_for_matching_resource_type() { // Arrange string newTitle1 = _fakers.MusicTrack.Generate().Title; string newTitle2 = _fakers.MusicTrack.Generate().Title; var requestBody = new { atomic__operations = new[] { new { op = "add", data = new { type = "musicTracks", attributes = new { title = newTitle1 } } }, new { op = "add", data = new { type = "musicTracks", attributes = new { title = newTitle2 } } } } }; const string route = "/operations/musicTracks/create"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.Should().HaveCount(2); } [Fact] public async Task Cannot_create_resource_for_mismatching_resource_type() { // Arrange var requestBody = new { atomic__operations = new[] { new { op = "add", data = new { type = "performers", attributes = new { } } } } }; const string route = "/operations/musicTracks/create"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Unsupported combination of operation code and resource type at this endpoint."); error.Detail.Should().Be("This endpoint can only be used to create resources of type 'musicTracks'."); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } [Fact] public async Task Cannot_update_resources_for_matching_resource_type() { // Arrange MusicTrack existingTrack = _fakers.MusicTrack.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.MusicTracks.Add(existingTrack); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new[] { new { op = "update", data = new { type = "musicTracks", id = existingTrack.StringId, attributes = new { } } } } }; const string route = "/operations/musicTracks/create"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Unsupported combination of operation code and resource type at this endpoint."); error.Detail.Should().Be("This endpoint can only be used to create resources of type 'musicTracks'."); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } [Fact] public async Task Cannot_add_to_ToMany_relationship_for_matching_resource_type() { // Arrange MusicTrack existingTrack = _fakers.MusicTrack.Generate(); Performer existingPerformer = _fakers.Performer.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingTrack, existingPerformer); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new[] { new { op = "add", @ref = new { type = "musicTracks", id = existingTrack.StringId, relationship = "performers" }, data = new[] { new { type = "performers", id = existingPerformer.StringId } } } } }; const string route = "/operations/musicTracks/create"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Unsupported combination of operation code and resource type at this endpoint."); error.Detail.Should().Be("This endpoint can only be used to create resources of type 'musicTracks'."); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elasticache-2015-02-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElastiCache.Model { /// <summary> /// Represents the output of a <i>PurchaseReservedCacheNodesOffering</i> action. /// </summary> public partial class ReservedCacheNode { private int? _cacheNodeCount; private string _cacheNodeType; private int? _duration; private double? _fixedPrice; private string _offeringType; private string _productDescription; private List<RecurringCharge> _recurringCharges = new List<RecurringCharge>(); private string _reservedCacheNodeId; private string _reservedCacheNodesOfferingId; private DateTime? _startTime; private string _state; private double? _usagePrice; /// <summary> /// Gets and sets the property CacheNodeCount. /// <para> /// The number of cache nodes that have been reserved. /// </para> /// </summary> public int CacheNodeCount { get { return this._cacheNodeCount.GetValueOrDefault(); } set { this._cacheNodeCount = value; } } // Check to see if CacheNodeCount property is set internal bool IsSetCacheNodeCount() { return this._cacheNodeCount.HasValue; } /// <summary> /// Gets and sets the property CacheNodeType. /// <para> /// The cache node type for the reserved cache nodes. /// </para> /// /// <para> /// Valid node types are as follows: /// </para> /// <ul> <li>General purpose: <ul> <li>Current generation: <code>cache.t2.micro</code>, /// <code>cache.t2.small</code>, <code>cache.t2.medium</code>, <code>cache.m3.medium</code>, /// <code>cache.m3.large</code>, <code>cache.m3.xlarge</code>, <code>cache.m3.2xlarge</code></li> /// <li>Previous generation: <code>cache.t1.micro</code>, <code>cache.m1.small</code>, /// <code>cache.m1.medium</code>, <code>cache.m1.large</code>, <code>cache.m1.xlarge</code></li> /// </ul></li> <li>Compute optimized: <code>cache.c1.xlarge</code></li> <li>Memory optimized /// <ul> <li>Current generation: <code>cache.r3.large</code>, <code>cache.r3.xlarge</code>, /// <code>cache.r3.2xlarge</code>, <code>cache.r3.4xlarge</code>, <code>cache.r3.8xlarge</code></li> /// <li>Previous generation: <code>cache.m2.xlarge</code>, <code>cache.m2.2xlarge</code>, /// <code>cache.m2.4xlarge</code></li> </ul></li> </ul> /// <para> /// <b>Notes:</b> /// </para> /// <ul> <li>All t2 instances are created in an Amazon Virtual Private Cloud (VPC).</li> /// <li>Redis backup/restore is not supported for t2 instances.</li> <li>Redis Append-only /// files (AOF) functionality is not supported for t1 or t2 instances.</li> </ul> /// <para> /// For a complete listing of cache node types and specifications, see <a href="http://aws.amazon.com/elasticache/details">Amazon /// ElastiCache Product Features and Details</a> and <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Memcached.html#CacheParameterGroups.Memcached.NodeSpecific">Cache /// Node Type-Specific Parameters for Memcached</a> or <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Redis.html#CacheParameterGroups.Redis.NodeSpecific">Cache /// Node Type-Specific Parameters for Redis</a>. /// </para> /// </summary> public string CacheNodeType { get { return this._cacheNodeType; } set { this._cacheNodeType = value; } } // Check to see if CacheNodeType property is set internal bool IsSetCacheNodeType() { return this._cacheNodeType != null; } /// <summary> /// Gets and sets the property Duration. /// <para> /// The duration of the reservation in seconds. /// </para> /// </summary> public int Duration { get { return this._duration.GetValueOrDefault(); } set { this._duration = value; } } // Check to see if Duration property is set internal bool IsSetDuration() { return this._duration.HasValue; } /// <summary> /// Gets and sets the property FixedPrice. /// <para> /// The fixed price charged for this reserved cache node. /// </para> /// </summary> public double FixedPrice { get { return this._fixedPrice.GetValueOrDefault(); } set { this._fixedPrice = value; } } // Check to see if FixedPrice property is set internal bool IsSetFixedPrice() { return this._fixedPrice.HasValue; } /// <summary> /// Gets and sets the property OfferingType. /// <para> /// The offering type of this reserved cache node. /// </para> /// </summary> public string OfferingType { get { return this._offeringType; } set { this._offeringType = value; } } // Check to see if OfferingType property is set internal bool IsSetOfferingType() { return this._offeringType != null; } /// <summary> /// Gets and sets the property ProductDescription. /// <para> /// The description of the reserved cache node. /// </para> /// </summary> public string ProductDescription { get { return this._productDescription; } set { this._productDescription = value; } } // Check to see if ProductDescription property is set internal bool IsSetProductDescription() { return this._productDescription != null; } /// <summary> /// Gets and sets the property RecurringCharges. /// <para> /// The recurring price charged to run this reserved cache node. /// </para> /// </summary> public List<RecurringCharge> RecurringCharges { get { return this._recurringCharges; } set { this._recurringCharges = value; } } // Check to see if RecurringCharges property is set internal bool IsSetRecurringCharges() { return this._recurringCharges != null && this._recurringCharges.Count > 0; } /// <summary> /// Gets and sets the property ReservedCacheNodeId. /// <para> /// The unique identifier for the reservation. /// </para> /// </summary> public string ReservedCacheNodeId { get { return this._reservedCacheNodeId; } set { this._reservedCacheNodeId = value; } } // Check to see if ReservedCacheNodeId property is set internal bool IsSetReservedCacheNodeId() { return this._reservedCacheNodeId != null; } /// <summary> /// Gets and sets the property ReservedCacheNodesOfferingId. /// <para> /// The offering identifier. /// </para> /// </summary> public string ReservedCacheNodesOfferingId { get { return this._reservedCacheNodesOfferingId; } set { this._reservedCacheNodesOfferingId = value; } } // Check to see if ReservedCacheNodesOfferingId property is set internal bool IsSetReservedCacheNodesOfferingId() { return this._reservedCacheNodesOfferingId != null; } /// <summary> /// Gets and sets the property StartTime. /// <para> /// The time the reservation started. /// </para> /// </summary> public DateTime StartTime { get { return this._startTime.GetValueOrDefault(); } set { this._startTime = value; } } // Check to see if StartTime property is set internal bool IsSetStartTime() { return this._startTime.HasValue; } /// <summary> /// Gets and sets the property State. /// <para> /// The state of the reserved cache node. /// </para> /// </summary> public string State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property UsagePrice. /// <para> /// The hourly price charged for this reserved cache node. /// </para> /// </summary> public double UsagePrice { get { return this._usagePrice.GetValueOrDefault(); } set { this._usagePrice = value; } } // Check to see if UsagePrice property is set internal bool IsSetUsagePrice() { return this._usagePrice.HasValue; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Security; using System.Collections; using System.IO; using System.Reflection.Emit; /* * Limitations: * The ExceptionDataContract utilizes the ClassDataConract class in order to deserialize Exceptions with the ability to fill private fields. * For the ClassDataContract to deserialize private fields, the name of the private field must exactly match the name of the field in xml. * However the thick framework does not serialize exceptions using private field names. The thick framework is able to bypass using private field names because it has a mapping for each Exception * made possible by implementing ISerializable. The mapping of every single .Net Exception Private Field to the Thick Framework serialized name is too much data for the ExceptionDataContract * to hold. * This class creates a mapping for the System.Exception private fields, which are considered the most important fields for an Exception. * Therefore the only private fields that are supported for serialization/deserialization are those declared in System.Exception. * * For the serialization of classes derived from System.Exception all public properties are included into the xml out. * There is no support for private properties other than those in System.Exception. * In order for the property to be reset on deserialization it must implement a setter. * Author: t-jicamp */ namespace System.Runtime.Serialization { internal sealed class ExceptionDataContract : DataContract { private XmlDictionaryString[] _contractNamespaces; private XmlDictionaryString[] _memberNames; private XmlDictionaryString[] _memberNamespaces; [SecurityCritical] private ExceptionDataContractCriticalHelper _helper; [SecuritySafeCritical] public ExceptionDataContract() : base(new ExceptionDataContractCriticalHelper()) { _helper = base.Helper as ExceptionDataContractCriticalHelper; _contractNamespaces = _helper.ContractNamespaces; _memberNames = _helper.MemberNames; _memberNamespaces = _helper.MemberNamespaces; } [SecuritySafeCritical] public ExceptionDataContract(Type type) : base(new ExceptionDataContractCriticalHelper(type)) { _helper = base.Helper as ExceptionDataContractCriticalHelper; _contractNamespaces = _helper.ContractNamespaces; _memberNames = _helper.MemberNames; _memberNamespaces = _helper.MemberNamespaces; } public List<DataMember> Members { [SecuritySafeCritical] get { return _helper.Members; } } internal override bool CanContainReferences //inherited as internal { get { return true; } } public static Dictionary<string, string> EssentialExceptionFields { [SecuritySafeCritical] get { return ExceptionDataContractCriticalHelper.EssentialExceptionFields; } } public override Dictionary<XmlQualifiedName, DataContract> KnownDataContracts //inherited as internal { [SecuritySafeCritical] get { return _helper.KnownDataContracts; } [SecurityCritical] set { _helper.KnownDataContracts = value; } } public XmlDictionaryString[] ContractNamespaces { get { return _contractNamespaces; } set { _contractNamespaces = value; } } public XmlDictionaryString[] MemberNames { get { return _memberNames; } set { _memberNames = value; } } public XmlDictionaryString[] MemberNamespaces { get { return _memberNamespaces; } set { _memberNamespaces = value; } } [SecurityCritical] private class ExceptionDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private XmlDictionaryString[] _contractNamespaces; private XmlDictionaryString[] _memberNames; private XmlDictionaryString[] _memberNamespaces; private ExceptionDataContract _baseContract; private List<DataMember> _members; private bool _hasDataContract; private Dictionary<XmlQualifiedName, DataContract> _knownDataContracts; //Contains the essential fields to serialize an Exception. Not all fields are serialized in an Exception. Some private fields //need to be serialized, but then again some need to be left out. This will keep track of which ones need to be serialized //And also their display name for serialization which differs from their declared name. private static readonly Dictionary<string, string> s_essentialExceptionFields = CreateExceptionFields(); /* * The ordering of this dictionary is important due to the nature of the ClassDataContract that ExceptionDataContract depends on. * In order for the ClassDataContract to correctly set the values for the members of the underlying class, it must have a list * of members in the same order as the xml document it is reading. These members are created in the ImportDataMembers() method, * and their ordering comes from this dictionary. * * This dictionary is in the order that the Full Framework declares System.Exceptions members. This order is established * in the Full Framework version of System.Exception's ISerializable interface. */ private static Dictionary<string, string> CreateExceptionFields() { var essentialExceptionFields = new Dictionary<string, string>(12); essentialExceptionFields.Add("_className", "ClassName"); essentialExceptionFields.Add("_message", "Message"); essentialExceptionFields.Add("_data", "Data"); essentialExceptionFields.Add("_innerException", "InnerException"); essentialExceptionFields.Add("_helpURL", "HelpURL"); essentialExceptionFields.Add("_stackTraceString", "StackTraceString"); essentialExceptionFields.Add("_remoteStackTraceString", "RemoteStackTraceString"); essentialExceptionFields.Add("_remoteStackIndex", "RemoteStackIndex"); essentialExceptionFields.Add("_exceptionMethodString", "ExceptionMethod"); essentialExceptionFields.Add("_HResult", "HResult"); essentialExceptionFields.Add("_source", "Source"); essentialExceptionFields.Add("_watsonBuckets", "WatsonBuckets"); return essentialExceptionFields; } public ExceptionDataContractCriticalHelper() { IsValueType = false; } public ExceptionDataContractCriticalHelper(Type type) : base(type) { this.StableName = DataContract.GetStableName(type, out _hasDataContract); Type baseType = Globals.TypeOfException; this.IsValueType = type.GetTypeInfo().IsValueType; if (baseType != null && baseType != Globals.TypeOfObject && type != Globals.TypeOfException) { DataContract baseContract = DataContract.GetDataContract(baseType); this.BaseContract = baseContract as ExceptionDataContract; } else { this.BaseContract = null; } ImportDataMembers(); ImportKnownTypes(); XmlDictionary dictionary = new XmlDictionary(2 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = dictionary.Add(StableName.Namespace); int baseContractCount = 0; if (BaseContract == null) { _memberNames = new XmlDictionaryString[Members.Count]; _memberNamespaces = new XmlDictionaryString[Members.Count]; _contractNamespaces = new XmlDictionaryString[1]; } else { _memberNames = new XmlDictionaryString[Members.Count]; _memberNamespaces = new XmlDictionaryString[Members.Count]; baseContractCount = BaseContract._contractNamespaces.Length; _contractNamespaces = new XmlDictionaryString[1 + baseContractCount]; Array.Copy(BaseContract._contractNamespaces, 0, _contractNamespaces, 0, baseContractCount); } _contractNamespaces[baseContractCount] = Namespace; for (int i = 0; i < Members.Count; i++) { _memberNames[i] = dictionary.Add(Members[i].Name); _memberNamespaces[i] = Namespace; } } public ExceptionDataContract BaseContract { get { return _baseContract; } set { _baseContract = value; } } public static Dictionary<string, string> EssentialExceptionFields { get { return s_essentialExceptionFields; } } internal override Dictionary<XmlQualifiedName, DataContract> KnownDataContracts // inherited as internal { [SecurityCritical] get { if (_knownDataContracts == null) _knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>(); return _knownDataContracts; } [SecurityCritical] set { /* do nothing */ } } public List<DataMember> Members { get { return _members; } } public XmlDictionaryString[] ContractNamespaces { get { return _contractNamespaces; } set { _contractNamespaces = value; } } public XmlDictionaryString[] MemberNames { get { return _memberNames; } set { _memberNames = value; } } public XmlDictionaryString[] MemberNamespaces { get { return _memberNamespaces; } set { _memberNamespaces = value; } } private void ImportDataMembers() { /* * DataMembers are used for the deserialization of Exceptions. * DataMembers represent the fields and/or settable properties that the underlying Exception has. * The DataMembers are stored and eventually passed to a ClassDataContract created from the underlying Exception. * The ClassDataContract uses the list of DataMembers to set the fields/properties for the newly created Exception. * If a DataMember is a property it must be settable. */ Type type = this.UnderlyingType; if (type == Globals.TypeOfException) { ImportSystemExceptionDataMembers(); //System.Exception must be handled specially because it is the only exception that imports private fields. return; } List<DataMember> tempMembers; if (BaseContract != null) { tempMembers = new List<DataMember>(BaseContract.Members); //Don't set tempMembers = BaseContract.Members and then start adding, because this alters the base's reference. } else { tempMembers = new List<DataMember>(); } Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>(); MemberInfo[] memberInfos; memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); for (int i = 0; i < memberInfos.Length; i++) { MemberInfo member = memberInfos[i]; //Public properties with set methods can be deserialized with the ClassDataContract PropertyInfo publicProperty = member as PropertyInfo; if (publicProperty != null && publicProperty.SetMethod != null) { DataMember memberContract = new DataMember(member); memberContract.Name = DataContract.EncodeLocalName(member.Name); memberContract.IsRequired = false; memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); if (HasNoConflictWithBaseMembers(memberContract)) { CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } } Interlocked.MemoryBarrier(); _members = tempMembers; } private void ImportSystemExceptionDataMembers() { /* * The data members imported for System.Exception are private fields. They must be treated specially. * The EssentialExceptionFields Dictionary keeps track of which private fields needs to be imported, and also the name that they should be serialized with. */ Type type = this.UnderlyingType; List<DataMember> tempMembers; tempMembers = new List<DataMember>(); Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>(); foreach (string fieldInfoName in EssentialExceptionFields.Keys) { FieldInfo member = type.GetField(fieldInfoName, BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance); if (CanSerializeMember(member)) { DataMember memberContract = new DataMember(member); memberContract.Name = DataContract.EncodeLocalName(member.Name); memberContract.IsRequired = false; memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } Interlocked.MemoryBarrier(); _members = tempMembers; } private void ImportKnownTypes() { DataContract dataDataContract = GetDataContract(typeof(IDictionary<object, object>)); this.KnownDataContracts.Add(dataDataContract.StableName, dataDataContract); } private bool HasNoConflictWithBaseMembers(DataMember memberContract) { //Don't add redundant members, this can happen if a property overrides it's base class implementation. Because the overridden property will appear as "declared" in that type. foreach (DataMember dm in BaseContract.Members) { if (dm.Name.Equals(memberContract.Name)) { return false; } } return true; } } private static bool CanSerializeMember(FieldInfo field) { return field != null && field.FieldType != Globals.TypeOfObject; // Don't really know how to serialize plain System.Object instance } private void WriteExceptionValue(XmlWriterDelegator writer, object value, XmlObjectSerializerWriteContext context) { /* * Every private field present in System.Exception that is serialized in the thick framework is also serialized in this method. * For classes that inherit from System.Exception all public properties are serialized. * The reason that the Members property is not used here to get the properties to serialize is because Members contains only the properties with setters. */ Type type = value.GetType(); writer.WriteXmlnsAttribute("x", new XmlDictionary(1).Add(Globals.SchemaNamespace)); WriteSystemExceptionRequiredValues(writer, value, context); PropertyInfo[] props = type.GetProperties(); foreach (PropertyInfo prop in props) { //Properties in System.Exception are handled in the call to WriteSystemExceptionRequiredValues, we don't want to repeat these properties. if (PropertyIsSystemExceptionProperty(prop)) continue; writer.WriteStartElement(prop.Name, ""); DataContract propDataContract = context.GetDataContract(prop.PropertyType); if (prop.GetValue(value) != null && propDataContract != null && !TryCheckIfNoCountIDictionary(prop.PropertyType, prop.GetValue(value))) { if (!TryWritePrimitive(prop.PropertyType, prop.GetValue(value), writer, context)) { writer.WriteAttributeString(Globals.XsiPrefix, "type", null, "a:" + propDataContract.StableName.Name); writer.WriteXmlnsAttribute("a", new XmlDictionary(1).Add(propDataContract.StableName.Namespace)); context.SerializeWithoutXsiType(propDataContract, writer, prop.GetValue(value), prop.PropertyType.TypeHandle); } } else { writer.WriteAttributeString(Globals.XsiPrefix, "nil", null, "true"); } writer.WriteEndElement(); } } private void WriteSystemExceptionRequiredValues(XmlWriterDelegator writer, object value, XmlObjectSerializerWriteContext context) { Dictionary<string, object> exceptionFields = GetExceptionFieldValues((Exception)value); object val; foreach (string key in exceptionFields.Keys) { if (!exceptionFields.TryGetValue(key, out val)) continue; Type fieldType; FieldInfo FieldFind = Globals.TypeOfException.GetField(key, BindingFlags.Instance | BindingFlags.NonPublic); if (FieldFind == null) { val = null; // need to nullify because the private fields that are necessary in Exception have changed. fieldType = typeof(int); // can be any type, it doesn't matter. field type will be used to recover a contract, but the type won't be utilized. } else fieldType = FieldFind.FieldType; string fieldDisplayName; if (EssentialExceptionFields.TryGetValue(key, out fieldDisplayName)) writer.WriteStartElement(fieldDisplayName, ""); else writer.WriteStartElement(key, ""); DataContract fieldDataContract = context.GetDataContract(fieldType); if (val != null && fieldDataContract != null && !TryCheckIfNoCountIDictionary(fieldType, val)) { if (!TryWritePrimitive(fieldType, val, writer, context)) { writer.WriteAttributeString(Globals.XsiPrefix, "type", null, "a:" + fieldDataContract.StableName.Name); writer.WriteXmlnsAttribute("a", new XmlDictionary(1).Add(fieldDataContract.StableName.Namespace)); fieldDataContract.WriteXmlValue(writer, val, context); } } else { writer.WriteAttributeString(Globals.XsiPrefix, "nil", null, "true"); } writer.WriteEndElement(); } } private bool PropertyIsSystemExceptionProperty(PropertyInfo prop) { PropertyInfo[] props = Globals.TypeOfException.GetProperties(); foreach (PropertyInfo propInfo in props) { if (propInfo.Name.Equals(prop.Name)) { return true; } } return false; } private static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable) { DataMember existingMemberContract; if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract)) { Type declaringType = memberContract.MemberInfo.DeclaringType; DataContract.ThrowInvalidDataContractException( SR.Format(SR.DupMemberName, existingMemberContract.MemberInfo.Name, memberContract.MemberInfo.Name, DataContract.GetClrTypeFullName(declaringType), memberContract.Name), declaringType); } memberNamesTable.Add(memberContract.Name, memberContract); members.Add(memberContract); } [SecuritySafeCritical] private Dictionary<string, object> GetExceptionFieldValues(Exception value) { // Obtain the unoverridden version of Message Type exceptionType = Globals.TypeOfException; PropertyInfo messageProperty = exceptionType.GetProperty("Message"); MethodInfo messageGetter = messageProperty.GetMethod; #if !NET_NATIVE DynamicMethod baseMessageImpl = new DynamicMethod("NonVirtual_Message", typeof(string), new Type[] { Globals.TypeOfException }, Globals.TypeOfException); ILGenerator gen = baseMessageImpl.GetILGenerator(); gen.Emit(OpCodes.Ldarg, messageGetter.GetParameters().Length); gen.EmitCall(OpCodes.Call, messageGetter, null); gen.Emit(OpCodes.Ret); string messageValue = (string)baseMessageImpl.Invoke(null, new object[] { value }); #else string messageValue = string.Empty; #endif // Populate the values for the necessary System.Exception private fields. Dictionary<string, object> fieldToValueDictionary = new Dictionary<string, object>(); fieldToValueDictionary.Add("_className", value.GetType().ToString()); fieldToValueDictionary.Add("_message", messageValue); //Thick framework retrieves the System.Exception implementation of message fieldToValueDictionary.Add("_data", value.Data); fieldToValueDictionary.Add("_innerException", value.InnerException); fieldToValueDictionary.Add("_helpURL", value.HelpLink); fieldToValueDictionary.Add("_stackTraceString", value.StackTrace); fieldToValueDictionary.Add("_remoteStackTraceString", null); fieldToValueDictionary.Add("_remoteStackIndex", 0); fieldToValueDictionary.Add("_exceptionMethodString", null); fieldToValueDictionary.Add("_HResult", value.HResult); fieldToValueDictionary.Add("_source", null); //value.source caused transparency error on build. fieldToValueDictionary.Add("_watsonBuckets", null); return fieldToValueDictionary; } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { Type type = obj.GetType(); if (!(typeof(Exception).IsAssignableFrom(type))) { throw new InvalidDataContractException("Cannot use ExceptionDataContract to serialize object with type: " + type); } WriteExceptionValue(xmlWriter, obj, context); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { XmlReaderDelegator xmlDelegator = ParseReaderString(xmlReader); ClassDataContract cdc = new ClassDataContract(this.UnderlyingType); // The Class Data Contract created from the underlying exception type uses custom imported members that are // created in this classes constructor. Here we clear out the Class Data Contract's default members and insert our own. cdc.Members.Clear(); foreach (DataMember dm in this.Members) { cdc.Members.Add(dm); } cdc.MemberNames = _memberNames; cdc.ContractNamespaces = _contractNamespaces; cdc.MemberNamespaces = _memberNamespaces; object obj = cdc.ReadXmlValue(xmlDelegator, context); if (context != null) context.AddNewObject(obj); return obj; } private bool TryWritePrimitive(Type type, object value, XmlWriterDelegator writer, XmlObjectSerializerWriteContext context) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; writer.WriteAttributeString(Globals.XsiPrefix, "type", null, "x:" + primitiveContract.StableName.Name); primitiveContract.WriteXmlValue(writer, value, context); return true; } private static bool TryCheckIfNoCountIDictionary(Type type, object value) { if (value == null) return true; if (type == Globals.TypeOfIDictionary) { IDictionary tempDictImitation = (IDictionary)value; return (tempDictImitation.Count == 0); } return false; } /* * The reason this function exists is to provide compatibility for ExceptionDataContract to utilize ClassDataContract for deserialization. * In order for ExceptionDataContract to deserialize using ClassDataContract the xml elements corresponding to private fields need * to have their name replaced with the name of the private field they map to. * Example: Message ---replaced to--> _message * * Currently this method utilizes a custom created class entitled ExceptionXmlParser that sits alongside the ExceptionDataContract * The ExceptionXmlParser reads the xml string passed to it exchanges any element names that are presented in the name map * in its constructor. * * The ExceptionXmlParser also gives each nested element the proper namespace for the given exception being deserialized. * The ClassDataContract needs an exact match on the element name and the namespace in order to deserialize the value, because not all serialization * explicitly inserts the xmlnamespace of nested objects, the exception xml parser handles this. */ private XmlReaderDelegator ParseReaderString(XmlReaderDelegator xmlReader) { //The reference to the xmlReader passed into this method should not be modified. //The call to ReadOuterXml advances the xmlReader to the next object if the exception being parsed is a nested object of another class. //When the call to ReadXmlValue that called this method returns, it is possible that the 'xmlReader' will still be used by the calling datacontract. string EntryXmlString = xmlReader.UnderlyingReader.ReadOuterXml(); string result = ExceptionXmlParser.ParseExceptionXmlForClassDataContract(ReverseDictionary(EssentialExceptionFields), this.Namespace.ToString(), EntryXmlString); byte[] byteBuffer = Encoding.UTF8.GetBytes(result); XmlReaderDelegator xmlDelegator = new XmlReaderDelegator(XmlDictionaryReader.CreateTextReader(byteBuffer, XmlDictionaryReaderQuotas.Max)); xmlDelegator.MoveToContent(); return xmlDelegator; } private static Dictionary<string, string> ReverseDictionary(Dictionary<string, string> inDict) { Dictionary<string, string> mapDict = new Dictionary<string, string>(); foreach (string key in inDict.Keys) { string valString; valString = inDict[key]; mapDict.Add(valString, key); } return mapDict; } } /* * This class is necessary to create a parsed xml document to utilize the ClassDataContract. * The ExceptionXmlParser inserts necessary xmlns declarations for exception members, the namespace is necessary for ClassDataContract to identify * the xml members as members of the Exception object. * This ExceptionXmlParser also performs the transformation of the serialized names of exception private fields to the actual field names. */ internal sealed class ExceptionXmlParser : IDisposable { private XmlReader _reader; private MemoryStream _ms; private StreamWriter _sw; private StringBuilder _sb; private string _exceptionNamespace; private Dictionary<string, string> _elementNamesToMap; private bool _disposed; private ExceptionXmlParser(Dictionary<string, string> dictMap, string exceptionNamespace) { // dictMap passes in the dictionary that is used for mapping field names to their serialized representations. if (dictMap == null) { throw new ArgumentNullException(nameof(dictMap)); } if (exceptionNamespace == null) { throw new ArgumentNullException(nameof(exceptionNamespace)); } _elementNamesToMap = dictMap; _exceptionNamespace = exceptionNamespace; _sb = new StringBuilder(); _ms = new MemoryStream(); _sw = new StreamWriter(_ms); _disposed = false; } public static string ParseExceptionXmlForClassDataContract(Dictionary<string, string> dictMap, string exceptionNamespace, string stringToParse) { using (ExceptionXmlParser parser = new ExceptionXmlParser(dictMap, exceptionNamespace)) { return parser.ParseExceptionXml(stringToParse); } } private string ParseExceptionXml(string stringToParse) { _sw.Write(stringToParse); _sw.Flush(); _ms.Position = 0; _reader = XmlReader.Create(_ms); return ParseRootElement(); } public void Dispose() { if (!_disposed) { _ms.Dispose(); _ms = null; _sw.Dispose(); _sw = null; _reader.Dispose(); _reader = null; _disposed = true; } } private string ParseRootElement() { _reader.MoveToContent(); string elementName = _reader.Name; OpenRootElement(elementName); if (_reader.IsEmptyElement) { _sb.Append("/>"); // close root element. } else { HandleRootElementsContents(); CloseRootElement(elementName); } return _sb.ToString(); } private void ParseChildElement() { string elementName = _reader.Name; elementName = OpenChildElement(elementName); if (_reader.IsEmptyElement) { InlineCloser(); } else { _sb.Append(">"); HandleChildElementContent(); CloseElement(elementName); } } private string WriteElementNameWithBracketAndMapping(string name) { _sb.Append("<"); name = SwitchElementNameIfNecessary(name); _sb.Append(name); return name; } private string WriteExactElementNameWithBracket(string name) { _sb.AppendFormat("<{0}", name); return name; } private string SwitchElementNameIfNecessary(string name) { string newName; if (_elementNamesToMap.TryGetValue(name, out newName)) { return newName; } return name; } private void InlineCloser() { _sb.Append("/>"); Read(); } private void OpenRootElement(string elementName) { WriteElementNameWithBracketAndMapping(elementName); for (int i = 0; i < _reader.AttributeCount; i++) { _reader.MoveToNextAttribute(); WriteAttribute(_reader.Name, _reader.Value); } _reader.MoveToElement(); } private void CloseRootElement(string ElementName) { _sb.AppendFormat("</{0}>", ElementName); } private void HandleRootElementsContents() { _sb.Append(">"); Read(); while (_reader.NodeType == XmlNodeType.Element) { ParseChildElement(); } } private string OpenChildElement(string elementName) { elementName = WriteElementNameWithBracketAndMapping(elementName); // the immediate child elements must have an xmlns attribute with namespace of the parent exception. WriteAttribute("xmlns", _exceptionNamespace); for (int i = 0; i < _reader.AttributeCount; i++) { _reader.MoveToNextAttribute(); if (_reader.Name.Equals("xmlns")) continue; WriteAttribute(_reader.Name, _reader.Value); } _reader.MoveToElement(); return elementName; } private void CloseElement(string ElementName) { _sb.AppendFormat("</{0}>", ElementName); } private void CopyXmlFromCurrentNode() { string elementName = _reader.Name; // Start with the element OpenExactElement(elementName); // Handle an empty element if (_reader.IsEmptyElement) { InlineCloser(); return; } _sb.Append(">"); // Append all children elements Read(); while (_reader.NodeType == XmlNodeType.Element) { CopyXmlFromCurrentNode(); // Recursive call } if (_reader.NodeType == XmlNodeType.Text) { AppendEscapedElementString(_reader.Value); Read(); } // Finish with the element CloseExactElement(elementName); } private void OpenExactElement(string elementName) { WriteExactElementNameWithBracket(elementName); for (int i = 0; i < _reader.AttributeCount; i++) { _reader.MoveToNextAttribute(); WriteAttribute(_reader.Name, _reader.Value); } _reader.MoveToElement(); } private void CloseExactElement(string elementName) { _sb.AppendFormat("</{0}>", elementName); Read(); } private void WriteAttribute(string name, string value) { _sb.AppendFormat(" {0}=\"{1}\"", name, value); } private void HandleChildElementContent() { Read(); if (_reader.NodeType == XmlNodeType.Text) { AppendEscapedElementString(_reader.Value); Read(); _reader.ReadEndElement(); } else { while (_reader.NodeType != XmlNodeType.EndElement) { CopyXmlFromCurrentNode(); } _reader.ReadEndElement(); } } private void Read() { //There is no reason the reader should return false for properly serialized xml. if (!_reader.Read()) { throw new InvalidOperationException(); } } private void AppendEscapedElementString(string stringToEscape) { foreach (char ch in stringToEscape) { switch (ch) { case '<': _sb.Append("&lt;"); break; case '>': _sb.Append("&gt;"); break; case '&': _sb.Append("&amp;"); break; default: // We didn't escape ', ", or hex chars as there was no valid use case, // consider to escape them if necessary. _sb.Append(ch); break; } } } } }
using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Search { /* * 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using DoubleField = DoubleField; using Field = Field; using FieldType = FieldType; using IndexReader = Lucene.Net.Index.IndexReader; using Int64Field = Int64Field; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MultiFields = Lucene.Net.Index.MultiFields; using NumericUtils = Lucene.Net.Util.NumericUtils; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using SlowCompositeReaderWrapper = Lucene.Net.Index.SlowCompositeReaderWrapper; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; using TestNumericUtils = Lucene.Net.Util.TestNumericUtils; // NaN arrays using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestNumericRangeQuery64 : LuceneTestCase { // distance of entries private static long distance; // shift the starting of the values to the left, to also have negative values: private static readonly long startOffset = -1L << 31; // number of docs to generate for testing private static int noDocs; private static Directory directory = null; private static IndexReader reader = null; private static IndexSearcher searcher = null; /// <summary> /// LUCENENET specific /// Is non-static because NewIndexWriterConfig is no longer static. /// </summary> [OneTimeSetUp] public override void BeforeClass() { base.BeforeClass(); noDocs = AtLeast(4096); distance = (1L << 60) / noDocs; directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(TestUtil.NextInt32(Random, 100, 1000)).SetMergePolicy(NewLogMergePolicy())); FieldType storedLong = new FieldType(Int64Field.TYPE_NOT_STORED); storedLong.IsStored = true; storedLong.Freeze(); FieldType storedLong8 = new FieldType(storedLong); storedLong8.NumericPrecisionStep = 8; FieldType storedLong4 = new FieldType(storedLong); storedLong4.NumericPrecisionStep = 4; FieldType storedLong6 = new FieldType(storedLong); storedLong6.NumericPrecisionStep = 6; FieldType storedLong2 = new FieldType(storedLong); storedLong2.NumericPrecisionStep = 2; FieldType storedLongNone = new FieldType(storedLong); storedLongNone.NumericPrecisionStep = int.MaxValue; FieldType unstoredLong = Int64Field.TYPE_NOT_STORED; FieldType unstoredLong8 = new FieldType(unstoredLong); unstoredLong8.NumericPrecisionStep = 8; FieldType unstoredLong6 = new FieldType(unstoredLong); unstoredLong6.NumericPrecisionStep = 6; FieldType unstoredLong4 = new FieldType(unstoredLong); unstoredLong4.NumericPrecisionStep = 4; FieldType unstoredLong2 = new FieldType(unstoredLong); unstoredLong2.NumericPrecisionStep = 2; Int64Field field8 = new Int64Field("field8", 0L, storedLong8), field6 = new Int64Field("field6", 0L, storedLong6), field4 = new Int64Field("field4", 0L, storedLong4), field2 = new Int64Field("field2", 0L, storedLong2), fieldNoTrie = new Int64Field("field" + int.MaxValue, 0L, storedLongNone), ascfield8 = new Int64Field("ascfield8", 0L, unstoredLong8), ascfield6 = new Int64Field("ascfield6", 0L, unstoredLong6), ascfield4 = new Int64Field("ascfield4", 0L, unstoredLong4), ascfield2 = new Int64Field("ascfield2", 0L, unstoredLong2); Document doc = new Document(); // add fields, that have a distance to test general functionality doc.Add(field8); doc.Add(field6); doc.Add(field4); doc.Add(field2); doc.Add(fieldNoTrie); // add ascending fields with a distance of 1, beginning at -noDocs/2 to test the correct splitting of range and inclusive/exclusive doc.Add(ascfield8); doc.Add(ascfield6); doc.Add(ascfield4); doc.Add(ascfield2); // Add a series of noDocs docs with increasing long values, by updating the fields for (int l = 0; l < noDocs; l++) { long val = distance * l + startOffset; field8.SetInt64Value(val); field6.SetInt64Value(val); field4.SetInt64Value(val); field2.SetInt64Value(val); fieldNoTrie.SetInt64Value(val); val = l - (noDocs / 2); ascfield8.SetInt64Value(val); ascfield6.SetInt64Value(val); ascfield4.SetInt64Value(val); ascfield2.SetInt64Value(val); writer.AddDocument(doc); } reader = writer.GetReader(); searcher = NewSearcher(reader); writer.Dispose(); } [OneTimeTearDown] public override void AfterClass() { searcher = null; reader.Dispose(); reader = null; directory.Dispose(); directory = null; base.AfterClass(); } [SetUp] public override void SetUp() { base.SetUp(); // set the theoretical maximum term count for 8bit (see docs for the number) // super.tearDown will restore the default BooleanQuery.MaxClauseCount = 7 * 255 * 2 + 255; } /// <summary> /// test for constant score + boolean query + filter, the other tests only use the constant score mode </summary> private void TestRange(int precisionStep) { string field = "field" + precisionStep; int count = 3000; long lower = (distance * 3 / 2) + startOffset, upper = lower + count * distance + (distance / 3); NumericRangeQuery<long> q = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, upper, true, true); NumericRangeFilter<long> f = NumericRangeFilter.NewInt64Range(field, precisionStep, lower, upper, true, true); for (sbyte i = 0; i < 3; i++) { TopDocs topDocs; string type; switch (i) { case 0: type = " (constant score filter rewrite)"; q.MultiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE; topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER); break; case 1: type = " (constant score boolean rewrite)"; q.MultiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE; topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER); break; case 2: type = " (filter)"; topDocs = searcher.Search(new MatchAllDocsQuery(), f, noDocs, Sort.INDEXORDER); break; default: return; } ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(count, sd.Length, "Score doc count" + type); Document doc = searcher.Doc(sd[0].Doc); Assert.AreEqual(2 * distance + startOffset, doc.GetField(field).GetInt64Value().Value, "First doc" + type); doc = searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((1 + count) * distance + startOffset, doc.GetField(field).GetInt64Value().Value, "Last doc" + type); } } [Test] public virtual void TestRange_8bit() { TestRange(8); } [Test] public virtual void TestRange_6bit() { TestRange(6); } [Test] public virtual void TestRange_4bit() { TestRange(4); } [Test] public virtual void TestRange_2bit() { TestRange(2); } [Test] public virtual void TestInverseRange() { AtomicReaderContext context = (AtomicReaderContext)SlowCompositeReaderWrapper.Wrap(searcher.IndexReader).Context; NumericRangeFilter<long> f = NumericRangeFilter.NewInt64Range("field8", 8, 1000L, -1000L, true, true); Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A inverse range should return the null instance"); f = NumericRangeFilter.NewInt64Range("field8", 8, long.MaxValue, null, false, false); Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A exclusive range starting with Long.MAX_VALUE should return the null instance"); f = NumericRangeFilter.NewInt64Range("field8", 8, null, long.MinValue, false, false); Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A exclusive range ending with Long.MIN_VALUE should return the null instance"); } [Test] public virtual void TestOneMatchQuery() { NumericRangeQuery<long> q = NumericRangeQuery.NewInt64Range("ascfield8", 8, 1000L, 1000L, true, true); TopDocs topDocs = searcher.Search(q, noDocs); ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(1, sd.Length, "Score doc count"); } private void TestLeftOpenRange(int precisionStep) { string field = "field" + precisionStep; int count = 3000; long upper = (count - 1) * distance + (distance / 3) + startOffset; NumericRangeQuery<long> q = NumericRangeQuery.NewInt64Range(field, precisionStep, null, upper, true, true); TopDocs topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER); ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(count, sd.Length, "Score doc count"); Document doc = searcher.Doc(sd[0].Doc); Assert.AreEqual(startOffset, doc.GetField(field).GetInt64Value().Value, "First doc"); doc = searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((count - 1) * distance + startOffset, doc.GetField(field).GetInt64Value().Value, "Last doc"); q = NumericRangeQuery.NewInt64Range(field, precisionStep, null, upper, false, true); topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER); sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(count, sd.Length, "Score doc count"); doc = searcher.Doc(sd[0].Doc); Assert.AreEqual(startOffset, doc.GetField(field).GetInt64Value().Value, "First doc"); doc = searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((count - 1) * distance + startOffset, doc.GetField(field).GetInt64Value().Value, "Last doc"); } [Test] public virtual void TestLeftOpenRange_8bit() { TestLeftOpenRange(8); } [Test] public virtual void TestLeftOpenRange_6bit() { TestLeftOpenRange(6); } [Test] public virtual void TestLeftOpenRange_4bit() { TestLeftOpenRange(4); } [Test] public virtual void TestLeftOpenRange_2bit() { TestLeftOpenRange(2); } private void TestRightOpenRange(int precisionStep) { string field = "field" + precisionStep; int count = 3000; long lower = (count - 1) * distance + (distance / 3) + startOffset; NumericRangeQuery<long> q = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, null, true, true); TopDocs topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER); ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(noDocs - count, sd.Length, "Score doc count"); Document doc = searcher.Doc(sd[0].Doc); Assert.AreEqual(count * distance + startOffset, doc.GetField(field).GetInt64Value().Value, "First doc"); doc = searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((noDocs - 1) * distance + startOffset, doc.GetField(field).GetInt64Value().Value, "Last doc"); q = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, null, true, false); topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER); sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(noDocs - count, sd.Length, "Score doc count"); doc = searcher.Doc(sd[0].Doc); Assert.AreEqual(count * distance + startOffset, doc.GetField(field).GetInt64Value().Value, "First doc"); doc = searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((noDocs - 1) * distance + startOffset, doc.GetField(field).GetInt64Value().Value, "Last doc"); } [Test] public virtual void TestRightOpenRange_8bit() { TestRightOpenRange(8); } [Test] public virtual void TestRightOpenRange_6bit() { TestRightOpenRange(6); } [Test] public virtual void TestRightOpenRange_4bit() { TestRightOpenRange(4); } [Test] public virtual void TestRightOpenRange_2bit() { TestRightOpenRange(2); } [Test] public virtual void TestInfiniteValues() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document doc = new Document(); doc.Add(new DoubleField("double", double.NegativeInfinity, Field.Store.NO)); doc.Add(new Int64Field("long", long.MinValue, Field.Store.NO)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleField("double", double.PositiveInfinity, Field.Store.NO)); doc.Add(new Int64Field("long", long.MaxValue, Field.Store.NO)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleField("double", 0.0, Field.Store.NO)); doc.Add(new Int64Field("long", 0L, Field.Store.NO)); writer.AddDocument(doc); foreach (double d in TestNumericUtils.DOUBLE_NANs) { doc = new Document(); doc.Add(new DoubleField("double", d, Field.Store.NO)); writer.AddDocument(doc); } writer.Dispose(); IndexReader r = DirectoryReader.Open(dir); IndexSearcher s = NewSearcher(r); Query q = NumericRangeQuery.NewInt64Range("long", null, null, true, true); TopDocs topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewInt64Range("long", null, null, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewInt64Range("long", long.MinValue, long.MaxValue, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewInt64Range("long", long.MinValue, long.MaxValue, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(1, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewDoubleRange("double", null, null, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewDoubleRange("double", null, null, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewDoubleRange("double", double.NegativeInfinity, double.PositiveInfinity, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewDoubleRange("double", double.NegativeInfinity, double.PositiveInfinity, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(1, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewDoubleRange("double", double.NaN, double.NaN, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(TestNumericUtils.DOUBLE_NANs.Length, topDocs.ScoreDocs.Length, "Score doc count"); r.Dispose(); dir.Dispose(); } private void TestRandomTrieAndClassicRangeQuery(int precisionStep) { string field = "field" + precisionStep; int totalTermCountT = 0, totalTermCountC = 0, termCountT, termCountC; int num = TestUtil.NextInt32(Random, 10, 20); for (int i = 0; i < num; i++) { long lower = (long)(Random.NextDouble() * noDocs * distance) + startOffset; long upper = (long)(Random.NextDouble() * noDocs * distance) + startOffset; if (lower > upper) { long a = lower; lower = upper; upper = a; } BytesRef lowerBytes = new BytesRef(NumericUtils.BUF_SIZE_INT64), upperBytes = new BytesRef(NumericUtils.BUF_SIZE_INT64); NumericUtils.Int64ToPrefixCodedBytes(lower, 0, lowerBytes); NumericUtils.Int64ToPrefixCodedBytes(upper, 0, upperBytes); // test inclusive range NumericRangeQuery<long> tq = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, upper, true, true); TermRangeQuery cq = new TermRangeQuery(field, lowerBytes, upperBytes, true, true); TopDocs tTopDocs = searcher.Search(tq, 1); TopDocs cTopDocs = searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); // test exclusive range tq = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, upper, false, false); cq = new TermRangeQuery(field, lowerBytes, upperBytes, false, false); tTopDocs = searcher.Search(tq, 1); cTopDocs = searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); // test left exclusive range tq = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, upper, false, true); cq = new TermRangeQuery(field, lowerBytes, upperBytes, false, true); tTopDocs = searcher.Search(tq, 1); cTopDocs = searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); // test right exclusive range tq = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, upper, true, false); cq = new TermRangeQuery(field, lowerBytes, upperBytes, true, false); tTopDocs = searcher.Search(tq, 1); cTopDocs = searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); } CheckTermCounts(precisionStep, totalTermCountT, totalTermCountC); if (Verbose && precisionStep != int.MaxValue) { Console.WriteLine("Average number of terms during random search on '" + field + "':"); Console.WriteLine(" Numeric query: " + (((double)totalTermCountT) / (num * 4))); Console.WriteLine(" Classical query: " + (((double)totalTermCountC) / (num * 4))); } } [Test] public virtual void TestEmptyEnums() { int count = 3000; long lower = (distance * 3 / 2) + startOffset, upper = lower + count * distance + (distance / 3); // test empty enum if (Debugging.AssertsEnabled) Debugging.Assert(lower < upper); Assert.IsTrue(0 < CountTerms(NumericRangeQuery.NewInt64Range("field4", 4, lower, upper, true, true))); Assert.AreEqual(0, CountTerms(NumericRangeQuery.NewInt64Range("field4", 4, upper, lower, true, true))); // test empty enum outside of bounds lower = distance * noDocs + startOffset; upper = 2L * lower; if (Debugging.AssertsEnabled) Debugging.Assert(lower < upper); Assert.AreEqual(0, CountTerms(NumericRangeQuery.NewInt64Range("field4", 4, lower, upper, true, true))); } private int CountTerms(MultiTermQuery q) { Terms terms = MultiFields.GetTerms(reader, q.Field); if (terms == null) { return 0; } TermsEnum termEnum = q.GetTermsEnum(terms); Assert.IsNotNull(termEnum); int count = 0; BytesRef cur, last = null; while (termEnum.MoveNext()) { cur = termEnum.Term; count++; if (last != null) { Assert.IsTrue(last.CompareTo(cur) < 0); } last = BytesRef.DeepCopyOf(cur); } // LUCENE-3314: the results after next() already returned null are undefined, // Assert.IsNull(termEnum.Next()); return count; } private void CheckTermCounts(int precisionStep, int termCountT, int termCountC) { if (precisionStep == int.MaxValue) { Assert.AreEqual(termCountC, termCountT, "Number of terms should be equal for unlimited precStep"); } else { Assert.IsTrue(termCountT <= termCountC, "Number of terms for NRQ should be <= compared to classical TRQ"); } } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_8bit() { TestRandomTrieAndClassicRangeQuery(8); } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_6bit() { TestRandomTrieAndClassicRangeQuery(6); } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_4bit() { TestRandomTrieAndClassicRangeQuery(4); } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_2bit() { TestRandomTrieAndClassicRangeQuery(2); } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_NoTrie() { TestRandomTrieAndClassicRangeQuery(int.MaxValue); } private void TestRangeSplit(int precisionStep) { string field = "ascfield" + precisionStep; // 10 random tests int num = TestUtil.NextInt32(Random, 10, 20); for (int i = 0; i < num; i++) { long lower = (long)(Random.NextDouble() * noDocs - noDocs / 2); long upper = (long)(Random.NextDouble() * noDocs - noDocs / 2); if (lower > upper) { long a = lower; lower = upper; upper = a; } // test inclusive range Query tq = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, upper, true, true); TopDocs tTopDocs = searcher.Search(tq, 1); Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length"); // test exclusive range tq = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, upper, false, false); tTopDocs = searcher.Search(tq, 1); Assert.AreEqual(Math.Max(upper - lower - 1, 0), tTopDocs.TotalHits, "Returned count of range query must be equal to exclusive range length"); // test left exclusive range tq = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, upper, false, true); tTopDocs = searcher.Search(tq, 1); Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length"); // test right exclusive range tq = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, upper, true, false); tTopDocs = searcher.Search(tq, 1); Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length"); } } [Test] public virtual void TestRangeSplit_8bit() { TestRangeSplit(8); } [Test] public virtual void TestRangeSplit_6bit() { TestRangeSplit(6); } [Test] public virtual void TestRangeSplit_4bit() { TestRangeSplit(4); } [Test] public virtual void TestRangeSplit_2bit() { TestRangeSplit(2); } /// <summary> /// we fake a double test using long2double conversion of NumericUtils </summary> private void TestDoubleRange(int precisionStep) { string field = "ascfield" + precisionStep; const long lower = -1000L, upper = +2000L; Query tq = NumericRangeQuery.NewDoubleRange(field, precisionStep, NumericUtils.SortableInt64ToDouble(lower), NumericUtils.SortableInt64ToDouble(upper), true, true); TopDocs tTopDocs = searcher.Search(tq, 1); Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length"); Filter tf = NumericRangeFilter.NewDoubleRange(field, precisionStep, NumericUtils.SortableInt64ToDouble(lower), NumericUtils.SortableInt64ToDouble(upper), true, true); tTopDocs = searcher.Search(new MatchAllDocsQuery(), tf, 1); Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range filter must be equal to inclusive range length"); } [Test] public virtual void TestDoubleRange_8bit() { TestDoubleRange(8); } [Test] public virtual void TestDoubleRange_6bit() { TestDoubleRange(6); } [Test] public virtual void TestDoubleRange_4bit() { TestDoubleRange(4); } [Test] public virtual void TestDoubleRange_2bit() { TestDoubleRange(2); } private void TestSorting(int precisionStep) { string field = "field" + precisionStep; // 10 random tests, the index order is ascending, // so using a reverse sort field should retun descending documents int num = TestUtil.NextInt32(Random, 10, 20); for (int i = 0; i < num; i++) { long lower = (long)(Random.NextDouble() * noDocs * distance) + startOffset; long upper = (long)(Random.NextDouble() * noDocs * distance) + startOffset; if (lower > upper) { long a = lower; lower = upper; upper = a; } Query tq = NumericRangeQuery.NewInt64Range(field, precisionStep, lower, upper, true, true); TopDocs topDocs = searcher.Search(tq, null, noDocs, new Sort(new SortField(field, SortFieldType.INT64, true))); if (topDocs.TotalHits == 0) { continue; } ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); long last = searcher.Doc(sd[0].Doc).GetField(field).GetInt64Value().Value; for (int j = 1; j < sd.Length; j++) { long act = searcher.Doc(sd[j].Doc).GetField(field).GetInt64Value().Value; Assert.IsTrue(last > act, "Docs should be sorted backwards"); last = act; } } } [Test] public virtual void TestSorting_8bit() { TestSorting(8); } [Test] public virtual void TestSorting_6bit() { TestSorting(6); } [Test] public virtual void TestSorting_4bit() { TestSorting(4); } [Test] public virtual void TestSorting_2bit() { TestSorting(2); } [Test] public virtual void TestEqualsAndHash() { QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt64Range("test1", 4, 10L, 20L, true, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt64Range("test2", 4, 10L, 20L, false, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt64Range("test3", 4, 10L, 20L, true, false)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt64Range("test4", 4, 10L, 20L, false, false)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt64Range("test5", 4, 10L, null, true, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt64Range("test6", 4, null, 20L, true, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt64Range("test7", 4, null, null, true, true)); QueryUtils.CheckEqual(NumericRangeQuery.NewInt64Range("test8", 4, 10L, 20L, true, true), NumericRangeQuery.NewInt64Range("test8", 4, 10L, 20L, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewInt64Range("test9", 4, 10L, 20L, true, true), NumericRangeQuery.NewInt64Range("test9", 8, 10L, 20L, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewInt64Range("test10a", 4, 10L, 20L, true, true), NumericRangeQuery.NewInt64Range("test10b", 4, 10L, 20L, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewInt64Range("test11", 4, 10L, 20L, true, true), NumericRangeQuery.NewInt64Range("test11", 4, 20L, 10L, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewInt64Range("test12", 4, 10L, 20L, true, true), NumericRangeQuery.NewInt64Range("test12", 4, 10L, 20L, false, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewInt64Range("test13", 4, 10L, 20L, true, true), NumericRangeQuery.NewSingleRange("test13", 4, 10f, 20f, true, true)); // difference to int range is tested in TestNumericRangeQuery32 } } }
using AjaxControlToolkit.Design; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing.Design; using System.Linq; using System.Text; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Drawing; namespace AjaxControlToolkit { /// <summary> /// The BubbleChart control enables you to render a bubble chart from one or more series of values. /// This control is compatible with any browser that supports SVG including Internet Explorer 9 and above. /// </summary> [ClientCssResource(Constants.BubbleChartName)] [ClientScriptResource("Sys.Extended.UI.BubbleChart", Constants.BubbleChartName)] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.BubbleChartName + Constants.IconPostfix)] public class BubbleChart : ChartBase { List<BubbleChartValue> _values = new List<BubbleChartValue>(); /// <summary> /// Provides a list of values to the client side. /// The Values property is required for designer experience support, /// because the editor always prevents providing values to the client side as ExtenderControlProperty at runtime. /// </summary> [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [ExtenderControlProperty(true, true)] [ClientPropertyName("bubbleChartClientValues")] public List<BubbleChartValue> BubbleChartClientValues { get { return _values; } } /// <summary> /// A list of values. /// </summary> [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [DefaultValue(null)] [NotifyParentProperty(true)] [Editor(typeof(ChartBaseSeriesEditor<BubbleChartValue>), typeof(UITypeEditor))] public List<BubbleChartValue> BubbleChartValues { get { return _values; } } /// <summary> /// Interval size for the Y axis line of the chart. /// The default is 6 /// </summary> [ExtenderControlProperty] [DefaultValue(6)] [ClientPropertyName("yAxisLines")] public int YAxisLines { get; set; } /// <summary> /// Iinterval size for the X axis line of the chart. /// The default is 6 /// </summary> [ExtenderControlProperty] [DefaultValue(6)] [ClientPropertyName("xAxisLines")] public int XAxisLines { get; set; } /// <summary> /// The number of different bubble sizes. /// The default is 5 /// </summary> [ExtenderControlProperty] [DefaultValue(5)] [ClientPropertyName("bubbleSizes")] public int BubbleSizes { get; set; } /// <summary> /// A color of the Y axis lines of the chart. /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("yAxisLineColor")] public string YAxisLineColor { get; set; } /// <summary> /// A color of the X axis lines of the chart. /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("xAxisLineColor")] public string XAxisLineColor { get; set; } /// <summary> /// The color of the base lines of a chart. /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("baseLineColor")] public string BaseLineColor { get; set; } /// <summary> /// A background color of the tooltip box. /// The default is #FFC652 /// </summary> [ExtenderControlProperty] [DefaultValue("#FFC652")] [ClientPropertyName("tooltipBackgroundColor")] public string TooltipBackgroundColor { get; set; } /// <summary> /// A font color of the tooltip box. /// The default is #0E426C /// </summary> [ExtenderControlProperty] [DefaultValue("#0E426C")] [ClientPropertyName("tooltipFontColor")] public string TooltipFontColor { get; set; } /// <summary> /// A border color of the tooltip box. /// The default is #B85B3E /// </summary> [ExtenderControlProperty] [DefaultValue("#B85B3E")] [ClientPropertyName("tooltipBorderColor")] public string TooltipBorderColor { get; set; } /// <summary> /// Text/label to describe what data is in XAxis. /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("xAxisLabel")] public string XAxisLabel { get; set; } /// <summary> /// Text/label to describe what data is in YAxis. /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("yAxisLabel")] public string YAxisLabel { get; set; } /// <summary> /// Text/label that will be shown in the tooltip and describe a bubble value. /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("bubbleLabel")] public string BubbleLabel { get; set; } /// <summary> /// The axis label font color /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("axislabelFontColor")] public string AxislabelFontColor { get; set; } protected override void OnInit(EventArgs e) { base.OnInit(e); if(IsDesignMode) return; foreach(BubbleChartValue bubbleChartValue in BubbleChartValues) { if(String.IsNullOrWhiteSpace(bubbleChartValue.Category)) throw new Exception("Category is missing the BubbleChartValue. Please provide a Category in the BubbleChartValue."); if(bubbleChartValue.Data == 0) throw new Exception("Data is missing the BubbleChartValue. Please provide a value of Data in the BubbleChartValue."); } } protected override void CreateChildControls() { var parent = new HtmlGenericControl("div"); parent.ID = "_ParentDiv"; parent.Attributes.Add("style", String.Format("border-style:solid; border-width:1px;width:{0};height:{1};", ChartWidth, ChartHeight)); var sbScript = new StringBuilder(); sbScript.Append("<script>"); sbScript.Append("function init(evt) { "); sbScript.Append(" if ( window.svgDocument == null ) { "); sbScript.Append(" gDocument = evt.target.ownerDocument;"); sbScript.Append(" } "); sbScript.Append("} "); sbScript.Append("function ShowTooltip(me, evt, category, data, bubbleLabel) { "); sbScript.Append(String.Format(" var tooltipDiv = document.getElementById('{0}_tooltipDiv');", ClientID)); sbScript.Append(" tooltipDiv.innerHTML = String.format('{0}: {1} {2}', category, data, bubbleLabel) ;"); sbScript.Append(" tooltipDiv.style.top = evt.pageY - 25 + 'px';"); sbScript.Append(" tooltipDiv.style.left = evt.pageX + 20 + 'px';"); sbScript.Append(" tooltipDiv.style.visibility = 'visible';"); sbScript.Append(" me.style.strokeWidth = '4';"); sbScript.Append(" me.style.fillOpacity = '1';"); sbScript.Append(" me.style.strokeOpacity = '1';"); sbScript.Append("} "); sbScript.Append("function HideTooltip(me, evt) { "); sbScript.Append(String.Format(" var tooltipDiv = document.getElementById('{0}_tooltipDiv');", ClientID)); sbScript.Append(" tooltipDiv.innerHTML = '';"); sbScript.Append(" tooltipDiv.style.visibility = 'hidden';"); sbScript.Append(" me.style.strokeWidth = '0';"); sbScript.Append(" me.style.fillOpacity = '0.7';"); sbScript.Append(" me.style.strokeOpacity = '0.7';"); sbScript.Append("} "); sbScript.Append("</script>"); parent.InnerHtml = sbScript.ToString(); Controls.Add(parent); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Mashup.Api.AuthADSP.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* * 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 NUnit.Framework; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; namespace Lucene.Net.Util { [TestFixture] public class TestSortedVIntList:LuceneTestCase { internal virtual void TstIterator(SortedVIntList vintList, int[] ints) { for (int i = 0; i < ints.Length; i++) { if ((i > 0) && (ints[i - 1] == ints[i])) { return ; // DocNrSkipper should not skip to same document. } } DocIdSetIterator m = vintList.Iterator(); for (int i = 0; i < ints.Length; i++) { Assert.IsTrue(m.NextDoc() != DocIdSetIterator.NO_MORE_DOCS, "No end of Matcher at: " + i); Assert.AreEqual(ints[i], m.DocID()); } Assert.IsTrue(m.NextDoc() == DocIdSetIterator.NO_MORE_DOCS, "End of Matcher"); } internal virtual void TstVIntList(SortedVIntList vintList, int[] ints, int expectedByteSize) { Assert.AreEqual(ints.Length, vintList.Size(), "Size"); Assert.AreEqual(expectedByteSize, vintList.GetByteSize(), "Byte size"); TstIterator(vintList, ints); } public virtual void TstViaBitSet(int[] ints, int expectedByteSize) { int MAX_INT_FOR_BITSET = 1024 * 1024; //mgarski - BitArray cannot grow, so make as large as we would need it to be System.Collections.BitArray bs = new System.Collections.BitArray(MAX_INT_FOR_BITSET); for (int i = 0; i < ints.Length; i++) { if (ints[i] > MAX_INT_FOR_BITSET) { return ; // BitSet takes too much memory } if ((i > 0) && (ints[i - 1] == ints[i])) { return ; // BitSet cannot store duplicate. } bs.Set(ints[i], true); } SortedVIntList svil = new SortedVIntList(bs); TstVIntList(svil, ints, expectedByteSize); TstVIntList(new SortedVIntList(svil.Iterator()), ints, expectedByteSize); } private const int VB1 = 0x7F; private const int BIT_SHIFT = 7; private static readonly int VB2 = (VB1 << BIT_SHIFT) | VB1; private static readonly int VB3 = (VB2 << BIT_SHIFT) | VB1; private static readonly int VB4 = (VB3 << BIT_SHIFT) | VB1; private int VIntByteSize(int i) { System.Diagnostics.Debug.Assert(i >= 0); if (i <= VB1) return 1; if (i <= VB2) return 2; if (i <= VB3) return 3; if (i <= VB4) return 4; return 5; } private int VIntListByteSize(int[] ints) { int byteSize = 0; int last = 0; for (int i = 0; i < ints.Length; i++) { byteSize += VIntByteSize(ints[i] - last); last = ints[i]; } return byteSize; } public virtual void TstInts(int[] ints) { int expectedByteSize = VIntListByteSize(ints); try { TstVIntList(new SortedVIntList(ints), ints, expectedByteSize); TstViaBitSet(ints, expectedByteSize); } catch (System.IO.IOException ioe) { throw new System.SystemException("", ioe); } } public virtual void TstIllegalArgExc(int[] ints) { try { new SortedVIntList(ints); } catch (System.ArgumentException e) { return ; } Assert.Fail("Expected IllegalArgumentException"); } private int[] FibArray(int a, int b, int size) { int[] fib = new int[size]; fib[0] = a; fib[1] = b; for (int i = 2; i < size; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } return fib; } private int[] ReverseDiffs(int[] ints) { // reverse the order of the successive differences int[] res = new int[ints.Length]; for (int i = 0; i < ints.Length; i++) { res[i] = ints[ints.Length - 1] + (ints[0] - ints[ints.Length - 1 - i]); } return res; } [Test] public virtual void Test01() { TstInts(new int[]{}); } [Test] public virtual void Test02() { TstInts(new int[]{0}); } [Test] public virtual void Test04a() { TstInts(new int[]{0, VB2 - 1}); } [Test] public virtual void Test04b() { TstInts(new int[]{0, VB2}); } [Test] public virtual void Test04c() { TstInts(new int[]{0, VB2 + 1}); } [Test] public virtual void Test05() { TstInts(FibArray(0, 1, 7)); // includes duplicate value 1 } [Test] public virtual void Test05b() { TstInts(ReverseDiffs(FibArray(0, 1, 7))); } [Test] public virtual void Test06() { TstInts(FibArray(1, 2, 45)); // no duplicates, size 46 exceeds max int. } [Test] public virtual void Test06b() { TstInts(ReverseDiffs(FibArray(1, 2, 45))); } [Test] public virtual void Test07a() { TstInts(new int[]{0, VB3}); } [Test] public virtual void Test07b() { TstInts(new int[]{1, VB3 + 2}); } [Test] public virtual void Test07c() { TstInts(new int[]{2, VB3 + 4}); } [Test] public virtual void Test08a() { TstInts(new int[]{0, VB4 + 1}); } [Test] public virtual void Test08b() { TstInts(new int[]{1, VB4 + 1}); } [Test] public virtual void Test08c() { TstInts(new int[]{2, VB4 + 1}); } [Test] public virtual void Test10() { TstIllegalArgExc(new int[]{- 1}); } [Test] public virtual void Test11() { TstIllegalArgExc(new int[]{1, 0}); } [Test] public virtual void Test12() { TstIllegalArgExc(new int[]{0, 1, 1, 2, 3, 5, 8, 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. #nullable enable using System.Diagnostics; using System.Text; #if MS_IO_REDIST using System; using System.IO; namespace Microsoft.IO #else namespace System.IO #endif { public static partial class Path { public static char[] GetInvalidFileNameChars() => new char[] { '\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, ':', '*', '?', '\\', '/' }; public static char[] GetInvalidPathChars() => new char[] { '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31 }; // Expands the given path to a fully qualified path. public static string GetFullPath(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); // If the path would normalize to string empty, we'll consider it empty if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) throw new ArgumentException(SR.Arg_PathEmpty, nameof(path)); // Embedded null characters are the only invalid character case we trully care about. // This is because the nulls will signal the end of the string to Win32 and therefore have // unpredictable results. if (path.Contains('\0')) throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path)); if (PathInternal.IsExtended(path.AsSpan())) { // \\?\ paths are considered normalized by definition. Windows doesn't normalize \\?\ // paths and neither should we. Even if we wanted to GetFullPathName does not work // properly with device paths. If one wants to pass a \\?\ path through normalization // one can chop off the prefix, pass it to GetFullPath and add it again. return path; } return PathHelper.Normalize(path); } public static string GetFullPath(string path, string basePath) { if (path == null) throw new ArgumentNullException(nameof(path)); if (basePath == null) throw new ArgumentNullException(nameof(basePath)); if (!IsPathFullyQualified(basePath)) throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath)); if (basePath.Contains('\0') || path.Contains('\0')) throw new ArgumentException(SR.Argument_InvalidPathChars); if (IsPathFullyQualified(path)) return GetFullPath(path); if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) return basePath; int length = path.Length; string? combinedPath = null; if (length >= 1 && PathInternal.IsDirectorySeparator(path[0])) { // Path is current drive rooted i.e. starts with \: // "\Foo" and "C:\Bar" => "C:\Foo" // "\Foo" and "\\?\C:\Bar" => "\\?\C:\Foo" combinedPath = Join(GetPathRoot(basePath.AsSpan()), path.AsSpan(1)); // Cut the separator to ensure we don't end up with two separators when joining with the root. } else if (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar) { // Drive relative paths Debug.Assert(length == 2 || !PathInternal.IsDirectorySeparator(path[2])); if (GetVolumeName(path.AsSpan()).EqualsOrdinal(GetVolumeName(basePath.AsSpan()))) { // Matching root // "C:Foo" and "C:\Bar" => "C:\Bar\Foo" // "C:Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo" combinedPath = Join(basePath.AsSpan(), path.AsSpan(2)); } else { // No matching root, root to specified drive // "D:Foo" and "C:\Bar" => "D:Foo" // "D:Foo" and "\\?\C:\Bar" => "\\?\D:\Foo" combinedPath = !PathInternal.IsDevice(basePath.AsSpan()) ? path.Insert(2, @"\") : length == 2 ? JoinInternal(basePath.AsSpan(0, 4), path.AsSpan(), @"\".AsSpan()) : JoinInternal(basePath.AsSpan(0, 4), path.AsSpan(0, 2), @"\".AsSpan(), path.AsSpan(2)); } } else { // "Simple" relative path // "Foo" and "C:\Bar" => "C:\Bar\Foo" // "Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo" combinedPath = JoinInternal(basePath.AsSpan(), path.AsSpan()); } // Device paths are normalized by definition, so passing something of this format (i.e. \\?\C:\.\tmp, \\.\C:\foo) // to Windows APIs won't do anything by design. Additionally, GetFullPathName() in Windows doesn't root // them properly. As such we need to manually remove segments and not use GetFullPath(). return PathInternal.IsDevice(combinedPath.AsSpan()) ? PathInternal.RemoveRelativeSegments(combinedPath, PathInternal.GetRootLength(combinedPath.AsSpan())) : GetFullPath(combinedPath); } public static string GetTempPath() { Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath]; var builder = new ValueStringBuilder(initialBuffer); GetTempPath(ref builder); string path = PathHelper.Normalize(ref builder); builder.Dispose(); return path; } private static void GetTempPath(ref ValueStringBuilder builder) { uint result; while ((result = Interop.Kernel32.GetTempPathW(builder.Capacity, ref builder.GetPinnableReference())) > builder.Capacity) { // Reported size is greater than the buffer size. Increase the capacity. builder.EnsureCapacity(checked((int)result)); } if (result == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); builder.Length = (int)result; } // Returns a unique temporary file name, and creates a 0-byte file by that // name on disk. public static string GetTempFileName() { Span<char> initialTempPathBuffer = stackalloc char[PathInternal.MaxShortPath]; ValueStringBuilder tempPathBuilder = new ValueStringBuilder(initialTempPathBuffer); GetTempPath(ref tempPathBuilder); Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath]; var builder = new ValueStringBuilder(initialBuffer); uint result = Interop.Kernel32.GetTempFileNameW( ref tempPathBuilder.GetPinnableReference(), "tmp", 0, ref builder.GetPinnableReference()); tempPathBuilder.Dispose(); if (result == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); builder.Length = builder.RawChars.IndexOf('\0'); string path = PathHelper.Normalize(ref builder); builder.Dispose(); return path; } // Tests if the given path contains a root. A path is considered rooted // if it starts with a backslash ("\") or a valid drive letter and a colon (":"). public static bool IsPathRooted(string? path) { return path != null && IsPathRooted(path.AsSpan()); } public static bool IsPathRooted(ReadOnlySpan<char> path) { int length = path.Length; return (length >= 1 && PathInternal.IsDirectorySeparator(path[0])) || (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. If the path is empty or // only contains whitespace characters an ArgumentException gets thrown. public static string? GetPathRoot(string? path) { if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) return null; ReadOnlySpan<char> result = GetPathRoot(path.AsSpan()); if (path!.Length == result.Length) return PathInternal.NormalizeDirectorySeparators(path); return PathInternal.NormalizeDirectorySeparators(result.ToString()); } /// <remarks> /// Unlike the string overload, this method will not normalize directory separators. /// </remarks> public static ReadOnlySpan<char> GetPathRoot(ReadOnlySpan<char> path) { if (PathInternal.IsEffectivelyEmpty(path)) return ReadOnlySpan<char>.Empty; int pathRoot = PathInternal.GetRootLength(path); return pathRoot <= 0 ? ReadOnlySpan<char>.Empty : path.Slice(0, pathRoot); } /// <summary>Gets whether the system is case-sensitive.</summary> internal static bool IsCaseSensitive => false; /// <summary> /// Returns the volume name for dos, UNC and device paths. /// </summary> internal static ReadOnlySpan<char> GetVolumeName(ReadOnlySpan<char> path) { // 3 cases: UNC ("\\server\share"), Device ("\\?\C:\"), or Dos ("C:\") ReadOnlySpan<char> root = GetPathRoot(path); if (root.Length == 0) return root; // Cut from "\\?\UNC\Server\Share" to "Server\Share" // Cut from "\\Server\Share" to "Server\Share" int startOffset = GetUncRootLength(path); if (startOffset == -1) { if (PathInternal.IsDevice(path)) { startOffset = 4; // Cut from "\\?\C:\" to "C:" } else { startOffset = 0; // e.g. "C:" } } ReadOnlySpan<char> pathToTrim = root.Slice(startOffset); return Path.EndsInDirectorySeparator(pathToTrim) ? pathToTrim.Slice(0, pathToTrim.Length - 1) : pathToTrim; } /// <summary> /// Returns offset as -1 if the path is not in Unc format, otherwise returns the root length. /// </summary> /// <param name="path"></param> /// <returns></returns> internal static int GetUncRootLength(ReadOnlySpan<char> path) { bool isDevice = PathInternal.IsDevice(path); if (!isDevice && path.Slice(0, 2).EqualsOrdinal(@"\\".AsSpan())) return 2; else if (isDevice && path.Length >= 8 && (path.Slice(0, 8).EqualsOrdinal(PathInternal.UncExtendedPathPrefix.AsSpan()) || path.Slice(5, 4).EqualsOrdinal(@"UNC\".AsSpan()))) return 8; return -1; } } }
// // DockBar.cs // // Author: // Lluis Sanchez Gual // // // Copyright (C) 2007 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; using Gtk; using System.Collections.Generic; namespace Pinta.Docking { public class DockBar: Gtk.EventBox { Gtk.PositionType position; Box box; DockFrame frame; Label filler; bool alwaysVisible; bool showBorder = true; internal DockBar (DockFrame frame, Gtk.PositionType position) { VisibleWindow = false; this.frame = frame; this.position = position; Gtk.Alignment al = new Alignment (0,0,0,0); if (Orientation == Gtk.Orientation.Horizontal) box = new HBox (); else box = new VBox (); al.Add (box); Add (al); filler = new Label (); filler.WidthRequest = 4; filler.HeightRequest = 4; box.PackEnd (filler); ShowAll (); UpdateVisibility (); } public bool IsExtracted { get { return OriginalBar != null; } } internal DockBar OriginalBar { get; set; } public bool AlwaysVisible { get { return this.alwaysVisible; } set { this.alwaysVisible = value; UpdateVisibility (); } } public bool AlignToEnd { get; set; } public bool ShowBorder { get { return showBorder; } set { showBorder = value; QueueResize (); } } internal Gtk.Orientation Orientation { get { return (position == PositionType.Left || position == PositionType.Right) ? Gtk.Orientation.Vertical : Gtk.Orientation.Horizontal; } } internal Gtk.PositionType Position { get { return position; } } internal DockFrame Frame { get { return frame; } } DateTime hoverActivationDelay; void DisableHoverActivation () { // Temporarily disables hover activation of items in this bar // Useful to avoid accidental triggers when the bar items // are reallocated hoverActivationDelay = DateTime.Now + TimeSpan.FromSeconds (1.5); } internal bool HoverActivationEnabled { get { return DateTime.Now >= hoverActivationDelay; } } internal DockBarItem AddItem (DockItem item, int size) { DisableHoverActivation (); DockBarItem it = new DockBarItem (this, item, size); box.PackStart (it, false, false, 0); it.ShowAll (); UpdateVisibility (); it.Shown += OnItemVisibilityChanged; it.Hidden += OnItemVisibilityChanged; return it; } void OnItemVisibilityChanged (object o, EventArgs args) { DisableHoverActivation (); UpdateVisibility (); } internal void OnCompactLevelChanged () { UpdateVisibility (); if (OriginalBar != null) OriginalBar.UpdateVisibility (); } internal void UpdateVisibility () { if (Frame.OverlayWidgetVisible) { Visible = false; } else { filler.Visible = (Frame.CompactGuiLevel < 3); int visibleCount = 0; foreach (Gtk.Widget w in box.Children) { if (w.Visible) visibleCount++; } Visible = alwaysVisible || filler.Visible || visibleCount > 0; } } internal void RemoveItem (DockBarItem it) { DisableHoverActivation (); box.Remove (it); it.Shown -= OnItemVisibilityChanged; it.Hidden -= OnItemVisibilityChanged; UpdateVisibility (); } internal void UpdateTitle (DockItem item) { foreach (Widget w in box.Children) { DockBarItem it = w as DockBarItem; if (it != null && it.DockItem == item) { it.UpdateTab (); break; } } } internal void UpdateStyle (DockItem item) { } protected override void OnSizeRequested (ref Requisition requisition) { base.OnSizeRequested (ref requisition); if (ShowBorder) { // Add space for the separator if (Orientation == Gtk.Orientation.Vertical) requisition.Width++; else requisition.Height++; } } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { base.OnSizeAllocated (allocation); if (ShowBorder && Child != null) { switch (Position) { case PositionType.Left: allocation.Width--; break; case PositionType.Right: allocation.X++; allocation.Width--; break; case PositionType.Top: allocation.Height--; break; case PositionType.Bottom: allocation.Y++; allocation.Height--; break; } Child.SizeAllocate (allocation); } } protected override bool OnExposeEvent (Gdk.EventExpose evnt) { var alloc = Allocation; using (var ctx = Gdk.CairoHelper.Create (GdkWindow)) { ctx.Rectangle (alloc.X, alloc.Y, alloc.X + alloc.Width, alloc.Y + alloc.Height); Cairo.LinearGradient gr; if (Orientation == Gtk.Orientation.Vertical) gr = new Cairo.LinearGradient (alloc.X, alloc.Y, alloc.X + alloc.Width, alloc.Y); else gr = new Cairo.LinearGradient (alloc.X, alloc.Y, alloc.X, alloc.Y + alloc.Height); using (gr) { gr.AddColorStop (0, Styles.DockBarBackground1); gr.AddColorStop (1, Styles.DockBarBackground2); ctx.SetSource (gr); } ctx.Fill (); // Light shadow double offs = ShowBorder ? 1.5 : 0.5; switch (Position) { case PositionType.Left:ctx.MoveTo (alloc.X + alloc.Width - offs, alloc.Y); ctx.RelLineTo (0, Allocation.Height); break; case PositionType.Right: ctx.MoveTo (alloc.X + offs, alloc.Y); ctx.RelLineTo (0, Allocation.Height); break; case PositionType.Top: ctx.MoveTo (alloc.X, alloc.Y + alloc.Height - offs); ctx.RelLineTo (Allocation.Width, 0); break; case PositionType.Bottom: ctx.MoveTo (alloc.X, alloc.Y + offs); ctx.RelLineTo (Allocation.Width, 0); break; } ctx.LineWidth = 1; ctx.SetSourceColor (Styles.DockBarSeparatorColorLight); ctx.Stroke (); } if (Child != null) PropagateExpose (Child, evnt); if (ShowBorder) { using (var ctx = Gdk.CairoHelper.Create (GdkWindow)) { ctx.LineWidth = 1; // Dark separator switch (Position) { case PositionType.Left:ctx.MoveTo (alloc.X + alloc.Width - 0.5, alloc.Y); ctx.RelLineTo (0, Allocation.Height); break; case PositionType.Right: ctx.MoveTo (alloc.X + 0.5, alloc.Y); ctx.RelLineTo (0, Allocation.Height); break; case PositionType.Top: ctx.MoveTo (alloc.X, alloc.Y + alloc.Height + 0.5); ctx.RelLineTo (Allocation.Width, 0); break; case PositionType.Bottom: ctx.MoveTo (alloc.X, alloc.Y + 0.5); ctx.RelLineTo (Allocation.Width, 0); break; } ctx.SetSourceColor (Styles.DockSeparatorColor.ToCairoColor ()); ctx.Stroke (); } } return true; } } }
namespace Epi.Windows.Dialogs { partial class BaseReadDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 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(BaseReadDialog)); this.txtDataSource = new System.Windows.Forms.TextBox(); this.lblDataSource = new System.Windows.Forms.Label(); this.lblDataSourceDrivers = new System.Windows.Forms.Label(); this.cmbDataSourcePlugIns = new System.Windows.Forms.ComboBox(); this.btnFindDataSource = new System.Windows.Forms.Button(); this.btnHelp = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.gbxExplorer = new System.Windows.Forms.GroupBox(); this.lvDataSourceObjects = new System.Windows.Forms.ListView(); this.columnHeaderItem = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.panel1 = new System.Windows.Forms.Panel(); this.btnAdvanced = new System.Windows.Forms.Button(); this.gbxShow = new System.Windows.Forms.GroupBox(); this.chkTables = new System.Windows.Forms.CheckBox(); this.chkViews = new System.Windows.Forms.CheckBox(); this.cmbRecentSources = new System.Windows.Forms.ComboBox(); this.lblRecentSources = new System.Windows.Forms.Label(); this.gbxExplorer.SuspendLayout(); this.panel1.SuspendLayout(); this.gbxShow.SuspendLayout(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); // // txtDataSource // resources.ApplyResources(this.txtDataSource, "txtDataSource"); this.txtDataSource.Name = "txtDataSource"; this.txtDataSource.ReadOnly = true; this.txtDataSource.TextChanged += new System.EventHandler(this.txtDataSource_TextChanged); // // lblDataSource // this.lblDataSource.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblDataSource, "lblDataSource"); this.lblDataSource.Name = "lblDataSource"; // // lblDataSourceDrivers // this.lblDataSourceDrivers.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblDataSourceDrivers, "lblDataSourceDrivers"); this.lblDataSourceDrivers.Name = "lblDataSourceDrivers"; // // cmbDataSourcePlugIns // resources.ApplyResources(this.cmbDataSourcePlugIns, "cmbDataSourcePlugIns"); this.cmbDataSourcePlugIns.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbDataSourcePlugIns.Name = "cmbDataSourcePlugIns"; this.cmbDataSourcePlugIns.SelectedIndexChanged += new System.EventHandler(this.cmbDataSourcePlugIns_SelectedIndexChanged); // // btnFindDataSource // resources.ApplyResources(this.btnFindDataSource, "btnFindDataSource"); this.btnFindDataSource.Name = "btnFindDataSource"; this.btnFindDataSource.Click += new System.EventHandler(this.btnFindDataSource_Click); // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; // // gbxExplorer // resources.ApplyResources(this.gbxExplorer, "gbxExplorer"); this.gbxExplorer.Controls.Add(this.lvDataSourceObjects); this.gbxExplorer.FlatStyle = System.Windows.Forms.FlatStyle.System; this.gbxExplorer.Name = "gbxExplorer"; this.gbxExplorer.TabStop = false; // // lvDataSourceObjects // resources.ApplyResources(this.lvDataSourceObjects, "lvDataSourceObjects"); this.lvDataSourceObjects.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderItem}); this.lvDataSourceObjects.FullRowSelect = true; this.lvDataSourceObjects.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.lvDataSourceObjects.HideSelection = false; this.lvDataSourceObjects.MultiSelect = false; this.lvDataSourceObjects.Name = "lvDataSourceObjects"; this.lvDataSourceObjects.Sorting = System.Windows.Forms.SortOrder.Ascending; this.lvDataSourceObjects.UseCompatibleStateImageBehavior = false; this.lvDataSourceObjects.View = System.Windows.Forms.View.Details; this.lvDataSourceObjects.SelectedIndexChanged += new System.EventHandler(this.lvDataSourceObjects_SelectedIndexChanged); this.lvDataSourceObjects.DoubleClick += new System.EventHandler(this.lvDataSourceObjects_DoubleClick); this.lvDataSourceObjects.Resize += new System.EventHandler(this.lvDataSourceObjects_Resize); // // columnHeaderItem // resources.ApplyResources(this.columnHeaderItem, "columnHeaderItem"); // // panel1 // this.panel1.Controls.Add(this.btnAdvanced); this.panel1.Controls.Add(this.btnOK); this.panel1.Controls.Add(this.btnCancel); this.panel1.Controls.Add(this.btnHelp); resources.ApplyResources(this.panel1, "panel1"); this.panel1.Name = "panel1"; // // btnAdvanced // this.btnAdvanced.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnAdvanced, "btnAdvanced"); this.btnAdvanced.Name = "btnAdvanced"; this.btnAdvanced.Click += new System.EventHandler(this.btnAdvanced_Click); // // gbxShow // this.gbxShow.Controls.Add(this.chkTables); this.gbxShow.Controls.Add(this.chkViews); resources.ApplyResources(this.gbxShow, "gbxShow"); this.gbxShow.Name = "gbxShow"; this.gbxShow.TabStop = false; // // chkTables // resources.ApplyResources(this.chkTables, "chkTables"); this.chkTables.Name = "chkTables"; this.chkTables.UseVisualStyleBackColor = true; this.chkTables.CheckedChanged += new System.EventHandler(this.CheckBox_CheckedChanged); // // chkViews // resources.ApplyResources(this.chkViews, "chkViews"); this.chkViews.Checked = true; this.chkViews.CheckState = System.Windows.Forms.CheckState.Checked; this.chkViews.Name = "chkViews"; this.chkViews.UseVisualStyleBackColor = true; this.chkViews.CheckedChanged += new System.EventHandler(this.CheckBox_CheckedChanged); // // cmbRecentSources // resources.ApplyResources(this.cmbRecentSources, "cmbRecentSources"); this.cmbRecentSources.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbRecentSources.Name = "cmbRecentSources"; this.cmbRecentSources.SelectedIndexChanged += new System.EventHandler(this.cmbRecentSources_SelectedIndexChanged); // // lblRecentSources // this.lblRecentSources.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblRecentSources, "lblRecentSources"); this.lblRecentSources.Name = "lblRecentSources"; // // BaseReadDialog // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.cmbRecentSources); this.Controls.Add(this.lblRecentSources); this.Controls.Add(this.panel1); this.Controls.Add(this.btnFindDataSource); this.Controls.Add(this.cmbDataSourcePlugIns); this.Controls.Add(this.lblDataSource); this.Controls.Add(this.lblDataSourceDrivers); this.Controls.Add(this.gbxShow); this.Controls.Add(this.txtDataSource); this.Controls.Add(this.gbxExplorer); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "BaseReadDialog"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; this.Load += new System.EventHandler(this.ReadDialog_Load); this.gbxExplorer.ResumeLayout(false); this.panel1.ResumeLayout(false); this.gbxShow.ResumeLayout(false); this.gbxShow.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtDataSource; private System.Windows.Forms.Label lblDataSource; private System.Windows.Forms.Label lblDataSourceDrivers; private System.Windows.Forms.ComboBox cmbDataSourcePlugIns; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnFindDataSource; private System.Windows.Forms.GroupBox gbxExplorer; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ListView lvDataSourceObjects; private System.Windows.Forms.ColumnHeader columnHeaderItem; private System.Windows.Forms.GroupBox gbxShow; private System.Windows.Forms.CheckBox chkTables; private System.Windows.Forms.CheckBox chkViews; private System.Windows.Forms.ComboBox cmbRecentSources; private System.Windows.Forms.Label lblRecentSources; private System.Windows.Forms.Button btnAdvanced; } }
#if DOTNET35 // 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. // The BigNumber class implements methods for formatting and parsing // big numeric values. To format and parse numeric values, applications should // use the Format and Parse methods provided by the numeric // classes (BigInteger). Those // Format and Parse methods share a common implementation // provided by this class, and are thus documented in detail here. // // Formatting // // The Format methods provided by the numeric classes are all of the // form // // public static String Format(XXX value, String format); // public static String Format(XXX value, String format, NumberFormatInfo info); // // where XXX is the name of the particular numeric class. The methods convert // the numeric value to a string using the format string given by the // format parameter. If the format parameter is null or // an empty string, the number is formatted as if the string "G" (general // format) was specified. The info parameter specifies the // NumberFormatInfo instance to use when formatting the number. If the // info parameter is null or omitted, the numeric formatting information // is obtained from the current culture. The NumberFormatInfo supplies // such information as the characters to use for decimal and thousand // separators, and the spelling and placement of currency symbols in monetary // values. // // Format strings fall into two categories: Standard format strings and // user-defined format strings. A format string consisting of a single // alphabetic character (A-Z or a-z), optionally followed by a sequence of // digits (0-9), is a standard format string. All other format strings are // used-defined format strings. // // A standard format string takes the form Axx, where A is an // alphabetic character called the format specifier and xx is a // sequence of digits called the precision specifier. The format // specifier controls the type of formatting applied to the number and the // precision specifier controls the number of significant digits or decimal // places of the formatting operation. The following table describes the // supported standard formats. // // C c - Currency format. The number is // converted to a string that represents a currency amount. The conversion is // controlled by the currency format information of the NumberFormatInfo // used to format the number. The precision specifier indicates the desired // number of decimal places. If the precision specifier is omitted, the default // currency precision given by the NumberFormatInfo is used. // // D d - Decimal format. This format is // supported for integral types only. The number is converted to a string of // decimal digits, prefixed by a minus sign if the number is negative. The // precision specifier indicates the minimum number of digits desired in the // resulting string. If required, the number will be left-padded with zeros to // produce the number of digits given by the precision specifier. // // E e Engineering (scientific) format. // The number is converted to a string of the form // "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each // 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative, and one digit always precedes the decimal point. The // precision specifier indicates the desired number of digits after the decimal // point. If the precision specifier is omitted, a default of 6 digits after // the decimal point is used. The format specifier indicates whether to prefix // the exponent with an 'E' or an 'e'. The exponent is always consists of a // plus or minus sign and three digits. // // F f Fixed point format. The number is // converted to a string of the form "-ddd.ddd....", where each // 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative. The precision specifier indicates the desired number of // decimal places. If the precision specifier is omitted, the default numeric // precision given by the NumberFormatInfo is used. // // G g - General format. The number is // converted to the shortest possible decimal representation using fixed point // or scientific format. The precision specifier determines the number of // significant digits in the resulting string. If the precision specifier is // omitted, the number of significant digits is determined by the type of the // number being converted (10 for int, 19 for long, 7 for // float, 15 for double, 19 for Currency, and 29 for // Decimal). Trailing zeros after the decimal point are removed, and the // resulting string contains a decimal point only if required. The resulting // string uses fixed point format if the exponent of the number is less than // the number of significant digits and greater than or equal to -4. Otherwise, // the resulting string uses scientific format, and the case of the format // specifier controls whether the exponent is prefixed with an 'E' or an // 'e'. // // N n Number format. The number is // converted to a string of the form "-d,ddd,ddd.ddd....", where // each 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative. Thousand separators are inserted between each group of // three digits to the left of the decimal point. The precision specifier // indicates the desired number of decimal places. If the precision specifier // is omitted, the default numeric precision given by the // NumberFormatInfo is used. // // X x - Hexadecimal format. This format is // supported for integral types only. The number is converted to a string of // hexadecimal digits. The format specifier indicates whether to use upper or // lower case characters for the hexadecimal digits above 9 ('X' for 'ABCDEF', // and 'x' for 'abcdef'). The precision specifier indicates the minimum number // of digits desired in the resulting string. If required, the number will be // left-padded with zeros to produce the number of digits given by the // precision specifier. // // Some examples of standard format strings and their results are shown in the // table below. (The examples all assume a default NumberFormatInfo.) // // Value Format Result // 12345.6789 C $12,345.68 // -12345.6789 C ($12,345.68) // 12345 D 12345 // 12345 D8 00012345 // 12345.6789 E 1.234568E+004 // 12345.6789 E10 1.2345678900E+004 // 12345.6789 e4 1.2346e+004 // 12345.6789 F 12345.68 // 12345.6789 F0 12346 // 12345.6789 F6 12345.678900 // 12345.6789 G 12345.6789 // 12345.6789 G7 12345.68 // 123456789 G7 1.234568E8 // 12345.6789 N 12,345.68 // 123456789 N4 123,456,789.0000 // 0x2c45e x 2c45e // 0x2c45e X 2C45E // 0x2c45e X8 0002C45E // // Format strings that do not start with an alphabetic character, or that start // with an alphabetic character followed by a non-digit, are called // user-defined format strings. The following table describes the formatting // characters that are supported in user defined format strings. // // // 0 - Digit placeholder. If the value being // formatted has a digit in the position where the '0' appears in the format // string, then that digit is copied to the output string. Otherwise, a '0' is // stored in that position in the output string. The position of the leftmost // '0' before the decimal point and the rightmost '0' after the decimal point // determines the range of digits that are always present in the output // string. // // # - Digit placeholder. If the value being // formatted has a digit in the position where the '#' appears in the format // string, then that digit is copied to the output string. Otherwise, nothing // is stored in that position in the output string. // // . - Decimal point. The first '.' character // in the format string determines the location of the decimal separator in the // formatted value; any additional '.' characters are ignored. The actual // character used as a the decimal separator in the output string is given by // the NumberFormatInfo used to format the number. // // , - Thousand separator and number scaling. // The ',' character serves two purposes. First, if the format string contains // a ',' character between two digit placeholders (0 or #) and to the left of // the decimal point if one is present, then the output will have thousand // separators inserted between each group of three digits to the left of the // decimal separator. The actual character used as a the decimal separator in // the output string is given by the NumberFormatInfo used to format the // number. Second, if the format string contains one or more ',' characters // immediately to the left of the decimal point, or after the last digit // placeholder if there is no decimal point, then the number will be divided by // 1000 times the number of ',' characters before it is formatted. For example, // the format string '0,,' will represent 100 million as just 100. Use of the // ',' character to indicate scaling does not also cause the formatted number // to have thousand separators. Thus, to scale a number by 1 million and insert // thousand separators you would use the format string '#,##0,,'. // // % - Percentage placeholder. The presence of // a '%' character in the format string causes the number to be multiplied by // 100 before it is formatted. The '%' character itself is inserted in the // output string where it appears in the format string. // // E+ E- e+ e- - Scientific notation. // If any of the strings 'E+', 'E-', 'e+', or 'e-' are present in the format // string and are immediately followed by at least one '0' character, then the // number is formatted using scientific notation with an 'E' or 'e' inserted // between the number and the exponent. The number of '0' characters following // the scientific notation indicator determines the minimum number of digits to // output for the exponent. The 'E+' and 'e+' formats indicate that a sign // character (plus or minus) should always precede the exponent. The 'E-' and // 'e-' formats indicate that a sign character should only precede negative // exponents. // // \ - Literal character. A backslash character // causes the next character in the format string to be copied to the output // string as-is. The backslash itself isn't copied, so to place a backslash // character in the output string, use two backslashes (\\) in the format // string. // // 'ABC' "ABC" - Literal string. Characters // enclosed in single or double quotation marks are copied to the output string // as-is and do not affect formatting. // // ; - Section separator. The ';' character is // used to separate sections for positive, negative, and zero numbers in the // format string. // // Other - All other characters are copied to // the output string in the position they appear. // // For fixed point formats (formats not containing an 'E+', 'E-', 'e+', or // 'e-'), the number is rounded to as many decimal places as there are digit // placeholders to the right of the decimal point. If the format string does // not contain a decimal point, the number is rounded to the nearest // integer. If the number has more digits than there are digit placeholders to // the left of the decimal point, the extra digits are copied to the output // string immediately before the first digit placeholder. // // For scientific formats, the number is rounded to as many significant digits // as there are digit placeholders in the format string. // // To allow for different formatting of positive, negative, and zero values, a // user-defined format string may contain up to three sections separated by // semicolons. The results of having one, two, or three sections in the format // string are described in the table below. // // Sections: // // One - The format string applies to all values. // // Two - The first section applies to positive values // and zeros, and the second section applies to negative values. If the number // to be formatted is negative, but becomes zero after rounding according to // the format in the second section, then the resulting zero is formatted // according to the first section. // // Three - The first section applies to positive // values, the second section applies to negative values, and the third section // applies to zeros. The second section may be left empty (by having no // characters between the semicolons), in which case the first section applies // to all non-zero values. If the number to be formatted is non-zero, but // becomes zero after rounding according to the format in the first or second // section, then the resulting zero is formatted according to the third // section. // // For both standard and user-defined formatting operations on values of type // float and double, if the value being formatted is a NaN (Not // a Number) or a positive or negative infinity, then regardless of the format // string, the resulting string is given by the NaNSymbol, // PositiveInfinitySymbol, or NegativeInfinitySymbol property of // the NumberFormatInfo used to format the number. // // Parsing // // The Parse methods provided by the numeric classes are all of the form // // public static XXX Parse(String s); // public static XXX Parse(String s, int style); // public static XXX Parse(String s, int style, NumberFormatInfo info); // // where XXX is the name of the particular numeric class. The methods convert a // string to a numeric value. The optional style parameter specifies the // permitted style of the numeric string. It must be a combination of bit flags // from the NumberStyles enumeration. The optional info parameter // specifies the NumberFormatInfo instance to use when parsing the // string. If the info parameter is null or omitted, the numeric // formatting information is obtained from the current culture. // // Numeric strings produced by the Format methods using the Currency, // Decimal, Engineering, Fixed point, General, or Number standard formats // (the C, D, E, F, G, and N format specifiers) are guaranteed to be parseable // by the Parse methods if the NumberStyles.Any style is // specified. Note, however, that the Parse methods do not accept // NaNs or Infinities. // using System.Diagnostics; using System.Globalization; using System.Security; using System.Text; namespace System.Numerics { internal static class BigNumber { private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier); private struct BigNumberBuffer { public StringBuilder digits; public int precision; public int scale; public bool sign; // negative sign exists public static BigNumberBuffer Create() { BigNumberBuffer number = new BigNumberBuffer(); number.digits = new StringBuilder(); return number; } } internal static bool TryValidateParseStyleInteger(NumberStyles style, out ArgumentException e) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { e = new ArgumentException("Argument_InvalidNumberStyles"); return false; } if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number if ((style & ~NumberStyles.HexNumber) != 0) { e = new ArgumentException("Argument_InvalidHexStyle"); return false; } } e = null; return true; } [SecuritySafeCritical] internal static bool TryParseBigInteger(string value, NumberStyles style, NumberFormatInfo info, out BigInteger result) { unsafe { result = BigInteger.Zero; ArgumentException e; if (!TryValidateParseStyleInteger(style, out e)) throw e; // TryParse still throws ArgumentException on invalid NumberStyles BigNumberBuffer bignumber = BigNumberBuffer.Create(); if (!FormatProvider.TryStringToBigInteger(value, style, info, bignumber.digits, out bignumber.precision, out bignumber.scale, out bignumber.sign)) return false; if ((style & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToBigInteger(ref bignumber, ref result)) { return false; } } else { if (!NumberToBigInteger(ref bignumber, ref result)) { return false; } } return true; } } internal static BigInteger ParseBigInteger(string value, NumberStyles style, NumberFormatInfo info) { if (value == null) throw new ArgumentNullException(nameof(value)); ArgumentException e; if (!TryValidateParseStyleInteger(style, out e)) throw e; BigInteger result = BigInteger.Zero; if (!TryParseBigInteger(value, style, info, out result)) { throw new FormatException("Overflow_ParseBigInteger"); } return result; } private unsafe static bool HexNumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value) { if (number.digits == null || number.digits.Length == 0) return false; int len = number.digits.Length - 1; // Ignore trailing '\0' byte[] bits = new byte[(len / 2) + (len % 2)]; bool shift = false; bool isNegative = false; int bitIndex = 0; // Parse the string into a little-endian two's complement byte array // string value : O F E B 7 \0 // string index (i) : 0 1 2 3 4 5 <-- // byte[] (bitIndex): 2 1 1 0 0 <-- // for (int i = len - 1; i > -1; i--) { char c = number.digits[i]; byte b; if (c >= '0' && c <= '9') { b = (byte)(c - '0'); } else if (c >= 'A' && c <= 'F') { b = (byte)((c - 'A') + 10); } else { Debug.Assert(c >= 'a' && c <= 'f'); b = (byte)((c - 'a') + 10); } if (i == 0 && (b & 0x08) == 0x08) isNegative = true; if (shift) { bits[bitIndex] = (byte)(bits[bitIndex] | (b << 4)); bitIndex++; } else { bits[bitIndex] = isNegative ? (byte)(b | 0xF0) : (b); } shift = !shift; } value = new BigInteger(bits); return true; } private unsafe static bool NumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value) { int i = number.scale; int cur = 0; BigInteger ten = 10; value = 0; while (--i >= 0) { value *= ten; if (number.digits[cur] != '\0') { value += number.digits[cur++] - '0'; } } while (number.digits[cur] != '\0') { if (number.digits[cur++] != '0') return false; // Disallow non-zero trailing decimal places } if (number.sign) { value = -value; } return true; } // This function is consistent with VM\COMNumber.cpp!COMNumber::ParseFormatSpecifier internal static char ParseFormatSpecifier(string format, out int digits) { digits = -1; if (string.IsNullOrEmpty(format)) { return 'R'; } int i = 0; char ch = format[i]; if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') { i++; int n = -1; if (i < format.Length && format[i] >= '0' && format[i] <= '9') { n = format[i++] - '0'; while (i < format.Length && format[i] >= '0' && format[i] <= '9') { n = n * 10 + (format[i++] - '0'); if (n >= 10) break; } } if (i >= format.Length || format[i] == '\0') { digits = n; return ch; } } return (char)0; // Custom format } private static string FormatBigIntegerToHexString(BigInteger value, char format, int digits, NumberFormatInfo info) { StringBuilder sb = new StringBuilder(); byte[] bits = value.ToByteArray(); string fmt = null; int cur = bits.Length - 1; if (cur > -1) { // [FF..F8] drop the high F as the two's complement negative number remains clear // [F7..08] retain the high bits as the two's complement number is wrong without it // [07..00] drop the high 0 as the two's complement positive number remains clear bool clearHighF = false; byte head = bits[cur]; if (head > 0xF7) { head -= 0xF0; clearHighF = true; } if (head < 0x08 || clearHighF) { // {0xF8-0xFF} print as {8-F} // {0x00-0x07} print as {0-7} fmt = string.Format(CultureInfo.InvariantCulture, "{0}1", format); sb.Append(head.ToString(fmt, info)); cur--; } } if (cur > -1) { fmt = string.Format(CultureInfo.InvariantCulture, "{0}2", format); while (cur > -1) { sb.Append(bits[cur--].ToString(fmt, info)); } } if (digits > 0 && digits > sb.Length) { // Insert leading zeros. User specified "X5" so we create "0ABCD" instead of "ABCD" sb.Insert(0, (value._sign >= 0 ? ("0") : (format == 'x' ? "f" : "F")), digits - sb.Length); } return sb.ToString(); } [SecuritySafeCritical] internal static string FormatBigInteger(BigInteger value, string format, NumberFormatInfo info) { int digits = 0; char fmt = ParseFormatSpecifier(format, out digits); if (fmt == 'x' || fmt == 'X') return FormatBigIntegerToHexString(value, fmt, digits, info); bool decimalFmt = (fmt == 'g' || fmt == 'G' || fmt == 'd' || fmt == 'D' || fmt == 'r' || fmt == 'R'); if (value._bits == null) { if (fmt == 'g' || fmt == 'G' || fmt == 'r' || fmt == 'R') { if (digits > 0) format = string.Format(CultureInfo.InvariantCulture, "D{0}", digits.ToString(CultureInfo.InvariantCulture)); else format = "D"; } return value._sign.ToString(format, info); } // First convert to base 10^9. const uint kuBase = 1000000000; // 10^9 const int kcchBase = 9; int cuSrc = value._bits.Length; int cuMax; try { cuMax = checked(cuSrc * 10 / 9 + 2); } catch (OverflowException e) { throw new FormatException("Format_TooLarge", e); } uint[] rguDst = new uint[cuMax]; int cuDst = 0; for (int iuSrc = cuSrc; --iuSrc >= 0;) { uint uCarry = value._bits[iuSrc]; for (int iuDst = 0; iuDst < cuDst; iuDst++) { Debug.Assert(rguDst[iuDst] < kuBase); ulong uuRes = NumericsHelpers.MakeUlong(rguDst[iuDst], uCarry); rguDst[iuDst] = (uint)(uuRes % kuBase); uCarry = (uint)(uuRes / kuBase); } if (uCarry != 0) { rguDst[cuDst++] = uCarry % kuBase; uCarry /= kuBase; if (uCarry != 0) rguDst[cuDst++] = uCarry; } } int cchMax; try { // Each uint contributes at most 9 digits to the decimal representation. cchMax = checked(cuDst * kcchBase); } catch (OverflowException e) { throw new FormatException("Format_TooLarge", e); } if (decimalFmt) { if (digits > 0 && digits > cchMax) cchMax = digits; if (value._sign < 0) { try { // Leave an extra slot for a minus sign. cchMax = checked(cchMax + info.NegativeSign.Length); } catch (OverflowException e) { throw new FormatException("Format_TooLarge", e); } } } int rgchBufSize; try { // We'll pass the rgch buffer to native code, which is going to treat it like a string of digits, so it needs // to be null terminated. Let's ensure that we can allocate a buffer of that size. rgchBufSize = checked(cchMax + 1); } catch (OverflowException e) { throw new FormatException("Format_TooLarge", e); } char[] rgch = new char[rgchBufSize]; int ichDst = cchMax; for (int iuDst = 0; iuDst < cuDst - 1; iuDst++) { uint uDig = rguDst[iuDst]; Debug.Assert(uDig < kuBase); for (int cch = kcchBase; --cch >= 0;) { rgch[--ichDst] = (char)('0' + uDig % 10); uDig /= 10; } } for (uint uDig = rguDst[cuDst - 1]; uDig != 0;) { rgch[--ichDst] = (char)('0' + uDig % 10); uDig /= 10; } if (!decimalFmt) { // sign = true for negative and false for 0 and positive values bool sign = (value._sign < 0); // The cut-off point to switch (G)eneral from (F)ixed-point to (E)xponential form int precision = 29; int scale = cchMax - ichDst; return FormatProvider.FormatBigInteger(precision, scale, sign, format, info, rgch, ichDst); } // Format Round-trip decimal // This format is supported for integral types only. The number is converted to a string of // decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision // specifier indicates the minimum number of digits desired in the resulting string. If required, // the number is padded with zeros to its left to produce the number of digits given by the // precision specifier. int numDigitsPrinted = cchMax - ichDst; while (digits > 0 && digits > numDigitsPrinted) { // pad leading zeros rgch[--ichDst] = '0'; digits--; } if (value._sign < 0) { string negativeSign = info.NegativeSign; for (int i = info.NegativeSign.Length - 1; i > -1; i--) rgch[--ichDst] = info.NegativeSign[i]; } return new string(rgch, ichDst, cchMax - ichDst); } } } #endif
// // System.Web.Services.Configuration.WebServicesConfigurationSectionHandler // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (C) 2003 Ximian, Inc (http://www.ximian.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; using System.Collections; using System.Configuration; using System.Xml; namespace System.Web.Services.Configuration { [Flags] enum WSProtocol { HttpSoap = 1, HttpPost = 1 << 1, HttpGet = 1 << 2, Documentation = 1 << 3, #if NET_1_1 HttpSoap12 = 1 << 4, HttpPostLocalhost = 1 << 5, #endif All = 0xFF } class WSConfig { #if !TARGET_JVM volatile static WSConfig instance; #else static WSConfig instance { get { return (WSConfig)AppDomain.CurrentDomain.GetData("WSConfig.instance"); } set { AppDomain.CurrentDomain.SetData("WSConfig.instance", value); } } #endif WSProtocol protocols; string wsdlHelpPage; string filePath; ArrayList extensionTypes = new ArrayList(); ArrayList extensionImporterTypes = new ArrayList(); ArrayList extensionReflectorTypes = new ArrayList(); ArrayList formatExtensionTypes = new ArrayList(); static readonly object lockobj = new object (); public WSConfig (WSConfig parent, object context) { if (parent == null) return; protocols = parent.protocols; wsdlHelpPage = parent.wsdlHelpPage; if (wsdlHelpPage != null) filePath = parent.filePath; else filePath = context as string; } static WSProtocol ParseProtocol (string protoName, out string error) { WSProtocol proto; error = null; #if ONLY_1_1 switch (protoName) { case "HttpSoap1.2": protoName = "HttpSoap12"; break; case "HttpSoap12": protoName = null; break; } #endif try { proto = (WSProtocol) Enum.Parse (typeof (WSProtocol), protoName); } catch { error = "Invalid protocol name"; return 0; } return proto; } // Methods to modify configuration values public bool AddProtocol (string protoName, out string error) { if (protoName == "All") { error = "Invalid protocol name"; return false; } WSProtocol proto = ParseProtocol (protoName, out error); if (error != null) return false; protocols |= proto; return true; } public bool RemoveProtocol (string protoName, out string error) { if (protoName == "All") { error = "Invalid protocol name"; return false; } WSProtocol proto = ParseProtocol (protoName, out error); if (error != null) return false; protocols &= ~proto; return true; } public void ClearProtocol () { protocols = 0; } // Methods to query/get configuration public static bool IsSupported (WSProtocol proto) { return ((Instance.protocols & proto) == proto && (proto != 0) && (proto != WSProtocol.All)); } // Properties public string WsdlHelpPage { get { return wsdlHelpPage; } set { wsdlHelpPage = value; } } public string ConfigFilePath { get { return filePath; } set { filePath = value; } } static public WSConfig Instance { get { //TODO: use HttpContext to get the configuration if (instance != null) return instance; lock (lockobj) { if (instance != null) return instance; instance = (WSConfig) ConfigurationSettings.GetConfig ("system.web/webServices"); } return instance; } } public ArrayList ExtensionTypes { get { return extensionTypes; } } public ArrayList ExtensionImporterTypes { get { return extensionImporterTypes; } } public ArrayList ExtensionReflectorTypes { get { return extensionReflectorTypes; } } public ArrayList FormatExtensionTypes { get { return formatExtensionTypes; } } } enum WSExtensionGroup { High, Low } class WSExtensionConfig { Type type; int priority; WSExtensionGroup group; public Exception SetType (string typeName) { Exception exc = null; try { type = Type.GetType (typeName, true); } catch (Exception e) { exc = e; } return exc; } public Exception SetPriority (string prio) { if (prio == null || prio == "") return null; Exception exc = null; try { priority = Int32.Parse (prio); } catch (Exception e) { exc = e; } return exc; } public Exception SetGroup (string grp) { if (grp == null || grp == "") return null; Exception exc = null; try { group = (WSExtensionGroup) Int32.Parse (grp); if (group < WSExtensionGroup.High || group > WSExtensionGroup.Low) throw new ArgumentOutOfRangeException ("group", "Must be 0 or 1"); } catch (Exception e) { exc = e; } return exc; } // Getters public Type Type { get { return type; } } public int Priority { get { return priority; } } public WSExtensionGroup Group { get { return group; } } } class WebServicesConfigurationSectionHandler : IConfigurationSectionHandler { public object Create (object parent, object context, XmlNode section) { WSConfig config = new WSConfig (parent as WSConfig, context); if (section.Attributes != null && section.Attributes.Count != 0) ThrowException ("Unrecognized attribute", section); XmlNodeList nodes = section.ChildNodes; foreach (XmlNode child in nodes) { XmlNodeType ntype = child.NodeType; if (ntype == XmlNodeType.Whitespace || ntype == XmlNodeType.Comment) continue; if (ntype != XmlNodeType.Element) ThrowException ("Only elements allowed", child); string name = child.Name; if (name == "protocols") { ConfigProtocols (child, config); continue; } if (name == "soapExtensionTypes") { ConfigSoapExtensionTypes (child, config.ExtensionTypes); continue; } if (name == "soapExtensionReflectorTypes") { ConfigSoapExtensionTypes (child, config.ExtensionReflectorTypes); continue; } if (name == "soapExtensionImporterTypes") { ConfigSoapExtensionTypes (child, config.ExtensionImporterTypes); continue; } if (name == "serviceDescriptionFormatExtensionTypes") { ConfigFormatExtensionTypes (child, config); continue; } if (name == "wsdlHelpGenerator") { string href = AttValue ("href", child, false); if (child.Attributes != null && child.Attributes.Count != 0) HandlersUtil.ThrowException ("Unrecognized attribute", child); config.ConfigFilePath = context as string; config.WsdlHelpPage = href; continue; } ThrowException ("Unexpected element", child); } return config; } static void ConfigProtocols (XmlNode section, WSConfig config) { if (section.Attributes != null && section.Attributes.Count != 0) ThrowException ("Unrecognized attribute", section); XmlNodeList nodes = section.ChildNodes; foreach (XmlNode child in nodes) { XmlNodeType ntype = child.NodeType; if (ntype == XmlNodeType.Whitespace || ntype == XmlNodeType.Comment) continue; if (ntype != XmlNodeType.Element) ThrowException ("Only elements allowed", child); string name = child.Name; string error; if (name == "add") { string protoName = AttValue ("name", child, false); if (child.Attributes != null && child.Attributes.Count != 0) HandlersUtil.ThrowException ("Unrecognized attribute", child); if (!config.AddProtocol (protoName, out error)) ThrowException (error, child); continue; } if (name == "remove") { string protoName = AttValue ("name", child, false); if (child.Attributes != null && child.Attributes.Count != 0) HandlersUtil.ThrowException ("Unrecognized attribute", child); if (!config.RemoveProtocol (protoName, out error)) ThrowException (error, child); continue; } if (name == "clear") { if (child.Attributes != null && child.Attributes.Count != 0) HandlersUtil.ThrowException ("Unrecognized attribute", child); config.ClearProtocol (); continue; } ThrowException ("Unexpected element", child); } } static void ConfigSoapExtensionTypes (XmlNode section, ArrayList extensions) { if (section.Attributes != null && section.Attributes.Count != 0) ThrowException ("Unrecognized attribute", section); XmlNodeList nodes = section.ChildNodes; foreach (XmlNode child in nodes) { XmlNodeType ntype = child.NodeType; if (ntype == XmlNodeType.Whitespace || ntype == XmlNodeType.Comment) continue; if (ntype != XmlNodeType.Element) ThrowException ("Only elements allowed", child); string name = child.Name; if (name == "add") { string seType = AttValue ("type", child, false); string priority = AttValue ("priority", child); string group = AttValue ("group", child); if (child.Attributes != null && child.Attributes.Count != 0) HandlersUtil.ThrowException ("Unrecognized attribute", child); WSExtensionConfig wse = new WSExtensionConfig (); Exception e = wse.SetType (seType); if (e != null) ThrowException (e.Message, child); e = wse.SetPriority (priority); if (e != null) ThrowException (e.Message, child); e = wse.SetGroup (group); if (e != null) ThrowException (e.Message, child); extensions.Add (wse); continue; } ThrowException ("Unexpected element", child); } } static void ConfigFormatExtensionTypes (XmlNode section, WSConfig config) { if (section.Attributes != null && section.Attributes.Count != 0) ThrowException ("Unrecognized attribute", section); XmlNodeList nodes = section.ChildNodes; foreach (XmlNode child in nodes) { XmlNodeType ntype = child.NodeType; if (ntype == XmlNodeType.Whitespace || ntype == XmlNodeType.Comment) continue; if (ntype != XmlNodeType.Element) ThrowException ("Only elements allowed", child); string name = child.Name; if (name == "add") { string typeName = AttValue ("name", child, false); if (child.Attributes != null && child.Attributes.Count != 0) HandlersUtil.ThrowException ("Unrecognized attribute", child); try { config.FormatExtensionTypes.Add (Type.GetType (typeName, true)); } catch (Exception e) { ThrowException (e.Message, child); } continue; } ThrowException ("Unexpected element", child); } } // To save some typing... static string AttValue (string name, XmlNode node, bool optional) { return HandlersUtil.ExtractAttributeValue (name, node, optional); } static string AttValue (string name, XmlNode node) { return HandlersUtil.ExtractAttributeValue (name, node, true); } static void ThrowException (string message, XmlNode node) { HandlersUtil.ThrowException (message, node); } // } class HandlersUtil { private HandlersUtil () { } static internal string ExtractAttributeValue (string attKey, XmlNode node) { return ExtractAttributeValue (attKey, node, false); } static internal string ExtractAttributeValue (string attKey, XmlNode node, bool optional) { if (node.Attributes == null) { if (optional) return null; ThrowException ("Required attribute not found: " + attKey, node); } XmlNode att = node.Attributes.RemoveNamedItem (attKey); if (att == null) { if (optional) return null; ThrowException ("Required attribute not found: " + attKey, node); } string value = att.Value; if (value == String.Empty) { string opt = optional ? "Optional" : "Required"; ThrowException (opt + " attribute is empty: " + attKey, node); } return value; } static internal void ThrowException (string msg, XmlNode node) { if (node != null && node.Name != String.Empty) msg = msg + " (node name: " + node.Name + ") "; throw new ConfigurationException (msg, node); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using osu.Framework.Development; using osu.Framework.Extensions.ImageExtensions; using osu.Framework.Graphics.Batches; using osu.Framework.Graphics.Primitives; using osuTK.Graphics.ES30; using osu.Framework.Statistics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.OpenGL.Vertices; using osu.Framework.Graphics.Textures; using osu.Framework.Lists; using osu.Framework.Platform; using osuTK; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using RectangleF = osu.Framework.Graphics.Primitives.RectangleF; namespace osu.Framework.Graphics.OpenGL.Textures { internal class TextureGLSingle : TextureGL { /// <summary> /// Contains all currently-active <see cref="TextureGLSingle"/>es. /// </summary> private static readonly LockedWeakList<TextureGLSingle> all_textures = new LockedWeakList<TextureGLSingle>(); public const int MAX_MIPMAP_LEVELS = 3; private static readonly Action<TexturedVertex2D> default_quad_action = new QuadBatch<TexturedVertex2D>(100, 1000).AddAction; private readonly Queue<ITextureUpload> uploadQueue = new Queue<ITextureUpload>(); /// <summary> /// Invoked when a new <see cref="TextureGLAtlas"/> is created. /// </summary> /// <remarks> /// Invocation from the draw or update thread cannot be assumed. /// </remarks> public static event Action<TextureGLSingle> TextureCreated; private int internalWidth; private int internalHeight; private readonly All filteringMode; private readonly Rgba32 initialisationColour; /// <summary> /// The total amount of times this <see cref="TextureGLSingle"/> was bound. /// </summary> public ulong BindCount { get; protected set; } // ReSharper disable once InconsistentlySynchronizedField (no need to lock here. we don't really care if the value is stale). public override bool Loaded => textureId > 0 || uploadQueue.Count > 0; public override RectangleI Bounds => new RectangleI(0, 0, Width, Height); /// <summary> /// Creates a new <see cref="TextureGLSingle"/>. /// </summary> /// <param name="width">The width of the texture.</param> /// <param name="height">The height of the texture.</param> /// <param name="manualMipmaps">Whether manual mipmaps will be uploaded to the texture. If false, the texture will compute mipmaps automatically.</param> /// <param name="filteringMode">The filtering mode.</param> /// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param> /// <param name="wrapModeT">The texture wrap mode in vertical direction.</param> /// <param name="initialisationColour">The colour to initialise texture levels with (in the case of sub region initial uploads).</param> public TextureGLSingle(int width, int height, bool manualMipmaps = false, All filteringMode = All.Linear, WrapMode wrapModeS = WrapMode.None, WrapMode wrapModeT = WrapMode.None, Rgba32 initialisationColour = default) : base(wrapModeS, wrapModeT) { Width = width; Height = height; this.manualMipmaps = manualMipmaps; this.filteringMode = filteringMode; this.initialisationColour = initialisationColour; all_textures.Add(this); TextureCreated?.Invoke(this); } /// <summary> /// Retrieves all currently-active <see cref="TextureGLSingle"/>s. /// </summary> public static TextureGLSingle[] GetAllTextures() => all_textures.ToArray(); #region Disposal ~TextureGLSingle() { Dispose(false); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); all_textures.Remove(this); while (tryGetNextUpload(out var upload)) upload.Dispose(); GLWrapper.ScheduleDisposal(texture => { int disposableId = texture.textureId; if (disposableId <= 0) return; GL.DeleteTextures(1, new[] { disposableId }); texture.memoryLease?.Dispose(); texture.textureId = 0; }, this); } #endregion #region Memory Tracking private List<long> levelMemoryUsage = new List<long>(); private NativeMemoryTracker.NativeMemoryLease memoryLease; private void updateMemoryUsage(int level, long newUsage) { levelMemoryUsage ??= new List<long>(); while (level >= levelMemoryUsage.Count) levelMemoryUsage.Add(0); levelMemoryUsage[level] = newUsage; memoryLease?.Dispose(); memoryLease = NativeMemoryTracker.AddMemory(this, getMemoryUsage()); } private long getMemoryUsage() { long usage = 0; for (int i = 0; i < levelMemoryUsage.Count; i++) usage += levelMemoryUsage[i]; return usage; } #endregion private int height; public override TextureGL Native => this; public override int Height { get => height; set => height = value; } private int width; public override int Width { get => width; set => width = value; } private int textureId; public override int TextureId { get { if (!Available) throw new ObjectDisposedException(ToString(), "Can not obtain ID of a disposed texture."); if (textureId == 0) throw new InvalidOperationException("Can not obtain ID of a texture before uploading it."); return textureId; } } /// <summary> /// Retrieves the size of this texture in bytes. /// </summary> public virtual int GetByteSize() => Width * Height * 4; private static void rotateVector(ref Vector2 toRotate, float sin, float cos) { float oldX = toRotate.X; toRotate.X = toRotate.X * cos - toRotate.Y * sin; toRotate.Y = oldX * sin + toRotate.Y * cos; } public override RectangleF GetTextureRect(RectangleF? textureRect) { RectangleF texRect = textureRect != null ? new RectangleF(textureRect.Value.X, textureRect.Value.Y, textureRect.Value.Width, textureRect.Value.Height) : new RectangleF(0, 0, Width, Height); texRect.X /= width; texRect.Y /= height; texRect.Width /= width; texRect.Height /= height; return texRect; } public const int VERTICES_PER_TRIANGLE = 4; internal override void DrawTriangle(Triangle vertexTriangle, ColourInfo drawColour, RectangleF? textureRect = null, Action<TexturedVertex2D> vertexAction = null, Vector2? inflationPercentage = null, RectangleF? textureCoords = null) { if (!Available) throw new ObjectDisposedException(ToString(), "Can not draw a triangle with a disposed texture."); RectangleF texRect = GetTextureRect(textureRect); Vector2 inflationAmount = inflationPercentage.HasValue ? new Vector2(inflationPercentage.Value.X * texRect.Width, inflationPercentage.Value.Y * texRect.Height) : Vector2.Zero; // If clamp to edge is active, allow the texture coordinates to penetrate by half the repeated atlas margin width if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge || GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge) { Vector2 inflationVector = Vector2.Zero; const int mipmap_padding_requirement = (1 << MAX_MIPMAP_LEVELS) / 2; if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge) inflationVector.X = mipmap_padding_requirement / (float)width; if (GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge) inflationVector.Y = mipmap_padding_requirement / (float)height; texRect = texRect.Inflate(inflationVector); } RectangleF coordRect = GetTextureRect(textureCoords ?? textureRect); RectangleF inflatedCoordRect = coordRect.Inflate(inflationAmount); vertexAction ??= default_quad_action; // We split the triangle into two, such that we can obtain smooth edges with our // texture coordinate trick. We might want to revert this to drawing a single // triangle in case we ever need proper texturing, or if the additional vertices // end up becoming an overhead (unlikely). SRGBColour topColour = (drawColour.TopLeft + drawColour.TopRight) / 2; SRGBColour bottomColour = (drawColour.BottomLeft + drawColour.BottomRight) / 2; vertexAction(new TexturedVertex2D { Position = vertexTriangle.P0, TexturePosition = new Vector2((inflatedCoordRect.Left + inflatedCoordRect.Right) / 2, inflatedCoordRect.Top), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = inflationAmount, Colour = topColour.Linear, }); vertexAction(new TexturedVertex2D { Position = vertexTriangle.P1, TexturePosition = new Vector2(inflatedCoordRect.Left, inflatedCoordRect.Bottom), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = inflationAmount, Colour = drawColour.BottomLeft.Linear, }); vertexAction(new TexturedVertex2D { Position = (vertexTriangle.P1 + vertexTriangle.P2) / 2, TexturePosition = new Vector2((inflatedCoordRect.Left + inflatedCoordRect.Right) / 2, inflatedCoordRect.Bottom), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = inflationAmount, Colour = bottomColour.Linear, }); vertexAction(new TexturedVertex2D { Position = vertexTriangle.P2, TexturePosition = new Vector2(inflatedCoordRect.Right, inflatedCoordRect.Bottom), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = inflationAmount, Colour = drawColour.BottomRight.Linear, }); FrameStatistics.Add(StatisticsCounterType.Pixels, (long)vertexTriangle.Area); } public const int VERTICES_PER_QUAD = 4; internal override void DrawQuad(Quad vertexQuad, ColourInfo drawColour, RectangleF? textureRect = null, Action<TexturedVertex2D> vertexAction = null, Vector2? inflationPercentage = null, Vector2? blendRangeOverride = null, RectangleF? textureCoords = null) { if (!Available) throw new ObjectDisposedException(ToString(), "Can not draw a quad with a disposed texture."); RectangleF texRect = GetTextureRect(textureRect); Vector2 inflationAmount = inflationPercentage.HasValue ? new Vector2(inflationPercentage.Value.X * texRect.Width, inflationPercentage.Value.Y * texRect.Height) : Vector2.Zero; // If clamp to edge is active, allow the texture coordinates to penetrate by half the repeated atlas margin width if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge || GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge) { Vector2 inflationVector = Vector2.Zero; const int mipmap_padding_requirement = (1 << MAX_MIPMAP_LEVELS) / 2; if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge) inflationVector.X = mipmap_padding_requirement / (float)width; if (GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge) inflationVector.Y = mipmap_padding_requirement / (float)height; texRect = texRect.Inflate(inflationVector); } RectangleF coordRect = GetTextureRect(textureCoords ?? textureRect); RectangleF inflatedCoordRect = coordRect.Inflate(inflationAmount); Vector2 blendRange = blendRangeOverride ?? inflationAmount; vertexAction ??= default_quad_action; vertexAction(new TexturedVertex2D { Position = vertexQuad.BottomLeft, TexturePosition = new Vector2(inflatedCoordRect.Left, inflatedCoordRect.Bottom), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = blendRange, Colour = drawColour.BottomLeft.Linear, }); vertexAction(new TexturedVertex2D { Position = vertexQuad.BottomRight, TexturePosition = new Vector2(inflatedCoordRect.Right, inflatedCoordRect.Bottom), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = blendRange, Colour = drawColour.BottomRight.Linear, }); vertexAction(new TexturedVertex2D { Position = vertexQuad.TopRight, TexturePosition = new Vector2(inflatedCoordRect.Right, inflatedCoordRect.Top), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = blendRange, Colour = drawColour.TopRight.Linear, }); vertexAction(new TexturedVertex2D { Position = vertexQuad.TopLeft, TexturePosition = new Vector2(inflatedCoordRect.Left, inflatedCoordRect.Top), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = blendRange, Colour = drawColour.TopLeft.Linear, }); FrameStatistics.Add(StatisticsCounterType.Pixels, (long)vertexQuad.Area); } internal override void SetData(ITextureUpload upload, WrapMode wrapModeS, WrapMode wrapModeT, Opacity? uploadOpacity) { if (!Available) throw new ObjectDisposedException(ToString(), "Can not set data of a disposed texture."); if (upload.Bounds.IsEmpty && upload.Data.Length > 0) { upload.Bounds = Bounds; if (width * height > upload.Data.Length) throw new InvalidOperationException($"Size of texture upload ({width}x{height}) does not contain enough data ({upload.Data.Length} < {width * height})"); } UpdateOpacity(upload, ref uploadOpacity); lock (uploadQueue) { bool requireUpload = uploadQueue.Count == 0; uploadQueue.Enqueue(upload); if (requireUpload && !BypassTextureUploadQueueing) GLWrapper.EnqueueTextureUpload(this); } } internal override bool Bind(TextureUnit unit, WrapMode wrapModeS, WrapMode wrapModeT) { if (!Available) throw new ObjectDisposedException(ToString(), "Can not bind a disposed texture."); Upload(); if (textureId <= 0) return false; if (GLWrapper.BindTexture(this, unit, wrapModeS, wrapModeT)) BindCount++; return true; } private bool manualMipmaps; internal override unsafe bool Upload() { if (!Available) return false; // We should never run raw OGL calls on another thread than the main thread due to race conditions. ThreadSafety.EnsureDrawThread(); bool didUpload = false; while (tryGetNextUpload(out ITextureUpload upload)) { using (upload) { fixed (Rgba32* ptr = upload.Data) DoUpload(upload, (IntPtr)ptr); didUpload = true; } } if (didUpload && !manualMipmaps) { GL.Hint(HintTarget.GenerateMipmapHint, HintMode.Nicest); GL.GenerateMipmap(TextureTarget.Texture2D); } return didUpload; } internal override void FlushUploads() { while (tryGetNextUpload(out var upload)) upload.Dispose(); } private bool tryGetNextUpload(out ITextureUpload upload) { lock (uploadQueue) { if (uploadQueue.Count == 0) { upload = null; return false; } upload = uploadQueue.Dequeue(); return true; } } protected virtual void DoUpload(ITextureUpload upload, IntPtr dataPointer) { // Do we need to generate a new texture? if (textureId <= 0 || internalWidth != width || internalHeight != height) { internalWidth = width; internalHeight = height; // We only need to generate a new texture if we don't have one already. Otherwise just re-use the current one. if (textureId <= 0) { int[] textures = new int[1]; GL.GenTextures(1, textures); textureId = textures[0]; GLWrapper.BindTexture(this); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureBaseLevel, 0); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMaxLevel, MAX_MIPMAP_LEVELS); // These shouldn't be required, but on some older Intel drivers the MAX_LOD chosen by the shader isn't clamped to the MAX_LEVEL from above, resulting in disappearing textures. GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinLod, 0); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMaxLod, MAX_MIPMAP_LEVELS); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)(manualMipmaps ? filteringMode : filteringMode == All.Linear ? All.LinearMipmapLinear : All.Nearest)); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)filteringMode); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); } else GLWrapper.BindTexture(this); if (width == upload.Bounds.Width && height == upload.Bounds.Height || dataPointer == IntPtr.Zero) { updateMemoryUsage(upload.Level, (long)width * height * 4); GL.TexImage2D(TextureTarget2d.Texture2D, upload.Level, TextureComponentCount.Srgb8Alpha8, width, height, 0, upload.Format, PixelType.UnsignedByte, dataPointer); } else { initializeLevel(upload.Level, width, height); GL.TexSubImage2D(TextureTarget2d.Texture2D, upload.Level, upload.Bounds.X, upload.Bounds.Y, upload.Bounds.Width, upload.Bounds.Height, upload.Format, PixelType.UnsignedByte, dataPointer); } } // Just update content of the current texture else if (dataPointer != IntPtr.Zero) { GLWrapper.BindTexture(this); if (!manualMipmaps && upload.Level > 0) { //allocate mipmap levels int level = 1; int d = 2; while (width / d > 0) { initializeLevel(level, width / d, height / d); level++; d *= 2; } manualMipmaps = true; } int div = (int)Math.Pow(2, upload.Level); GL.TexSubImage2D(TextureTarget2d.Texture2D, upload.Level, upload.Bounds.X / div, upload.Bounds.Y / div, upload.Bounds.Width / div, upload.Bounds.Height / div, upload.Format, PixelType.UnsignedByte, dataPointer); } } private void initializeLevel(int level, int width, int height) { using (var image = createBackingImage(width, height)) using (var pixels = image.CreateReadOnlyPixelSpan()) { updateMemoryUsage(level, (long)width * height * 4); GL.TexImage2D(TextureTarget2d.Texture2D, level, TextureComponentCount.Srgb8Alpha8, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, ref MemoryMarshal.GetReference(pixels.Span)); } } private Image<Rgba32> createBackingImage(int width, int height) { // it is faster to initialise without a background specification if transparent black is all that's required. return initialisationColour == default ? new Image<Rgba32>(width, height) : new Image<Rgba32>(width, height, initialisationColour); } } }
using System; using EnsureThat; using EnsureThat.Internals; using Xunit; namespace UnitTests { public class EnsureTypeParamTests : UnitTestBase { private class Bogus { } private class NonBogus { } private class AssignableToNonBogus : NonBogus { } private static readonly Type BogusType = typeof(Bogus); private static readonly Type NonBogusType = typeof(NonBogus); private static readonly Type AssignableToNonBogusType = typeof(AssignableToNonBogus); [Fact] public void IsOfType_WhenNotTypeOf_ThrowsArgumentException() => AssertIsOfTypeScenario( NonBogusType, BogusType, () => Ensure.Type.IsOfType(typeof(Bogus), NonBogusType, ParamName), () => Ensure.Type.IsOfType(new Bogus(), NonBogusType, ParamName), () => EnsureArg.IsOfType(typeof(Bogus), NonBogusType, ParamName), () => EnsureArg.IsOfType(new Bogus(), NonBogusType, ParamName), () => Ensure.ThatType(typeof(Bogus), ParamName).IsOfType(NonBogusType), () => Ensure.ThatTypeFor(new Bogus(), ParamName).IsOfType(NonBogusType)); [Fact] public void IsOfType_WhenIsCorrectType_It_should_not_throw() => ShouldNotThrow( () => Ensure.Type.IsOfType(BogusType, BogusType, ParamName), () => Ensure.Type.IsOfType(new Bogus(), BogusType, ParamName), () => EnsureArg.IsOfType(BogusType, BogusType, ParamName), () => EnsureArg.IsOfType(new Bogus(), BogusType, ParamName), () => Ensure.ThatType(typeof(Bogus), ParamName).IsOfType(BogusType), () => Ensure.ThatTypeFor(new Bogus(), ParamName).IsOfType(BogusType)); [Fact] public void IsNotOfType_WhenTypeOf_ThrowsArgumentException() => ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Types_IsNotOfType_Failed, BogusType), () => Ensure.Type.IsNotOfType(typeof(Bogus), BogusType, ParamName), () => Ensure.Type.IsNotOfType(new Bogus(), BogusType, ParamName), () => EnsureArg.IsNotOfType(typeof(Bogus), BogusType, ParamName), () => EnsureArg.IsNotOfType(new Bogus(), BogusType, ParamName), () => Ensure.ThatType(typeof(Bogus), ParamName).IsNotOfType(BogusType), () => Ensure.ThatTypeFor(new Bogus(), ParamName).IsNotOfType(BogusType)); [Fact] public void IsNotOfType_WhenIsNotTheType_It_should_not_throw() => ShouldNotThrow( () => Ensure.Type.IsNotOfType(BogusType, NonBogusType, ParamName), () => Ensure.Type.IsNotOfType(new Bogus(), NonBogusType, ParamName), () => EnsureArg.IsNotOfType(BogusType, NonBogusType, ParamName), () => EnsureArg.IsNotOfType(new Bogus(), NonBogusType, ParamName), () => Ensure.ThatType(typeof(Bogus), ParamName).IsNotOfType(NonBogusType), () => Ensure.ThatTypeFor(new Bogus(), ParamName).IsNotOfType(NonBogusType)); [Fact] public void IsAssignableToType_WhenNotAssignableToType_ThrowsArgumentException() => AssertIsAssignableToTypeScenario( NonBogusType, BogusType, () => Ensure.Type.IsAssignableToType(typeof(Bogus), NonBogusType, ParamName), () => Ensure.Type.IsAssignableToType(new Bogus(), NonBogusType, ParamName), () => EnsureArg.IsAssignableToType(typeof(Bogus), NonBogusType, ParamName), () => EnsureArg.IsAssignableToType(new Bogus(), NonBogusType, ParamName), () => Ensure.ThatType(typeof(Bogus), ParamName).IsAssignableToType(NonBogusType), () => Ensure.ThatTypeFor(new Bogus(), ParamName).IsAssignableToType(NonBogusType)); [Fact] public void IsAssignableToType_WhenAssignableToType_It_should_not_throw() => ShouldNotThrow( () => Ensure.Type.IsAssignableToType(NonBogusType, NonBogusType, ParamName), () => Ensure.Type.IsAssignableToType(new NonBogus(), NonBogusType, ParamName), () => EnsureArg.IsAssignableToType(NonBogusType, NonBogusType, ParamName), () => EnsureArg.IsAssignableToType(new NonBogus(), NonBogusType, ParamName), () => Ensure.ThatType(typeof(NonBogus), ParamName).IsAssignableToType(NonBogusType), () => Ensure.ThatTypeFor(new NonBogus(), ParamName).IsAssignableToType(NonBogusType), () => Ensure.Type.IsAssignableToType(AssignableToNonBogusType, NonBogusType, ParamName), () => Ensure.Type.IsAssignableToType(new AssignableToNonBogus(), NonBogusType, ParamName), () => EnsureArg.IsAssignableToType(AssignableToNonBogusType, NonBogusType, ParamName), () => EnsureArg.IsAssignableToType(new AssignableToNonBogus(), NonBogusType, ParamName), () => Ensure.ThatType(typeof(AssignableToNonBogus), ParamName).IsAssignableToType(NonBogusType), () => Ensure.ThatTypeFor(new AssignableToNonBogus(), ParamName).IsAssignableToType(NonBogusType)); [Fact] public void IsNotAssignableToType_WhenAssignableToType_ThrowsArgumentException() => ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Types_IsNotAssignableToType_Failed, NonBogusType), () => Ensure.Type.IsNotAssignableToType(typeof(NonBogus), NonBogusType, ParamName), () => Ensure.Type.IsNotAssignableToType(new NonBogus(), NonBogusType, ParamName), () => EnsureArg.IsNotAssignableToType(typeof(NonBogus), NonBogusType, ParamName), () => EnsureArg.IsNotAssignableToType(new NonBogus(), NonBogusType, ParamName), () => Ensure.ThatType(typeof(NonBogus), ParamName).IsNotAssignableToType(NonBogusType), () => Ensure.ThatTypeFor(new NonBogus(), ParamName).IsNotAssignableToType(NonBogusType), () => Ensure.Type.IsNotAssignableToType(typeof(AssignableToNonBogus), NonBogusType, ParamName), () => Ensure.Type.IsNotAssignableToType(new AssignableToNonBogus(), NonBogusType, ParamName), () => EnsureArg.IsNotAssignableToType(typeof(AssignableToNonBogus), NonBogusType, ParamName), () => EnsureArg.IsNotAssignableToType(new AssignableToNonBogus(), NonBogusType, ParamName), () => Ensure.ThatType(typeof(AssignableToNonBogus), ParamName).IsNotAssignableToType(NonBogusType), () => Ensure.ThatTypeFor(new AssignableToNonBogus(), ParamName).IsNotAssignableToType(NonBogusType)); [Fact] public void IsNotAssignableToType_WhenNotAssignableToType_It_should_not_throw() => ShouldNotThrow( () => Ensure.Type.IsNotAssignableToType(BogusType, NonBogusType, ParamName), () => Ensure.Type.IsNotAssignableToType(new Bogus(), NonBogusType, ParamName), () => EnsureArg.IsNotAssignableToType(BogusType, NonBogusType, ParamName), () => EnsureArg.IsNotAssignableToType(new Bogus(), NonBogusType, ParamName), () => Ensure.ThatType(typeof(Bogus), ParamName).IsNotAssignableToType(NonBogusType), () => Ensure.ThatTypeFor(new Bogus(), ParamName).IsNotAssignableToType(NonBogusType)); [Fact] public void IsInt_WhenNotTypeOf_ThrowsArgumentException() => AssertIsOfTypeScenario( typeof(int), typeof(decimal), () => Ensure.Type.IsInt(typeof(decimal), ParamName), () => Ensure.Type.IsInt(42m, ParamName), () => EnsureArg.IsInt(typeof(decimal), ParamName), () => EnsureArg.IsInt(42m, ParamName), () => Ensure.ThatType(typeof(decimal), ParamName).IsInt(), () => Ensure.ThatTypeFor(42m, ParamName).IsInt()); [Fact] public void IsInt_WhenIsCorrectType_It_should_not_throw() => ShouldNotThrow( () => Ensure.Type.IsInt(typeof(int), ParamName), () => Ensure.Type.IsInt(42, ParamName), () => EnsureArg.IsInt(typeof(int), ParamName), () => EnsureArg.IsInt(42, ParamName), () => Ensure.ThatType(typeof(int), ParamName).IsInt(), () => Ensure.ThatTypeFor(42, ParamName).IsInt()); [Fact] public void IsShort_WhenNotTypeOf_ThrowsArgumentException() => AssertIsOfTypeScenario( typeof(short), typeof(int), () => Ensure.Type.IsShort(typeof(int), ParamName), () => Ensure.Type.IsShort(42, ParamName), () => EnsureArg.IsShort(typeof(int), ParamName), () => EnsureArg.IsShort(42, ParamName), () => Ensure.ThatType(typeof(int), ParamName).IsShort(), () => Ensure.ThatTypeFor(42, ParamName).IsShort()); [Fact] public void IsShort_WhenIsCorrectType_It_should_not_throw() => ShouldNotThrow( () => Ensure.Type.IsShort(typeof(short), ParamName), () => Ensure.Type.IsShort((short)42, ParamName), () => EnsureArg.IsShort(typeof(short), ParamName), () => EnsureArg.IsShort((short)42, ParamName), () => Ensure.ThatType(typeof(short), ParamName).IsShort(), () => Ensure.ThatTypeFor((short)42, ParamName).IsShort()); [Fact] public void IsDecimal_WhenNotTypeOf_ThrowsArgumentException() => AssertIsOfTypeScenario( typeof(decimal), typeof(int), () => Ensure.Type.IsDecimal(typeof(int), ParamName), () => Ensure.Type.IsDecimal(42, ParamName), () => EnsureArg.IsDecimal(typeof(int), ParamName), () => EnsureArg.IsDecimal(42, ParamName), () => Ensure.ThatType(typeof(int), ParamName).IsDecimal(), () => Ensure.ThatTypeFor(42, ParamName).IsDecimal()); [Fact] public void IsDecimal_WhenIsCorrectType_It_should_not_throw() => ShouldNotThrow( () => Ensure.Type.IsDecimal(typeof(decimal), ParamName), () => Ensure.Type.IsDecimal(42.33m, ParamName), () => EnsureArg.IsDecimal(typeof(decimal), ParamName), () => EnsureArg.IsDecimal(42.33m, ParamName), () => Ensure.ThatType(typeof(decimal), ParamName).IsDecimal(), () => Ensure.ThatTypeFor(42.33m, ParamName).IsDecimal()); [Fact] public void IsDouble_WhenNotTypeOf_ThrowsArgumentException() => AssertIsOfTypeScenario( typeof(double), typeof(int), () => Ensure.Type.IsDouble(typeof(int), ParamName), () => Ensure.Type.IsDouble(42, ParamName), () => EnsureArg.IsDouble(typeof(int), ParamName), () => EnsureArg.IsDouble(42, ParamName), () => Ensure.ThatType(typeof(int), ParamName).IsDouble(), () => Ensure.ThatTypeFor(42, ParamName).IsDouble()); [Fact] public void IsDouble_WhenIsCorrectType_It_should_not_throw() => ShouldNotThrow( () => Ensure.Type.IsDouble(typeof(double), ParamName), () => Ensure.Type.IsDouble(42.33, ParamName), () => EnsureArg.IsDouble(typeof(double), ParamName), () => EnsureArg.IsDouble(42.33, ParamName), () => Ensure.ThatType(typeof(double), ParamName).IsDouble(), () => Ensure.ThatTypeFor(42.33, ParamName).IsDouble()); [Fact] public void IsFloat_WhenNotTypeOf_ThrowsArgumentException() => AssertIsOfTypeScenario( typeof(float), typeof(int), () => Ensure.Type.IsFloat(typeof(int), ParamName), () => Ensure.Type.IsFloat(42, ParamName), () => EnsureArg.IsFloat(typeof(int), ParamName), () => EnsureArg.IsFloat(42, ParamName), () => Ensure.ThatType(typeof(int), ParamName).IsFloat(), () => Ensure.ThatTypeFor(42, ParamName).IsFloat()); [Fact] public void IsFloat_WhenIsCorrectType_It_should_not_throw() { const float value = (float)42.33; ShouldNotThrow( () => Ensure.Type.IsFloat(typeof(float), ParamName), () => Ensure.Type.IsFloat(value, ParamName), () => EnsureArg.IsFloat(typeof(float), ParamName), () => EnsureArg.IsFloat(value, ParamName), () => Ensure.ThatType(typeof(float), ParamName).IsFloat(), () => Ensure.ThatTypeFor(value, ParamName).IsFloat()); } [Fact] public void IsBool_WhenNotTypeOf_ThrowsArgumentException() => AssertIsOfTypeScenario( typeof(bool), typeof(int), () => Ensure.Type.IsBool(typeof(int), ParamName), () => Ensure.Type.IsBool(42, ParamName), () => EnsureArg.IsBool(typeof(int), ParamName), () => EnsureArg.IsBool(42, ParamName), () => Ensure.ThatType(typeof(int), ParamName).IsBool(), () => Ensure.ThatTypeFor(42, ParamName).IsBool()); [Fact] public void IsBool_WhenIsCorrectType_It_should_not_throw() { const bool value = true; ShouldNotThrow( () => Ensure.Type.IsBool(typeof(bool), ParamName), () => Ensure.Type.IsBool(value, ParamName), () => EnsureArg.IsBool(typeof(bool), ParamName), () => EnsureArg.IsBool(value, ParamName), () => Ensure.ThatType(typeof(bool), ParamName).IsBool(), () => Ensure.ThatTypeFor(value, ParamName).IsBool()); } [Fact] public void IsDateTime_WhenNotTypeOf_ThrowsArgumentException() => AssertIsOfTypeScenario( typeof(DateTime), typeof(int), () => Ensure.Type.IsDateTime(typeof(int), ParamName), () => Ensure.Type.IsDateTime(42, ParamName), () => EnsureArg.IsDateTime(typeof(int), ParamName), () => EnsureArg.IsDateTime(42, ParamName), () => Ensure.ThatType(typeof(int), ParamName).IsDateTime(), () => Ensure.ThatTypeFor(42, ParamName).IsDateTime()); [Fact] public void IsDateTime_WhenIsCorrectType_It_should_not_throw() { var value = DateTime.Now; ShouldNotThrow( () => Ensure.Type.IsDateTime(typeof(DateTime), ParamName), () => Ensure.Type.IsDateTime(value, ParamName), () => EnsureArg.IsDateTime(typeof(DateTime), ParamName), () => EnsureArg.IsDateTime(value, ParamName), () => Ensure.ThatType(typeof(DateTime), ParamName).IsDateTime(), () => Ensure.ThatTypeFor(value, ParamName).IsDateTime()); } [Fact] public void IsString_WhenNotTypeOf_ThrowsArgumentException() => AssertIsOfTypeScenario( typeof(string), typeof(int), () => Ensure.Type.IsString(typeof(int), ParamName), () => Ensure.Type.IsString(42, ParamName), () => EnsureArg.IsString(typeof(int), ParamName), () => EnsureArg.IsString(42, ParamName), () => Ensure.ThatType(typeof(int), ParamName).IsString(), () => Ensure.ThatTypeFor(42, ParamName).IsString()); [Fact] public void IsString_WhenIsCorrectType_It_should_not_throw() { var value = string.Empty; ShouldNotThrow( () => Ensure.Type.IsString(typeof(string), ParamName), () => Ensure.Type.IsString(value, ParamName), () => EnsureArg.IsString(typeof(string), ParamName), () => EnsureArg.IsString(value, ParamName), () => Ensure.ThatType(typeof(string), ParamName).IsString(), () => Ensure.ThatTypeFor(value, ParamName).IsString()); } [Fact] public void IsClass_WhenIsNotClass_ThrowsArgumentException() => AssertIsNotClass( typeof(int), () => Ensure.Type.IsClass(typeof(int), ParamName), () => Ensure.Type.IsClass(42, ParamName), () => EnsureArg.IsClass(typeof(int), ParamName), () => EnsureArg.IsClass(42, ParamName), () => Ensure.ThatType(typeof(int), ParamName).IsClass(), () => Ensure.ThatTypeFor(42, ParamName).IsClass()); [Fact] public void IsClass_WhenPassingNull_ThrowsArgumentNullException() => ShouldThrow<ArgumentNullException>( ExceptionMessages.Types_IsClass_Failed_Null, () => Ensure.Type.IsClass(null, ParamName), () => EnsureArg.IsClass(null, ParamName), () => Ensure.ThatType(null, ParamName).IsClass()); [Fact] public void IsClass_WhenIsClass_It_should_not_throw() { var value = new MyClass(); ShouldNotThrow( () => Ensure.Type.IsClass(typeof(MyClass), ParamName), () => Ensure.Type.IsClass(value, ParamName), () => EnsureArg.IsClass(typeof(MyClass), ParamName), () => EnsureArg.IsClass(value, ParamName), () => Ensure.ThatType(typeof(MyClass), ParamName).IsClass(), () => Ensure.ThatTypeFor(value, ParamName).IsClass()); } private static void AssertIsOfTypeScenario(Type expected, Type actual, params Action[] actions) => ShouldThrow<ArgumentException>(string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Types_IsOfType_Failed, expected.FullName, actual.FullName), actions); private static void AssertIsAssignableToTypeScenario(Type expected, Type actual, params Action[] actions) => ShouldThrow<ArgumentException>(string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Types_IsAssignableToType_Failed, expected.FullName, actual.FullName), actions); private static void AssertIsNotClass(Type type, params Action[] actions) => ShouldThrow<ArgumentException>(string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Types_IsClass_Failed, type.FullName), actions); private class MyClass { } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Diagnostics; using System.IO.Ports; using System.IO; namespace CRVV { public partial class CRVV : Form { string file = Directory.GetCurrentDirectory() + "INT.UAS"; int dec = 0; SerialPort spot = new SerialPort("COM69", 9600); int spo = 0; public CRVV() { InitializeComponent(); try { spot.Open(); spot.Write("CRVV: Hello Server,How Are You Today?"); spot.Write("CRVVSERV: Oh Thanks, Good"); spot.Write("CRVV: Soooo, What We Are Going To Do?"); spot.Write("CRVVSERV: Let's Convert"); spo = 1; } catch { MessageBox.Show(this, "Not Found a CRVV Serv on this machine", "[CRVVMBHQ]", MessageBoxButtons.OK, MessageBoxIcon.Information); spo = 0; } if (File.Exists(file)) { if (spo == 1) { spot.Write("CRVVFL:Files Found"); } MessageBox.Show(this, "Files Sucessfully Loaded!!!", "[CRVVMBHQ]", MessageBoxButtons.OK, MessageBoxIcon.Information); Flip.Enabled = true; Morse.Enabled = true; HTML.Enabled = true; Vir.Enabled = true; Dec.Enabled = true; Bin.Enabled = true; Hex.Enabled = true; Atbash.Enabled = true; Cesar.Enabled = true; NATO.Enabled = true; Base.Enabled = true; ROT.Enabled = true; IUPAC.Enabled = true; CTC.Enabled = true; dore.Enabled = true; MP.Enabled = true; VSC.Enabled = true; CSN.Enabled = true; ROTVSV.Enabled = true; button2.Enabled = true; } else { if (spo == 1) { spot.Write("CRVVFL:Files NOT Found"); } MessageBox.Show(this, "Files Not Loaded", "[CRVVMBHQ]", MessageBoxButtons.OK, MessageBoxIcon.Error); Flip.Enabled = false; Morse.Enabled = false; HTML.Enabled = false; Vir.Enabled = false; Dec.Enabled = false; Bin.Enabled = false; Hex.Enabled = false; Atbash.Enabled = false; Cesar.Enabled = false; NATO.Enabled = false; Base.Enabled = false; ROT.Enabled = false; IUPAC.Enabled = false; CTC.Enabled = false; dore.Enabled = false; MP.Enabled = false; VSC.Enabled = false; CSN.Enabled = false; ROTVSV.Enabled = false; button2.Enabled = false; } } public void CRVVD() { if (File.Exists(file)) { Flip.Enabled = true; Morse.Enabled = true; HTML.Enabled = true; Vir.Enabled = true; Dec.Enabled = true; Bin.Enabled = true; Hex.Enabled = true; Atbash.Enabled = true; Cesar.Enabled = true; NATO.Enabled = true; Base.Enabled = true; ROT.Enabled = true; IUPAC.Enabled = true; CTC.Enabled = true; dore.Enabled = true; MP.Enabled = true; VSC.Enabled = true; CSN.Enabled = true; ROTVSV.Enabled = true; button2.Enabled = true; MessageBox.Show(this, "Files Sucessfully Loaded!!!", "[CRVVMBHQ]", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void textBox1_TextChanged(object sender, EventArgs e) { } private void CRVV_Load(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "BINARY " + io); } if (dec == 1) { string s = io; string result = ""; while (s.Length > 0) { var first8 = s.Substring(0, 8); s = s.Substring(8); var number = Convert.ToInt32(first8, 2); result += (char)number; } oi.Text = oi.Text + result; } if (dec == 0) { string str = io; string converted = string.Empty; byte[] byteArray = Encoding.ASCII.GetBytes(str); for (int i = 0; i < byteArray.Length; i++) { for (int j = 0; j < 8; j++) { converted += (byteArray[i] & 0x80) > 0 ? "1" : "0"; byteArray[i] <<= 1; } } oi.Text = oi.Text + converted; } } private void Flip_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "Flipping " + io); } char[] txt = io.ToArray(); int i = 0; int j = txt.Length - 1; while (i < j) { char t = txt[i]; txt[i] = txt[j]; txt[j] = t; ++i; --j; } string o = new string(txt); oi.Text = o; } private void label2_Click(object sender, EventArgs e) { } private void Morse_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "Morse " + io); } if (dec == 1) { string moutput = io.Replace(".- ", "A").Replace("-... ", "B").Replace("-.-. ", "C").Replace("-.. ", "D").Replace(". ", "E").Replace("..-. ", "F").Replace("--. ", "G").Replace(".... ", "H").Replace(".. ", "I").Replace(".--- ", "J").Replace("-.- ", "K").Replace(".-.. ", "L").Replace("-- ", "M").Replace("-. ", "N").Replace("--- ", "O").Replace(".--. ", "P").Replace("--.- ", "Q").Replace(".-. ", "R").Replace("... ", "S").Replace("- ", "T").Replace("..- ", "U").Replace("...- ", "V").Replace(".-- ", "W").Replace("-..- ", "X").Replace("-.-- ", "Y").Replace("--.. ", "Z").Replace("----- ", "0").Replace(".---- ", "1").Replace("..--- ", "2").Replace("...-- ", "3").Replace("....- ", "4").Replace("..... ", "5").Replace("-.... ", "6").Replace("--... ", "7").Replace("---.. ", "8").Replace("----. ", "9"); oi.Text = oi.Text + moutput; } if (dec == 0) { Dictionary<char, String> morse = new Dictionary<char, String>() { {'A' , ".- "}, {'B' , "-... "}, {'C' , "-.-. "}, {'D' , "-.. "}, {'E' , ". "}, {'F' , "..-. "}, {'G' , "--. "}, {'H' , ".... "}, {'I' , ".. "}, {'J' , ".--- "}, {'K' , "-.- "}, {'L' , ".-.. "}, {'M' , "-- "}, {'N' , "-. "}, {'O' , "--- "}, {'P' , ".--. "}, {'Q' , "--.- "}, {'R' , ".-. "}, {'S' , "... "}, {'T' , "- "}, {'U' , "..- "}, {'V' , "...- "}, {'W' , ".-- "}, {'X' , "-..- "}, {'Y' , "-.-- "}, {'Z' , "--.. "}, {'0' , "----- "}, {'1' , ".---- "}, {'2' , "..--- "}, {'3' , "...-- "}, {'4' , "....- "}, {'5' , "..... "}, {'6' , "-.... "}, {'7' , "--... "}, {'8' , "---.. "}, {'9' , "----. "}, {' ', "" }, }; String input1 = io; input1 = input1.ToUpper(); for (int i = 0; i < input1.Length; i++) { if (i > 0) oi.Text = oi.Text; char c = input1[i]; if (morse.ContainsKey(c)) oi.Text = oi.Text + (morse[c]); } } } private void HTML_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "HTML " + io); } if (dec == 1) { string htmlrep = io.Replace("&", "").Replace("#", "").Replace(";", ""); string[] htmltable = htmlrep.Split(' '); int[] htmldd = Array.ConvertAll(htmltable, int.Parse); char[] chars = htmldd.Select(x => (char)x).ToArray(); string str = new string(chars); oi.Text = oi.Text + str; } if (dec == 0) { string reg = ""; foreach (char c in io) { reg = reg + "&#"; reg = reg + (int)c; reg = reg + "; "; //reg = reg.Remove(reg.Length - 1, 1); //oi.Text = oi.Text + reg; } string regn = reg.Remove(reg.Length - 1, 1); oi.Text = oi.Text + regn; } } private void CTC_Click(object sender, EventArgs e) { if (spo == 1) { spot.Write("CRVVCTCHQ:Coping " + oi.Text + " To Clipboard"); } Clipboard.SetText(oi.Text); } private void Dec_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "Decimal " + io); } if (dec == 1) { string[] dectable = io.Split(' '); int[] decldd = Array.ConvertAll(dectable, int.Parse); char[] chars = decldd.Select(x => (char)x).ToArray(); string str = new string(chars); oi.Text = oi.Text + str; } if (dec == 0) { string reg = ""; foreach (char c in io) { reg = reg + (int)c; reg = reg + " "; } string regn = reg.Remove(reg.Length - 1, 1); oi.Text = oi.Text + regn; } } private void Hex_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "HEX " + io); } if (dec == 1) { string hex = io; string res = String.Empty; for (int a = 0; a < hex.Length; a = a + 2) { string Char2Convert = hex.Substring(a, 2); int n = Convert.ToInt32(Char2Convert, 16); char c = (char)n; res += c.ToString(); } oi.Text = oi.Text + res; } if (dec == 0) { string ascii = io; StringBuilder sb = new StringBuilder(); byte[] inputBytes = Encoding.UTF8.GetBytes(ascii); foreach (byte b in inputBytes) { sb.Append(string.Format("{0:x2}", b)); } oi.Text = oi.Text + sb.ToString(); } } private void Atbash_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "Atbash " + io); } AtbashTable x = new AtbashTable(); oi.Text = oi.Text + x.Transform(io); } private void Cesar_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "Cesar " + io + "Destiny = " + CSN.Value); } if (dec == 1) { int sl = CSN.Value * -1; string csb = Caesar(io, sl); oi.Text = oi.Text + csb; } if (dec == 0) { int sl = CSN.Value; string csb = Caesar(io, sl); oi.Text = oi.Text + csb; } } static string Caesar(string value, int shift) { char[] buffer = value.ToCharArray(); for (int i = 0; i < buffer.Length; i++) { char letter = buffer[i]; letter = (char)(letter + shift); if (letter > 'z') { letter = (char)(letter - 26); } else if (letter < 'a') { letter = (char)(letter + 26); } buffer[i] = letter; } return new string(buffer); } private void CSN_Scroll(object sender, EventArgs e) { } private void MP_TextChanged(object sender, EventArgs e) { int value; if (int.TryParse(this.io.Text, out value)) { this.CSN.Value = Convert.ToInt32(MP.Text); } } private void Vir_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "Virgenie " + io + "KEY = " + VSC.Text); } if (dec == 1) { string key = this.VSC.Text; oi.Text = oi.Text + VigenereDecrypt(io, key, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } if (dec == 0) { string key = this.VSC.Text; oi.Text = oi.Text + VigenereEncrypt(io, key, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } } static string VigenereEncrypt(string s, string key, string alphabet) { s = s.ToUpper(); key = key.ToUpper(); int j = 0; StringBuilder ret = new StringBuilder(s.Length); for (int i = 0; i < s.Length; i++) { if (alphabet.Contains(s[i])) ret.Append(alphabet[(alphabet.IndexOf(s[i]) + alphabet.IndexOf(key[j])) % alphabet.Length]); else ret.Append(s[i]); j = (j + 1) % key.Length; } return ret.ToString(); } static string VigenereDecrypt(string s, string key, string alphabet) { s = s.ToUpper(); key = key.ToUpper(); int j = 0; StringBuilder ret = new StringBuilder(s.Length); for (int i = 0; i < s.Length; i++) { if (alphabet.Contains(s[i])) ret.Append(alphabet[(alphabet.IndexOf(s[i]) - alphabet.IndexOf(key[j]) + alphabet.Length) % alphabet.Length]); else ret.Append(s[i]); j = (j + 1) % key.Length; } return ret.ToString(); } private void ROT_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "Rot" + ROTVSV.Text + " " + io); } string ioch = ROTVSV.Text; if (ioch == "47") { Form p = new Form(); oi.Text = oi.Text + Rot47(io); } if (ioch == "5") { Form p = new Form(); oi.Text = oi.Text + rot5(io); } if (ioch == "18") { Form p = new Form(); oi.Text = oi.Text + rot18(io); } if (ioch == "13") { Form p = new Form(); oi.Text = oi.Text + rot13(io); } } private char Rot47(char chr) { if (chr == ' ') return ' '; int ascii = chr; ascii += 47; if (ascii > 126) ascii -= 94; if (ascii < 33) ascii += 94; return (char)ascii; } public string Rot47(string str) { string RetStr = ""; foreach (char c in str.ToCharArray()) RetStr += Rot47(c).ToString(); return RetStr; } public string rot5(string s) { string k = ""; foreach (char c in s) { if ((int)c >= 48 && (int)c <= 57) { k += (char)((((c - 48) + 5) % 10) + 48); continue; } k += c; } return k; } public string rot13(string s) { string k = ""; foreach (char c in s) { if ((int)c >= 65 && (int)c <= 90) { k += (char)((((c - 65) + 13) % 26) + 65); continue; } if ((int)c >= 97 && (int)c <= 122) { k += (char)((((c - 97) + 13) % 26) + 97); continue; } k += c; } return k; } public string rot18(string s) { return rot5(rot13(s)); } private void NATO_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "NATO " + io); } Dictionary<char, String> morse1 = new Dictionary<char, string>() { {'A' , "Alpha "}, {'B' , "Bravo "}, {'C' , "Charlie "}, {'D' , "Delta "}, {'E' , "Echo "}, {'F' , "Foxfort"}, {'G' , "Golf "}, {'H' , "Hotel "}, {'I' , "India "}, {'J' , "Juliett "}, {'K' , "Kilo "}, {'L' , "Lima "}, {'M' , "Mike "}, {'N' , "November "}, {'O' , "Oscar "}, {'P' , "Papa "}, {'Q' , "Quebec "}, {'R' , "Romeo "}, {'S' , "Sierra "}, {'T' , "Tango "}, {'U' , "Uniform "}, {'V' , "Victor "}, {'W' , "Whiskey "}, {'X' , "X-ray "}, {'Y' , "Yankee "}, {'Z' , "Zulu "}, {'0' , "Zero"}, {'1' , "One"}, {'2' , "Two "}, {'3' , "Three "}, {'4' , "Four "}, {'5' , "Five "}, {'6' , "Six "}, {'7' , "Seven "}, {'8' , "Eight "}, {'9' , "Nine "}, {' ', "" }, }; String input = io; input = input.ToUpper(); for (int i = 0; i < input.Length; i++) { if (i > 0) oi.Text = oi.Text + ' '; char c = input[i]; if (morse1.ContainsKey(c)) oi.Text = oi.Text + morse1[c]; } } private void Base_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "Base64 " + io); } if (dec == 1) { oi.Text = oi.Text + Base64Decode(io); } if (dec == 0) { oi.Text = oi.Text + Base64Encode(io); } } public static string Base64Encode(string plainText) { var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); return System.Convert.ToBase64String(plainTextBytes); } public static string Base64Decode(string base64EncodedData) { var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); } public static int IntLength(int i) { if (i < 0) throw new ArgumentOutOfRangeException(); if (i == 0) return 1; return (int)Math.Floor(Math.Log10(i)) + 1; } private void IUPAC_Click(object sender, EventArgs e) { int value; if (int.TryParse(this.io.Text, out value)) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "IUPAC " + io); } int inint = Convert.ToInt32(io); int digit0 = (inint / 1) % 10; int digit1 = (inint / 10) % 10; int digit2 = (inint / 100) % 10; int digit3 = (inint / 1000) % 10; string r = ""; int loio = IntLength(inint); if (loio == 1) { if (inint == 1) { r = "mono"; } else if (inint == 2) { r = "di"; } else if (inint == 3) { r = "tri"; } else if (inint == 4) { r = "terta"; } else if (inint == 5) { r = "penta"; } else if (inint == 6) { r = "hexa"; } else if (inint == 7) { r = "hepta"; } else if (inint == 8) { r = "octa"; } else if (inint == 9) { r = "nona"; } } if (loio >= 2) { if (digit0 == 1) { r = "hen"; } else if (digit0 == 2) { r = "do"; } else if (digit0 == 3) { r = "tri"; } else if (digit0 == 4) { r = "terta"; } else if (digit0 == 5) { r = "penta"; } else if (digit0 == 6) { r = "hexa"; } else if (digit0 == 7) { r = "hepta"; } else if (digit0 == 8) { r = "octa"; } else if (digit0 == 9) { r = "nona"; } if (digit1 == 1 & digit0 == 0) { r = "deca"; } else if (digit1 == 1) { r = r + "deca"; } else if (digit1 == 2 & digit0 == 0) { r = "icosa"; } else if (digit1 == 2) { r = r + "cosa"; } else if (digit1 == 3 & digit0 == 0) { r = "triaconta"; } else if (digit1 == 3) { r = r + "triaconta"; } else if (digit1 == 4 & digit0 == 0) { r = "tetraconta"; } else if (digit1 == 4) { r = r + "tetraconta"; } else if (digit1 == 5 & digit0 == 0) { r = "pentaconta"; } else if (digit1 == 5) { r = r + "pentaconta"; } else if (digit1 == 6 & digit0 == 0) { r = "hexaconta"; } else if (digit1 == 6) { r = r + "hexaconta"; } else if (digit1 == 7 & digit0 == 0) { r = "heptaconta"; } else if (digit1 == 7) { r = r + "heptaconta"; } else if (digit1 == 8 & digit0 == 0) { r = "octaconta"; } else if (digit1 == 8) { r = r + "octaconta"; } else if (digit1 == 9 & digit0 == 0) { r = "nonaconta"; } else if (digit1 == 9) { r = r + "nonaconta"; } if (loio >= 3) { if (digit2 == 1 & digit1 == 0 & digit0 == 0) { r = "hecta"; } if (digit2 == 1) { r = r + "hecta"; } if (digit2 == 2 & digit1 == 0 & digit0 == 0) { r = "dicta"; } if (digit2 == 2) { r = r + "dicta"; } if (digit2 == 3 & digit1 == 0 & digit0 == 0) { r = "tricta"; } if (digit2 == 3) { r = r + "tricta"; } if (digit2 == 4 & digit1 == 0 & digit0 == 0) { r = "tetracta"; } if (digit2 == 4) { r = r + "tetracta"; } if (digit2 == 5 & digit1 == 0 & digit0 == 0) { r = "pentacta"; } if (digit2 == 5) { r = r + "pentacta"; } if (digit2 == 6 & digit1 == 0 & digit0 == 0) { r = "hexacta"; } if (digit2 == 6) { r = r + "hexacta"; } if (digit2 == 7 & digit1 == 0 & digit0 == 0) { r = "heptacta"; } if (digit2 == 7) { r = r + "heptacta"; } if (digit2 == 8 & digit1 == 0 & digit0 == 0) { r = "octacta"; } if (digit2 == 8) { r = r + "octacta"; } if (digit2 == 9 & digit1 == 0 & digit0 == 0) { r = "nonacta"; } if (digit2 == 9) { r = r + "nonacta"; } if (loio == 4) { if (digit3 == 1 & digit2 == 0 & digit1 == 0 & digit0 == 0) { r = "kilia"; } if (digit3 == 1) { r = r + "kilia"; } if (digit3 == 2 & digit2 == 0 & digit1 == 0 & digit0 == 0) { r = "dilia"; } if (digit3 == 2) { r = r + "dilia"; } if (digit3 == 3 & digit2 == 0 & digit1 == 0 & digit0 == 0) { r = "trilia"; } if (digit3 == 3) { r = r + "trilia"; } if (digit3 == 4 & digit2 == 0 & digit1 == 0 & digit0 == 0) { r = "tetralia"; } if (digit3 == 4) { r = r + "tetralia"; } if (digit3 == 5 & digit2 == 0 & digit1 == 0 & digit0 == 0) { r = "pentalia"; } if (digit3 == 5) { r = r + "pentalia"; } if (digit3 == 6 & digit2 == 0 & digit1 == 0 & digit0 == 0) { r = "hexalia"; } if (digit3 == 6) { r = r + "hexalia"; } if (digit3 == 7 & digit2 == 0 & digit1 == 0 & digit0 == 0) { r = "heptalia"; } if (digit3 == 7) { r = r + "heptalia"; } if (digit3 == 8 & digit2 == 0 & digit1 == 0 & digit0 == 0) { r = "octalia"; } if (digit3 == 8) { r = r + "octalia"; } if (digit3 == 9 & digit2 == 0 & digit1 == 0 & digit0 == 0) { r = "nonalia"; } if (digit3 == 9) { r = r + "nonalia"; } } } } oi.Text = r + oi.Text; } } private void dore_CheckedChanged(object sender, EventArgs e) { if (dore.Checked) { dec = 1; } else { dec = 0; } } private void PB_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { if (spo == 1) { spot.Write("GoodBye"); } Close(); } private void STB_Click(object sender, EventArgs e) { if (spo == 1) { spot.Write("CRVVIN:BEGINING INITIALIZE OF FILES"); } PBT.Start(); } private void PBT_Tick(object sender, EventArgs e) { PB.Increment(1); if (PB.Value == 100) { PBT.Stop(); PB.Value = 0; using (FileStream fs = File.Create(file)) { Byte[] info = new UTF8Encoding(true).GetBytes("https://www.dropbox.com/s/2al8yvnn4thy7ib/TL%20WIN32-64.rar?dl=0"); fs.Write(info, 0, info.Length); } MessageBox.Show(this, "Initialistation Complete!", "[CRVVMBHQ]", MessageBoxButtons.OK, MessageBoxIcon.Information); CRVVD(); } } private void q_Click(object sender, EventArgs e) { } private void button2_Click_1(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "Octal " + io); } if (dec == 1) { oi.Text = OctalToASCII(io); } if (dec == 0) { string reg = ""; foreach (char c in io) { reg = reg + Convert.ToString(c, 8); reg = reg + " "; } string regn = reg.Remove(reg.Length - 1, 1); oi.Text = oi.Text + regn.Replace(" ", ""); } } public static string OctalToASCII(string oct) { string ascii = string.Empty; for (int i = 0; i < oct.Length; i += 3) { ascii += (char)OctalToDecimal(oct.Substring(i, 3)); } return ascii; } private static int OctalToDecimal(string octal) { int octLength = octal.Length; double dec = 0; for (int i = 0; i < octLength; ++i) { dec += ((byte)octal[i] - 48) * Math.Pow(8, ((octLength - i) - 1)); } return (int)dec; } private void button3_Click(object sender, EventArgs e) { } private void a1z26_Click(object sender, EventArgs e) { oi.Text = ""; string io = this.io.Text; if (spo == 1) { spot.Write(Convert.ToString(dec) + "A1Z26 " + io); } if (dec == 1) { io = io + " "; string moutput = io.Replace("26 ", "Z").Replace("25 ", "Y").Replace("24 ", "X").Replace("23 ", "W").Replace("22 ", "V").Replace("21 ", "U").Replace("20 ", "T").Replace("19 ", "S").Replace("18 ", "R").Replace("17 ", "Q").Replace("16 ", "P").Replace("15 ", "O").Replace("14 ", "N").Replace("13 ", "M").Replace("12 ", "L").Replace("11 ", "K").Replace("10 ", "J").Replace("9 ", "I").Replace("8 ", "H").Replace("7 ", "G").Replace("6 ", "F").Replace("5 ", "E").Replace("4 ", "D").Replace("3 ", "C").Replace("2 ", "B").Replace("1 ", "A"); oi.Text = oi.Text + moutput; } if (dec == 0) { Dictionary<char, String> morse = new Dictionary<char, String>() { {'A' , "1 "}, {'B' , "2 "}, {'C' , "3 "}, {'D' , "4 "}, {'E' , "5 "}, {'F' , "6 "}, {'G' , "7 "}, {'H' , "8 "}, {'I' , "9 "}, {'J' , "10 "}, {'K' , "11 "}, {'L' , "12 "}, {'M' , "13 "}, {'N' , "14 "}, {'O' , "15 "}, {'P' , "16 "}, {'Q' , "17 "}, {'R' , "18 "}, {'S' , "19 "}, {'T' , "20 "}, {'U' , "21 "}, {'V' , "22 "}, {'W' , "23 "}, {'X' , "24 "}, {'Y' , "25 "}, {'Z' , "26 "}, {'1', "1 " }, {'2', "2 " }, {'3', "3 " }, {'4', "4 " }, {'5', "5 " }, {'6', "6 " }, {'7', "7 " }, {'8', "8 " }, {'9', "9 " }, {'0', "0 " }, {' ', "" }, }; String input1 = io; input1 = input1.ToUpper(); for (int i = 0; i < input1.Length; i++) { if (i > 0) oi.Text = oi.Text; char c = input1[i]; if (morse.ContainsKey(c)) oi.Text = oi.Text + (morse[c]); } } } class AtbashTable { char[] _shift = new char[char.MaxValue]; public AtbashTable() { for (int i = 0; i < char.MaxValue; i++) { _shift[i] = (char)i; } for (char c = 'A'; c <= 'Z'; c++) { _shift[(int)c] = (char)('Z' + 'A' - c); } for (char c = 'a'; c <= 'z'; c++) { _shift[(int)c] = (char)('z' + 'a' - c); } } public string Transform(string value) { try { char[] a = value.ToCharArray(); for (int i = 0; i < a.Length; i++) { int t = (int)a[i]; a[i] = _shift[t]; } return new string(a); } catch { return value; } } } } }
using System; using System.Collections.Generic; using static lox.TokenType; namespace lox { class Parser { readonly List<Token> tokens = new List<Token>(); int current = 0; int loopDepth = 0; #region Helper Members Token Peek => tokens[current]; Token Previous => tokens[current - 1]; bool IsAtEnd => Peek.Type == EOF; bool IsInLoop => loopDepth > 0; Token Advance() { if (!IsAtEnd) current++; return Previous; } void Regurgitate() { if (current > 0) current--; } bool Check(TokenType type) { if (IsAtEnd) return false; return Peek.Type == type; } bool Match(params TokenType[] types) { foreach (var type in types) { if (Check(type)) { Advance(); return true; } } return false; } ParseErrorException Error(Token token, string message) { Program.Error(token, message); return new ParseErrorException(); } void EnterLoop() { loopDepth++; } void ExitLoop() { loopDepth = Math.Max(0, loopDepth - 1); } void Synchronize() { Advance(); while (!IsAtEnd) { if (Previous.Type == Semicolon) return; switch (Peek.Type) { case Class: case Fun: case Var: case For: case If: case While: case Print: case Return: return; } Advance(); } } Token Consume(TokenType type, string message) { if (Check(type)) return Advance(); throw Error(Peek, message); } Expr ConsumeBinaryOperatorNoLeft(Func<Expr> nextRule, params TokenType[] matchedTypes) { if (Match(matchedTypes)) { // Hack for unary minus if (Previous.Type == Minus) { Regurgitate(); return Unary(); } var op = Previous; var right = nextRule(); throw Error(op, "Binary operator appeared at start of expression (without left operand.)"); } else return nextRule(); } Expr ConsumeBinaryOperator(Func<Expr> nextRule, Func<Expr, Token, Expr, Expr> ctor, params TokenType[] matchedTypes) { var expr = ConsumeBinaryOperatorNoLeft(nextRule, matchedTypes); while (Match(matchedTypes)) { var op = Previous; var right = nextRule(); expr = ctor(expr, op, right); } return expr; } Expr ConsumeLogical(Func<Expr> nextRule, params TokenType[] matchedTypes) { return ConsumeBinaryOperator(nextRule, (l, o, r) => new Expr.Logical(l, o, r), matchedTypes); } Expr ConsumeBinary(Func<Expr> nextRule, params TokenType[] matchedTypes) { return ConsumeBinaryOperator(nextRule, (l, o, r) => new Expr.Binary(l, o, r), matchedTypes); } #endregion #region Grammar Rules Expr Primary() { if (Match(False)) return new Expr.Literal(false); if (Match(True)) return new Expr.Literal(true); if (Match(Nil)) return new Expr.Literal(null); if (Match(Number, TokenType.String)) return new Expr.Literal(Previous.Literal); if (Match(Identifier)) return new Expr.Variable(Previous); if (Match(LeftParen)) { var expr = Expression(); Consume(RightParen, "Expected ')' after expression."); return new Expr.Grouping(expr); } throw Error(Peek, "Expected expression."); } Expr FinishCall(Expr callee) { var arguments = new List<Expr>(); if (!Check(RightParen)) { do { if (arguments.Count >= 8) Error(Peek, "Cannot have more than 8 arguments."); arguments.Add(Expression()); } while (Match(TokenType.Comma)); } var paren = Consume(RightParen, "Expect ')' after arguments."); return new Expr.Call(callee, paren, arguments); } Expr Call() { var expr = Primary(); while (true) { if (Match(LeftParen)) expr = FinishCall(expr); else break; } return expr; } Expr Unary() { if (Match(Bang, Minus)) { var op = Previous; var right = Unary(); return new Expr.Unary(op, right); } return Call(); } Expr Factor() => ConsumeBinary(Unary, Slash, Star); Expr Term() => ConsumeBinary(Factor, Minus, Plus); Expr Comparison() => ConsumeBinary(Term, Greater, GreaterEqual, Less, LessEqual); Expr Equality() => ConsumeBinary(Comparison, BangEqual, EqualEqual); Expr Ternary() { var cond = Equality(); if (Match(TokenType.QuestionMark)) { var left = Equality(); Consume(Colon, "Expected ':' in ternary operator expression."); var right = Equality(); return new Expr.Ternary(cond, left, right); } return cond; } Expr Comma() => ConsumeBinary(Ternary, TokenType.Comma); Expr And() => ConsumeLogical(Comma, TokenType.And); Expr Or() => ConsumeLogical(And, TokenType.Or); Expr Assignment() { var expr = Or(); if (Match(Equal)) { var equals = Previous; var value = Assignment(); if (expr is Expr.Variable variable) { var name = variable.Name; return new Expr.Assign(name, value); } Error(equals, "Invalid assignment target."); } return expr; } Expr Expression() => Assignment(); Stmt ForStatement() { Consume(LeftParen, "Expect '(' after 'for'."); Stmt initializer; if (Match(Semicolon)) initializer = null; else if (Match(Var)) initializer = VarDeclaration(); else initializer = ExpressionStatement(); Expr condition = null; if (!Check(Semicolon)) condition = Expression(); Consume(Semicolon, "Expect ';' after loop condition."); Expr increment = null; if (!Check(RightParen)) increment = Expression(); Consume(RightParen, "Expect ')' after for clause."); EnterLoop(); var body = Statement(); ExitLoop(); if (increment != null) { body = new Stmt.Block(new List<Stmt> { body, new Stmt.Expression(increment), }); } if (condition == null) condition = new Expr.Literal(true); body = new Stmt.While(condition, body); if (initializer != null) body = new Stmt.Block(new List<Stmt> { initializer, body }); return body; } Stmt IfStatement() { Consume(LeftParen, "Expect '(' after 'if'."); var condition = Expression(); Consume(RightParen, "Expect ')' after if condition."); var thenBranch = Statement(); Stmt elseBranch = null; if (Match(Else)) elseBranch = Statement(); return new Stmt.If(condition, thenBranch, elseBranch); } Stmt PrintStatement() { var value = Expression(); Consume(Semicolon, "Expect ';' after value."); return new Stmt.Print(value); } Stmt ReturnStatement() { var keyword = Previous; Expr value = null; if (!Check(Semicolon)) value = Expression(); Consume(Semicolon, "Expect ';' after return value"); return new Stmt.Return(keyword, value); } Stmt WhileStatement() { Consume(LeftParen, "Expect '(' after 'while'."); var cond = Expression(); Consume(RightParen, "Expect ')' after condition."); EnterLoop(); var body = Statement(); ExitLoop(); return new Stmt.While(cond, body); } Stmt ExpressionStatement() { var value = Expression(); Consume(Semicolon, "Expect ';' after value."); return new Stmt.Expression(value); } Stmt.Function Function(string kind) { var name = Consume(Identifier, $"Expect {kind} name."); Consume(LeftParen, $"Expect '(' after {kind} name."); var parameters = new List<Token>(); if (!Check(RightParen)) { do { if (parameters.Count >= 8) Error(Peek, "Cannot have more than 8 parameters."); parameters.Add(Consume(Identifier, "Expect parameter name.")); } while (Match(TokenType.Comma)); } Consume(RightParen, "Expect ')' after parameters."); Consume(LeftBrace, $"Expect '{{' before {kind} body."); var body = Block(); return new Stmt.Function(name, parameters, body); } List<Stmt> Block() { var statements = new List<Stmt>(); while (!Check(RightBrace) && !IsAtEnd) statements.Add(Declaration()); Consume(RightBrace, "Expect '}' at end of block."); return statements; } Stmt Statement() { if (Match(Break)) { if (!IsInLoop) throw Error(Previous, "Encountered 'break' while not in a loop."); var keyword = Previous; Consume(Semicolon, "Expect ';' after a 'break'."); return new Stmt.Break(keyword); } if (Match(For)) return ForStatement(); if (Match(If)) return IfStatement(); if (Match(Print)) return PrintStatement(); if (Match(Return)) return ReturnStatement(); if (Match(While)) return WhileStatement(); if (Match(LeftBrace)) return new Stmt.Block(Block()); return ExpressionStatement(); } Stmt VarDeclaration() { var name = Consume(Identifier, "Expect variable name."); Expr initializer = null; if (Match(Equal)) initializer = Expression(); Consume(Semicolon, "Expect ';' after variable declaration."); return new Stmt.Var(name, initializer); } Stmt Declaration() { try { if (Match(Fun)) return Function("function"); if (Match(Var)) return VarDeclaration(); return Statement(); } catch (ParseErrorException) { Synchronize(); return null; } } #endregion public IEnumerable<Stmt> Parse() { var statements = new List<Stmt>(); while (!IsAtEnd) statements.Add(Declaration()); return statements; } public Parser(IEnumerable<Token> tokens) { this.tokens.AddRange(tokens); } } }
//--------------------------------------------------------------------- // <copyright file="EntityParameterCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.Common; using System.Data.Metadata.Edm; namespace System.Data.EntityClient { /// <summary> /// Class representing a parameter collection used in EntityCommand /// </summary> public sealed partial class EntityParameterCollection : DbParameterCollection { private static Type ItemType = typeof(EntityParameter); private bool _isDirty; /// <summary> /// Constructs the EntityParameterCollection object /// </summary> internal EntityParameterCollection() : base() { } /// <summary> /// Gets the parameter from the collection at the specified index /// </summary> /// <param name="index">The index of the parameter to retrieved</param> /// <returns>The parameter at the index</returns> public new EntityParameter this[int index] { get { return (EntityParameter)this.GetParameter(index); } set { this.SetParameter(index, value); } } /// <summary> /// Gets the parameter with the given name from the collection /// </summary> /// <param name="parameterName">The name of the parameter to retrieved</param> /// <returns>The parameter with the given name</returns> public new EntityParameter this[string parameterName] { get { return (EntityParameter)this.GetParameter(parameterName); } set { this.SetParameter(parameterName, value); } } /// <summary> /// Gets whether this collection has been changes since the last reset /// </summary> internal bool IsDirty { get { if (_isDirty) { return true; } // Loop through and return true if any parameter is dirty foreach (EntityParameter parameter in this) { if (parameter.IsDirty) { return true; } } return false; } } /// <summary> /// Add a EntityParameter to the collection /// </summary> /// <param name="value">The parameter to add to the collection</param> /// <returns>The index of the new parameter within the collection</returns> public EntityParameter Add(EntityParameter value) { this.Add((object)value); return value; } /// <summary> /// Add a EntityParameter with the given name and value to the collection /// </summary> /// <param name="parameterName">The name of the parameter to add</param> /// <param name="value">The value of the parameter to add</param> /// <returns>The index of the new parameter within the collection</returns> public EntityParameter AddWithValue(string parameterName, object value) { EntityParameter param = new EntityParameter(); param.ParameterName = parameterName; param.Value = value; return this.Add(param); } /// <summary> /// Adds a EntityParameter with the given name and type to the collection /// </summary> /// <param name="parameterName">The name of the parameter to add</param> /// <param name="dbType">The type of the parameter</param> /// <returns>The index of the new parameter within the collection</returns> public EntityParameter Add(string parameterName, DbType dbType) { return this.Add(new EntityParameter(parameterName, dbType)); } /// <summary> /// Add a EntityParameter with the given name, type, and size to the collection /// </summary> /// <param name="parameterName">The name of the parameter to add</param> /// <param name="dbType">The type of the parameter</param> /// <param name="size">The size of the parameter</param> /// <returns>The index of the new parameter within the collection</returns> public EntityParameter Add(string parameterName, DbType dbType, int size) { return this.Add(new EntityParameter(parameterName, dbType, size)); } /// <summary> /// Adds a range of EntityParameter objects to this collection /// </summary> /// <param name="values">The arary of EntityParameter objects to add</param> public void AddRange(EntityParameter[] values) { this.AddRange((Array)values); } /// <summary> /// Check if the collection has a parameter with the given parameter name /// </summary> /// <param name="parameterName">The parameter name to look for</param> /// <returns>True if the collection has a parameter with the given name</returns> public override bool Contains(string parameterName) { return this.IndexOf(parameterName) != -1; } /// <summary> /// Copies the given array of parameters into this collection /// </summary> /// <param name="array">The array to copy into</param> /// <param name="index">The index in the array where the copy starts</param> public void CopyTo(EntityParameter[] array, int index) { this.CopyTo((Array)array, index); } /// <summary> /// Finds the index in the collection of the given parameter object /// </summary> /// <param name="value">The parameter to search for</param> /// <returns>The index of the parameter, -1 if not found</returns> public int IndexOf(EntityParameter value) { return IndexOf((object)value); } /// <summary> /// Add a EntityParameter with the given value to the collection at a location indicated by the index /// </summary> /// <param name="index">The index at which the parameter is to be inserted</param> /// <param name="value">The value of the parameter</param> public void Insert(int index, EntityParameter value) { this.Insert(index, (object)value); } /// <summary> /// Marks that this collection has been changed /// </summary> private void OnChange() { _isDirty = true; } /// <summary> /// Remove a EntityParameter with the given value from the collection /// </summary> /// <param name="value">The parameter to remove</param> public void Remove(EntityParameter value) { this.Remove((object)value); } /// <summary> /// Reset the dirty flag on the collection /// </summary> internal void ResetIsDirty() { _isDirty = false; // Loop through and reset each parameter foreach (EntityParameter parameter in this) { parameter.ResetIsDirty(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; namespace System { /// <summary> /// Helper so we can call some tuple methods recursively without knowing the underlying types. /// </summary> internal interface ITupleInternal : ITuple { string ToString(StringBuilder sb); int GetHashCode(IEqualityComparer comparer); } // This interface should also be implemented by System.Tuple and System.Collections.Generic.KeyValuePair // Allows value tuples to be used in pattern matching and decomposition public interface ITuple { int Size { get; } object this[int i] { get; } } public static class ValueTuple { public static ValueTuple<T1> Create<T1>(T1 item1) => new ValueTuple<T1>(item1); public static ValueTuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) => new ValueTuple<T1, T2>(item1, item2); public static ValueTuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) => new ValueTuple<T1, T2, T3>(item1, item2, item3); public static ValueTuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) => new ValueTuple<T1, T2, T3, T4>(item1, item2, item3, item4); public static ValueTuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) => new ValueTuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5); public static ValueTuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) => new ValueTuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6); public static ValueTuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) => new ValueTuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7); public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) => new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, new ValueTuple<T8>(item8)); // From System.Web.Util.HashCodeCombiner internal static int CombineHashCodes(int h1, int h2) { return (((h1 << 5) + h1) ^ h2); } internal static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4) { return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); } } [Serializable] public struct ValueTuple<T1> : IEquatable<ValueTuple<T1>>, IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); } public Boolean Equals(ValueTuple<T1> other) { return Equals(Item1, other.Item1); } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1>)) return false; var objTuple = (ValueTuple<T1>)other; return comparer.Equals(Item1, objTuple.Item1); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; if(!(other is ValueTuple<T1>)) { throw new ArgumentException(); } var objTuple = (ValueTuple<T1>)other; return comparer.Compare(Item1, objTuple.Item1); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(Item1); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(Item1); sb.Append(")"); return sb.ToString(); } int ITuple.Size { get { return 1; } } object ITuple.this[int i] { get { switch (i) { case 1: return Item1; default: throw new IndexOutOfRangeException(); } } } } [Serializable] public struct ValueTuple<T1, T2> : IEquatable<ValueTuple<T1, T2>>, IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } public Boolean Equals(ValueTuple<T1, T2> other) { return Equals(Item1, other.Item1) && Equals(Item2, other.Item2); } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2>)) return false; var objTuple = (ValueTuple<T1, T2>)other; return comparer.Equals(Item1, objTuple.Item1) && comparer.Equals(Item2, objTuple.Item2); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; if (!(other is ValueTuple<T1, T2>)) { throw new ArgumentException(); } var objTuple = (ValueTuple<T1, T2>)other; int c = 0; c = comparer.Compare(Item1, objTuple.Item1); if (c != 0) return c; return comparer.Compare(Item2, objTuple.Item2); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(Item1); sb.Append(", "); sb.Append(Item2); sb.Append(")"); return sb.ToString(); } int ITuple.Size { get { return 2; } } object ITuple.this[int i] { get { switch (i) { case 1: return Item1; case 2: return Item2; default: throw new IndexOutOfRangeException(); } } } } [Serializable] public struct ValueTuple<T1, T2, T3> : IEquatable<ValueTuple<T1, T2, T3>>, IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { public T1 Item1; public T2 Item2; public T3 Item3; public ValueTuple(T1 item1, T2 item2, T3 item3) { Item1 = item1; Item2 = item2; Item3 = item3; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } public Boolean Equals(ValueTuple<T1, T2, T3> other) { return Equals(Item1, other.Item1) && Equals(Item2, other.Item2) && Equals(Item3, other.Item3); } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2, T3>)) return false; var objTuple = (ValueTuple<T1, T2, T3>)other; return comparer.Equals(Item1, objTuple.Item1) && comparer.Equals(Item2, objTuple.Item2) && comparer.Equals(Item3, objTuple.Item3); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; if (!(other is ValueTuple<T1, T2, T3>)) { throw new ArgumentException(); } var objTuple = (ValueTuple<T1, T2, T3>)other; int c = 0; c = comparer.Compare(Item1, objTuple.Item1); if (c != 0) return c; c = comparer.Compare(Item2, objTuple.Item2); if (c != 0) return c; return comparer.Compare(Item3, objTuple.Item3); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(Item1); sb.Append(", "); sb.Append(Item2); sb.Append(", "); sb.Append(Item3); sb.Append(")"); return sb.ToString(); } int ITuple.Size { get { return 3; } } object ITuple.this[int i] { get { switch (i) { case 1: return Item1; case 2: return Item2; case 3: return Item3; default: throw new IndexOutOfRangeException(); } } } } [Serializable] public struct ValueTuple<T1, T2, T3, T4> : IEquatable<ValueTuple<T1, T2, T3, T4>>, IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } public Boolean Equals(ValueTuple<T1, T2, T3, T4> other) { return Equals(Item1, other.Item1) && Equals(Item2, other.Item2) && Equals(Item3, other.Item3) && Equals(Item4, other.Item4); } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (!(other is ValueTuple<T1, T2, T3, T4>)) { throw new ArgumentException(); } var objTuple = (ValueTuple<T1, T2, T3, T4>)other; return comparer.Equals(Item1, objTuple.Item1) && comparer.Equals(Item2, objTuple.Item2) && comparer.Equals(Item3, objTuple.Item3) && comparer.Equals(Item4, objTuple.Item4); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; if (!(other is ValueTuple<T1, T2, T3, T4>)) { throw new ArgumentException(); } var objTuple = (ValueTuple<T1, T2, T3, T4>)other; int c = 0; c = comparer.Compare(Item1, objTuple.Item1); if (c != 0) return c; c = comparer.Compare(Item2, objTuple.Item2); if (c != 0) return c; c = comparer.Compare(Item3, objTuple.Item3); if (c != 0) return c; return comparer.Compare(Item4, objTuple.Item4); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(Item1); sb.Append(", "); sb.Append(Item2); sb.Append(", "); sb.Append(Item3); sb.Append(", "); sb.Append(Item4); sb.Append(")"); return sb.ToString(); } int ITuple.Size { get { return 4; } } object ITuple.this[int i] { get { switch (i) { case 1: return Item1; case 2: return Item2; case 3: return Item3; case 4: return Item4; default: throw new IndexOutOfRangeException(); } } } } [Serializable] public struct ValueTuple<T1, T2, T3, T4, T5> : IEquatable<ValueTuple<T1, T2, T3, T4, T5>>, IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } public Boolean Equals(ValueTuple<T1, T2, T3, T4, T5> other) { return Equals(Item1, other.Item1) && Equals(Item2, other.Item2) && Equals(Item3, other.Item3) && Equals(Item4, other.Item4) && Equals(Item5, other.Item5); } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5>)) return false; var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other; return comparer.Equals(Item1, objTuple.Item1) && comparer.Equals(Item2, objTuple.Item2) && comparer.Equals(Item3, objTuple.Item3) && comparer.Equals(Item4, objTuple.Item4) && comparer.Equals(Item5, objTuple.Item5); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; if (!(other is ValueTuple<T1, T2, T3, T4, T5>)) { throw new ArgumentException(); } var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other; int c = 0; c = comparer.Compare(Item1, objTuple.Item1); if (c != 0) return c; c = comparer.Compare(Item2, objTuple.Item2); if (c != 0) return c; c = comparer.Compare(Item3, objTuple.Item3); if (c != 0) return c; c = comparer.Compare(Item4, objTuple.Item4); if (c != 0) return c; return comparer.Compare(Item5, objTuple.Item5); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(Item1); sb.Append(", "); sb.Append(Item2); sb.Append(", "); sb.Append(Item3); sb.Append(", "); sb.Append(Item4); sb.Append(", "); sb.Append(Item5); sb.Append(")"); return sb.ToString(); } int ITuple.Size { get { return 5; } } object ITuple.this[int i] { get { switch (i) { case 1: return Item1; case 2: return Item2; case 3: return Item3; case 4: return Item4; case 5: return Item5; default: throw new IndexOutOfRangeException(); } } } } [Serializable] public struct ValueTuple<T1, T2, T3, T4, T5, T6> : IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } public Boolean Equals(ValueTuple<T1, T2, T3, T4, T5, T6> other) { return Equals(Item1, other.Item1) && Equals(Item2, other.Item2) && Equals(Item3, other.Item3) && Equals(Item4, other.Item4) && Equals(Item5, other.Item5) && Equals(Item6, other.Item6); } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6>)) return false; var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other; return comparer.Equals(Item1, objTuple.Item1) && comparer.Equals(Item2, objTuple.Item2) && comparer.Equals(Item3, objTuple.Item3) && comparer.Equals(Item4, objTuple.Item4) && comparer.Equals(Item5, objTuple.Item5) && comparer.Equals(Item6, objTuple.Item6); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>)) { throw new ArgumentException(); } var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other; int c = 0; c = comparer.Compare(Item1, objTuple.Item1); if (c != 0) return c; c = comparer.Compare(Item2, objTuple.Item2); if (c != 0) return c; c = comparer.Compare(Item3, objTuple.Item3); if (c != 0) return c; c = comparer.Compare(Item4, objTuple.Item4); if (c != 0) return c; c = comparer.Compare(Item5, objTuple.Item5); if (c != 0) return c; return comparer.Compare(Item6, objTuple.Item6); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(Item1); sb.Append(", "); sb.Append(Item2); sb.Append(", "); sb.Append(Item3); sb.Append(", "); sb.Append(Item4); sb.Append(", "); sb.Append(Item5); sb.Append(", "); sb.Append(Item6); sb.Append(")"); return sb.ToString(); } int ITuple.Size { get { return 6; } } object ITuple.this[int i] { get { switch (i) { case 1: return Item1; case 2: return Item2; case 3: return Item3; case 4: return Item4; case 5: return Item5; case 6: return Item6; default: throw new IndexOutOfRangeException(); } } } } [Serializable] public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7> : IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } public Boolean Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other) { return Equals(Item1, other.Item1) && Equals(Item2, other.Item2) && Equals(Item3, other.Item3) && Equals(Item4, other.Item4) && Equals(Item5, other.Item5) && Equals(Item6, other.Item6) && Equals(Item7, other.Item7); } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>)) return false; var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other; return comparer.Equals(Item1, objTuple.Item1) && comparer.Equals(Item2, objTuple.Item2) && comparer.Equals(Item3, objTuple.Item3) && comparer.Equals(Item4, objTuple.Item4) && comparer.Equals(Item5, objTuple.Item5) && comparer.Equals(Item6, objTuple.Item6) && comparer.Equals(Item7, objTuple.Item7); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>)) { throw new ArgumentException(); } var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other; int c = 0; c = comparer.Compare(Item1, objTuple.Item1); if (c != 0) return c; c = comparer.Compare(Item2, objTuple.Item2); if (c != 0) return c; c = comparer.Compare(Item3, objTuple.Item3); if (c != 0) return c; c = comparer.Compare(Item4, objTuple.Item4); if (c != 0) return c; c = comparer.Compare(Item5, objTuple.Item5); if (c != 0) return c; c = comparer.Compare(Item6, objTuple.Item6); if (c != 0) return c; return comparer.Compare(Item7, objTuple.Item7); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(Item1); sb.Append(", "); sb.Append(Item2); sb.Append(", "); sb.Append(Item3); sb.Append(", "); sb.Append(Item4); sb.Append(", "); sb.Append(Item5); sb.Append(", "); sb.Append(Item6); sb.Append(", "); sb.Append(Item7); sb.Append(")"); return sb.ToString(); } int ITuple.Size { get { return 7; } } object ITuple.this[int i] { get { switch (i) { case 1: return Item1; case 2: return Item2; case 3: return Item3; case 4: return Item4; case 5: return Item5; case 6: return Item6; case 7: return Item7; default: throw new IndexOutOfRangeException(); } } } } [Serializable] public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple where TRest : ITuple { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { if (!(rest is ITupleInternal)) { throw new ArgumentException(); } Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; Rest = rest; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } public Boolean Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other) { return Equals(Item1, other.Item1) && Equals(Item2, other.Item2) && Equals(Item3, other.Item3) && Equals(Item4, other.Item4) && Equals(Item5, other.Item5) && Equals(Item6, other.Item6) && Equals(Item7, other.Item7) && Equals(Rest, other.Rest); } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)) return false; var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other; return comparer.Equals(Item1, objTuple.Item1) && comparer.Equals(Item2, objTuple.Item2) && comparer.Equals(Item3, objTuple.Item3) && comparer.Equals(Item4, objTuple.Item4) && comparer.Equals(Item5, objTuple.Item5) && comparer.Equals(Item6, objTuple.Item6) && comparer.Equals(Item7, objTuple.Item7) && comparer.Equals(Rest, objTuple.Rest); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)) { throw new ArgumentException(); } var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other; int c = 0; c = comparer.Compare(Item1, objTuple.Item1); if (c != 0) return c; c = comparer.Compare(Item2, objTuple.Item2); if (c != 0) return c; c = comparer.Compare(Item3, objTuple.Item3); if (c != 0) return c; c = comparer.Compare(Item4, objTuple.Item4); if (c != 0) return c; c = comparer.Compare(Item5, objTuple.Item5); if (c != 0) return c; c = comparer.Compare(Item6, objTuple.Item6); if (c != 0) return c; c = comparer.Compare(Item7, objTuple.Item7); if (c != 0) return c; return comparer.Compare(Rest, objTuple.Rest); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple ITupleInternal t = (ITupleInternal)Rest; if (t.Size >= 8) { return t.GetHashCode(comparer); } // In this case, the rest memeber has less than 8 elements so we need to combine some our elements with the elements in rest int k = 8 - t.Size; switch (k) { case 1: return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item7), t.GetHashCode(comparer)); case 2: return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), t.GetHashCode(comparer)); case 3: return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), t.GetHashCode(comparer)); case 4: return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), t.GetHashCode(comparer)); case 5: return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), t.GetHashCode(comparer)); case 6: return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), t.GetHashCode(comparer)); case 7: return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), t.GetHashCode(comparer)); } Contract.Assert(false, "Missed all cases for computing ValueTuple hash code"); return -1; } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(Item1); sb.Append(", "); sb.Append(Item2); sb.Append(", "); sb.Append(Item3); sb.Append(", "); sb.Append(Item4); sb.Append(", "); sb.Append(Item5); sb.Append(", "); sb.Append(Item6); sb.Append(", "); sb.Append(Item7); sb.Append(", "); return ((ITupleInternal)Rest).ToString(sb); } int ITuple.Size { get { return 7 + ((ITupleInternal)Rest).Size; } } object ITuple.this[int i] { get { switch (i) { case 1: return Item1; case 2: return Item2; case 3: return Item3; case 4: return Item4; case 5: return Item5; case 6: return Item6; case 7: return Item7; default: return Rest[i - 7]; } } } } }
#region Copyright /* * Product: IronyScript.NET * Author: Petro Protsyk * Date: 11.02.2008 * Time: 20:58 * Update: June 2008 * * * History: * * 17.03.2008: Evaluation implementation with Visitor pattern. * 02.04.2008: Large refactoring to use Evaluation function instead of Visitor * June 2008: Getting things done */ #endregion #region Using using System; using System.Globalization; using System.Collections.Generic; using Irony.Compiler; using ScriptNET.Ast; using ScriptNET.Runtime; #endregion namespace ScriptNET { /// <summary> /// This class represents Irony Grammar for Script.NET /// </summary> [Bindable(false)] public class ScriptdotnetGrammar : Grammar { public ScriptdotnetGrammar(bool expressionGrammar) { #region 1. Terminals NumberLiteral n = TerminalFactory.CreateCSharpNumber("number"); IdentifierTerminal v = CreateScriptNetIdentifier("Identifier"); Terminal s = CreateScriptNetString("string"); Terminal @is = Symbol("is"); Terminal dot = Symbol(".", "dot"); Terminal less = Symbol("<"); Terminal greater = Symbol(">"); Terminal arrow = Symbol("->"); Terminal LSb = Symbol("["); Terminal RSb = Symbol("]"); Terminal LCb = Symbol("("); Terminal RCb = Symbol(")"); Terminal RFb = Symbol("}"); Terminal LFb = Symbol("{"); Terminal LMb = Symbol("<!"); Terminal RMb = Symbol("!>"); Terminal LGb = Symbol("<|"); Terminal RGb = Symbol("|>"); Terminal comma = Symbol(","); Terminal semicolon = Symbol(";"); Terminal colon = Symbol(":"); #endregion #region 2. Non-terminals #region 2.1 Expressions NonTerminal Expr = new NonTerminal("Expr", typeof(ScriptExpr)); NonTerminal ConstExpr = new NonTerminal("ConstExpr", typeof(ScriptConstExpr)); NonTerminal BinExpr = new NonTerminal("BinExpr", typeof(ScriptBinExpr)); NonTerminal UnaryExpr = new NonTerminal("UnaryExpr", typeof(ScriptUnaryExpr)); NonTerminal AssignExpr = new NonTerminal("AssignExpr", typeof(ScriptAssignExpr)); NonTerminal TypeConvertExpr = new NonTerminal("TypeConvertExpr", typeof(ScriptTypeConvertExpr)); NonTerminal IsExpr = new NonTerminal("IsExpr", typeof(ScriptIsExpr)); NonTerminal MetaExpr = new NonTerminal("MetaExpr", typeof(ScriptMetaExpr)); NonTerminal FuncDefExpr = new NonTerminal("FuncDefExpr", typeof(ScriptFunctionDefinition)); //typeof(ScriptFunctionDefExpression)); NonTerminal TypeExpr = new NonTerminal("TypeExpr", typeof(ScriptTypeExpr)); NonTerminal TypeConstructor = new NonTerminal("TypeConstructor", typeof(ScriptTypeConstructor)); NonTerminal FunctionCall = new NonTerminal("FunctionCall", typeof(ScriptFunctionCall)); NonTerminal ArrayResolution = new NonTerminal("ArrayResolution", typeof(ScriptArrayResolution)); NonTerminal BinOp = new NonTerminal("BinOp"); NonTerminal LUnOp = new NonTerminal("LUnOp"); NonTerminal RUnOp = new NonTerminal("RUnOp"); NonTerminal ArrayConstructor = new NonTerminal("ArrayConstructor", typeof(ScriptArrayConstructor)); NonTerminal MObjectConstructor = new NonTerminal("MObjectConstructor", typeof(ScriptMObject)); NonTerminal MObjectPart = new NonTerminal("MObjectPart", typeof(ScriptMObjectPart)); NonTerminal MObjectParts = new NonTerminal("MObjectPart", typeof(ScriptAst)); NonTerminal TypeList = new NonTerminal("TypeList", typeof(ScriptTypeExprList)); #endregion #region 2.2 QualifiedName //Expression List: expr1, expr2, expr3, .. NonTerminal ExprList = new NonTerminal("ExprList", typeof(ScriptExprList)); //A name in form: a.b.c().d[1,2].e .... NonTerminal NewStmt = new NonTerminal("NewStmt", typeof(ScriptNewStmt)); NonTerminal NewArrStmt = new NonTerminal("NewArrStmt", typeof(ScriptNewArrStmt)); NonTerminal QualifiedName = new NonTerminal("QualifiedName", typeof(ScriptQualifiedName)); NonTerminal GenericsPostfix = new NonTerminal("GenericsPostfix", typeof(ScriptGenericsPostfix)); NonTerminal GlobalList = new NonTerminal("GlobalList", typeof(ScriptGlobalList)); #endregion #region 2.3 Statement NonTerminal Condition = new NonTerminal("Condition", typeof(ScriptCondition)); NonTerminal Statement = new NonTerminal("Statement", typeof(ScriptStatement)); NonTerminal IfStatement = new NonTerminal("IfStatement", typeof(ScriptIfStatement)); NonTerminal WhileStatement = new NonTerminal("WhileStatement", typeof(ScriptWhileStatement)); NonTerminal ForStatement = new NonTerminal("ForStatement", typeof(ScriptForStatement)); NonTerminal ForEachStatement = new NonTerminal("ForEachStatement", typeof(ScriptForEachStatement)); NonTerminal OptionalExpression = new NonTerminal("OptionalExpression", typeof(ScriptExpr)); NonTerminal SwitchStatement = new NonTerminal("SwitchStatement", typeof(ScriptStatement)); NonTerminal SwitchStatements = new NonTerminal("SwitchStatements", typeof(ScriptSwitchStatement)); NonTerminal SwitchCaseStatement = new NonTerminal("SwitchCaseStatement", typeof(ScriptSwitchCaseStatement)); NonTerminal SwitchDefaultStatement = new NonTerminal("SwitchDefaultStatement", typeof(ScriptSwitchDefaultStatement)); NonTerminal UsingStatement = new NonTerminal("UsingStatement", typeof(ScriptUsingStatement)); NonTerminal TryCatchFinallyStatement = new NonTerminal("TryCatchFinallyStatement", typeof(ScriptTryCatchFinallyStatement)); NonTerminal FlowControlStatement = new NonTerminal("FlowControl", typeof(ScriptFlowControlStatement)); NonTerminal ExprStatement = new NonTerminal("ExprStatement", typeof(ScriptStatement)); //Block NonTerminal BlockStatement = new NonTerminal("BlockStatement", typeof(ScriptStatement)); NonTerminal Statements = new NonTerminal("Statements(Compound)", typeof(ScriptCompoundStatement)); #endregion #region 2.4 Program and Functions NonTerminal Prog = new NonTerminal("Prog", typeof(ScriptProg)); NonTerminal Element = new NonTerminal("Element", typeof(ScriptAst)); NonTerminal Elements = new NonTerminal("Elements", typeof(ScriptElements)); NonTerminal FuncDef = new NonTerminal("FuncDef", typeof(ScriptFunctionDefinition)); NonTerminal FuncContract = new NonTerminal("FuncContract", typeof(ScriptFuncContract)); NonTerminal ParameterList = new NonTerminal("ParamaterList", typeof(ScriptFuncParameters)); NonTerminal FuncContractPre = new NonTerminal("Pre Conditions", typeof(ScriptFuncContractPre)); NonTerminal FuncContractPost = new NonTerminal("Post Conditions", typeof(ScriptFuncContractPost)); NonTerminal FuncContractInv = new NonTerminal("Invariant Conditions", typeof(ScriptFuncContractInv)); #endregion #endregion #region 3. BNF rules #region 3.1 Expressions ConstExpr.Rule = Symbol("true") | "false" | "null" | s | n; BinExpr.Rule = Expr + BinOp + Expr | IsExpr; UnaryExpr.Rule = LUnOp + Expr; IsExpr.Rule = Expr + @is + TypeExpr; TypeConvertExpr.Rule = LCb + Expr + RCb + Expr.Q(); AssignExpr.Rule = QualifiedName + "=" + Expr | QualifiedName + "++" | QualifiedName + "--" | QualifiedName + ":=" + Expr | QualifiedName + "+=" + Expr | QualifiedName + "-=" + Expr; //TODO: MetaFeatures; // <[ ] + > because of conflict a[1]>2 MetaExpr.Rule = LMb + Elements + RMb; GlobalList.Rule = "global" + LCb + ParameterList + RCb; FuncDefExpr.Rule = "function" + LCb + ParameterList + RCb + GlobalList.Q() + FuncContract.Q() + BlockStatement; Expr.Rule = ConstExpr | BinExpr | UnaryExpr | QualifiedName | AssignExpr | NewStmt | FuncDefExpr | NewArrStmt | ArrayConstructor | MObjectConstructor | TypeConvertExpr | MetaExpr ; NewStmt.Rule = "new" + TypeConstructor; NewArrStmt.Rule = "new" + TypeExpr + ArrayResolution; BinOp.Rule = Symbol("+") | "-" | "*" | "/" | "%" | "^" | "&" | "|" | "&&" | "||" | "==" | "!=" | greater | less | ">=" | "<="; LUnOp.Rule = Symbol("~") | "-" | "!"/* | "$"*/; ArrayConstructor.Rule = LSb + ExprList + RSb; MObjectPart.Rule = v + arrow + Expr; MObjectParts.Rule = MakePlusRule(MObjectParts, comma, MObjectPart); MObjectConstructor.Rule = LSb + MObjectParts + RSb; OptionalExpression.Rule = Expr.Q(); #endregion #region 3.2 QualifiedName TypeExpr.Rule = //MakePlusRule(TypeExpr, dot, v); v + GenericsPostfix.Q() | TypeExpr + dot + (v + GenericsPostfix.Q()); GenericsPostfix.Rule = LGb + TypeList + RGb; FunctionCall.Rule = LCb + ExprList.Q() + RCb; ArrayResolution.Rule = LSb + ExprList + RSb; QualifiedName.Rule = v + (GenericsPostfix | ArrayResolution | FunctionCall).Star() | QualifiedName + dot + v + (GenericsPostfix | ArrayResolution | FunctionCall).Star(); ExprList.Rule = MakePlusRule(ExprList, comma, Expr); TypeList.Rule = MakePlusRule(TypeList, comma, TypeExpr); TypeConstructor.Rule = TypeExpr + FunctionCall; #endregion #region 3.3 Statement Condition.Rule = LCb + Expr + RCb; IfStatement.Rule = "if" + Condition + Statement + ("else" + Statement).Q(); WhileStatement.Rule = "while" + Condition + Statement; ForStatement.Rule = "for" + LCb + OptionalExpression + semicolon + OptionalExpression + semicolon + OptionalExpression + RCb + Statement; ForEachStatement.Rule = "foreach" + LCb + v + "in" + Expr + RCb + Statement; UsingStatement.Rule = "using" + LCb + Expr + RCb + BlockStatement; TryCatchFinallyStatement.Rule = "try" + BlockStatement + "catch" + LCb + v + RCb + BlockStatement + "finally" + BlockStatement; SwitchStatement.Rule = "switch" + LCb + Expr + RCb + LFb + SwitchStatements + RFb; ExprStatement.Rule = Expr + semicolon; FlowControlStatement.Rule = "break" + semicolon | "continue" + semicolon | "return" + Expr + semicolon | "throw" + Expr + semicolon; Statement.Rule = semicolon | IfStatement //1. If | WhileStatement //2. While | ForStatement //3. For | ForEachStatement //4. ForEach | UsingStatement //5. Using | SwitchStatement //6. Switch | BlockStatement //7. Block | TryCatchFinallyStatement //8. TryCatch | ExprStatement //9. Expr | FlowControlStatement; //10. FlowControl Statements.SetOption(TermOptions.IsList); Statements.Rule = Statements + Statement | Empty; BlockStatement.Rule = LFb + Statements + RFb; SwitchStatements.Rule = SwitchCaseStatement.Star() + SwitchDefaultStatement.Q(); SwitchCaseStatement.Rule = Symbol("case") + Expr + colon + Statements; SwitchDefaultStatement.Rule = "default" + colon + Statements; #endregion #region 3.4 Prog FuncContract.Rule = LSb + FuncContractPre + semicolon + FuncContractPost + semicolon + FuncContractInv + semicolon + RSb; FuncContractPre.Rule = "pre" + LCb + ExprList.Q() + RCb; FuncContractPost.Rule = "post" + LCb + ExprList.Q() + RCb; FuncContractInv.Rule = "invariant" + LCb + ExprList.Q() + RCb; ParameterList.Rule = MakeStarRule(ParameterList, comma, v); FuncDef.Rule = "function" + v + LCb + ParameterList + RCb + GlobalList.Q() + FuncContract.Q() + BlockStatement; Element.Rule = Statement | FuncDef; Elements.SetOption(TermOptions.IsList); Elements.Rule = Elements + Element | Empty; Prog.Rule = Elements + Eof; Terminal Comment = new CommentTerminal("Comment", "/*", "*/"); NonGrammarTerminals.Add(Comment); Terminal LineComment = new CommentTerminal("LineComment", "//", "\n"); NonGrammarTerminals.Add(LineComment); #endregion #endregion #region 4. Set starting symbol if (!expressionGrammar) Root = Prog; // Set grammar root else Root = Expr; #endregion #region 5. Operators precedence RegisterOperators(1, "=", "+=", "-=", ":="); RegisterOperators(2, "|", "||"); RegisterOperators(3, "&", "&&"); RegisterOperators(4, "==", "!=", ">", "<", ">=", "<="); RegisterOperators(5, "is"); RegisterOperators(6, "+", "-"); RegisterOperators(7, "*", "/", "%"); RegisterOperators(8, Associativity.Right, "^"); RegisterOperators(9, "~", "!", /*"$",*/ "++", "--"); RegisterOperators(10, "."); //RegisterOperators(10, Associativity.Right, ".",",", ")", "(", "]", "[", "{", "}"); //RegisterOperators(11, Associativity.Right, "else"); #endregion #region 6. Punctuation symbols RegisterPunctuation( "(", ")", "[", "]", "{", "}", ",", ";" ); #endregion } #region Compiler public static readonly LanguageCompiler Compiler = new LanguageCompiler(new ScriptdotnetGrammar(false)); public static readonly LanguageCompiler ExpressionCompiler = new LanguageCompiler(new ScriptdotnetGrammar(true)); #endregion #region Helpers /// <summary> /// Creates identifier terminal for script grammar /// </summary> /// <param name="name"></param> /// <returns></returns> private static IdentifierTerminal CreateScriptNetIdentifier(string name) { IdentifierTerminal id = new IdentifierTerminal(name); id.SetOption(TermOptions.CanStartWithEscape); id.AddKeywords("true", "false", "null", "if", "else", "while", "for", "foreach", "in", "switch", "case", "default", "break", "continue", "return", "function", "is", "pre", "post", "invariant", "new", "using", "global"); id.AddPrefixFlag("@", ScanFlags.IsNotKeyword | ScanFlags.DisableEscapes); //From spec: //Start char is "_" or letter-character, which is a Unicode character of classes Lu, Ll, Lt, Lm, Lo, or Nl id.StartCharCategories.AddRange(new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, //Ul UnicodeCategory.LowercaseLetter, //Ll UnicodeCategory.TitlecaseLetter, //Lt UnicodeCategory.ModifierLetter, //Lm UnicodeCategory.OtherLetter, //Lo UnicodeCategory.LetterNumber //Nl }); //Internal chars /* From spec: identifier-part-character: letter-character | decimal-digit-character | connecting-character | combining-character | formatting-character */ id.CharCategories.AddRange(id.StartCharCategories); //letter-character categories id.CharCategories.AddRange(new UnicodeCategory[] { UnicodeCategory.DecimalDigitNumber, //Nd UnicodeCategory.ConnectorPunctuation, //Pc UnicodeCategory.SpacingCombiningMark, //Mc UnicodeCategory.NonSpacingMark, //Mn UnicodeCategory.Format //Cf }); //Chars to remove from final identifier id.CharsToRemoveCategories.Add(UnicodeCategory.Format); return id; } private static StringLiteral CreateScriptNetString(string name) { StringLiteral term = new StringLiteral(name, TermOptions.None); term.AddStartEnd("'", ScanFlags.AllowAllEscapes); term.AddStartEnd("\"", ScanFlags.AllowAllEscapes); term.AddPrefixFlag("@", ScanFlags.DisableEscapes | ScanFlags.AllowLineBreak | ScanFlags.AllowDoubledQuote); return term; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Text; namespace System.Data.Odbc { internal class OdbcMetaDataFactory : DbMetaDataFactory { private readonly struct SchemaFunctionName { internal SchemaFunctionName(string schemaName, ODBC32.SQL_API odbcFunction) { _schemaName = schemaName; _odbcFunction = odbcFunction; } internal readonly string _schemaName; internal readonly ODBC32.SQL_API _odbcFunction; } private const string _collectionName = "CollectionName"; private const string _populationMechanism = "PopulationMechanism"; private const string _prepareCollection = "PrepareCollection"; private readonly SchemaFunctionName[] _schemaMapping; internal static readonly char[] KeywordSeparatorChar = new char[1] { ',' }; internal OdbcMetaDataFactory(Stream XMLStream, string serverVersion, string serverVersionNormalized, OdbcConnection connection) : base(XMLStream, serverVersion, serverVersionNormalized) { // set up the colletion name ODBC function mapping guid mapping _schemaMapping = new SchemaFunctionName[] { new SchemaFunctionName(DbMetaDataCollectionNames.DataTypes,ODBC32.SQL_API.SQLGETTYPEINFO), new SchemaFunctionName(OdbcMetaDataCollectionNames.Columns,ODBC32.SQL_API.SQLCOLUMNS), new SchemaFunctionName(OdbcMetaDataCollectionNames.Indexes,ODBC32.SQL_API.SQLSTATISTICS), new SchemaFunctionName(OdbcMetaDataCollectionNames.Procedures,ODBC32.SQL_API.SQLPROCEDURES), new SchemaFunctionName(OdbcMetaDataCollectionNames.ProcedureColumns,ODBC32.SQL_API.SQLPROCEDURECOLUMNS), new SchemaFunctionName(OdbcMetaDataCollectionNames.ProcedureParameters,ODBC32.SQL_API.SQLPROCEDURECOLUMNS), new SchemaFunctionName(OdbcMetaDataCollectionNames.Tables,ODBC32.SQL_API.SQLTABLES), new SchemaFunctionName(OdbcMetaDataCollectionNames.Views,ODBC32.SQL_API.SQLTABLES)}; // verify the existance of the table in the data set DataTable metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; if (metaDataCollectionsTable == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.MetaDataCollections); } // copy the table filtering out any rows that don't apply to the current version of the provider metaDataCollectionsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.MetaDataCollections, null); // verify the existance of the table in the data set DataTable restrictionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; if (restrictionsTable != null) { // copy the table filtering out any rows that don't apply to the current version of the provider restrictionsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.Restrictions, null); } // need to filter out any of the collections where // 1) it is populated using prepare collection // 2) it is in the collection to odbc function mapping above // 3) the provider does not support the necessary odbc function DataColumn populationMechanism = metaDataCollectionsTable.Columns[_populationMechanism]; DataColumn collectionName = metaDataCollectionsTable.Columns[_collectionName]; DataColumn restrictionCollectionName = null; if (restrictionsTable != null) { restrictionCollectionName = restrictionsTable.Columns[_collectionName]; } foreach (DataRow collection in metaDataCollectionsTable.Rows) { if ((string)collection[populationMechanism] == _prepareCollection) { // is the collection in the mapping int mapping = -1; for (int i = 0; i < _schemaMapping.Length; i++) { if (_schemaMapping[i]._schemaName == (string)collection[collectionName]) { mapping = i; break; } } // no go on to the next collection if (mapping == -1) { continue; } // does the provider support the necessary odbc function // if not delete the row from the table if (connection.SQLGetFunctions(_schemaMapping[mapping]._odbcFunction) == false) { // but first delete any related restrictions if (restrictionsTable != null) { foreach (DataRow restriction in restrictionsTable.Rows) { if ((string)collection[collectionName] == (string)restriction[restrictionCollectionName]) { restriction.Delete(); } } restrictionsTable.AcceptChanges(); } collection.Delete(); } } } // replace the original table with the updated one metaDataCollectionsTable.AcceptChanges(); CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]); CollectionDataSet.Tables.Add(metaDataCollectionsTable); if (restrictionsTable != null) { CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]); CollectionDataSet.Tables.Add(restrictionsTable); } } private object BooleanFromODBC(object odbcSource) { if (odbcSource != DBNull.Value) { //convert to Int32 before doing the comparison //some odbc drivers report the odbcSource value as unsigned, in which case we will //have upgraded the type to Int32, and thus can't cast directly to short if (Convert.ToInt32(odbcSource, null) == 0) { return false; } else { return true; } } return DBNull.Value; } private OdbcCommand GetCommand(OdbcConnection connection) { OdbcCommand command = connection.CreateCommand(); // You need to make sure you pick up the transaction from the connection, // or odd things can happen... command.Transaction = connection.LocalTransaction; return command; } private DataTable DataTableFromDataReader(IDataReader reader, string tableName) { // set up the column structure of the data table from the reader object[] values; DataTable resultTable = NewDataTableFromReader(reader, out values, tableName); // populate the data table from the data reader while (reader.Read()) { reader.GetValues(values); resultTable.Rows.Add(values); } return resultTable; } private void DataTableFromDataReaderDataTypes(DataTable dataTypesTable, OdbcDataReader dataReader, OdbcConnection connection) { DataTable schemaTable = null; // // Build a DataTable from the reader schemaTable = dataReader.GetSchemaTable(); // vstfdevdiv:479715 Handle cases where reader is empty if (null == schemaTable) { throw ADP.OdbcNoTypesFromProvider(); } object[] getTypeInfoValues = new object[schemaTable.Rows.Count]; DataRow dataTypesRow; DataColumn typeNameColumn = dataTypesTable.Columns[DbMetaDataColumnNames.TypeName]; DataColumn providerDbTypeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.ProviderDbType]; DataColumn columnSizeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.ColumnSize]; DataColumn createParametersColumn = dataTypesTable.Columns[DbMetaDataColumnNames.CreateParameters]; DataColumn dataTypeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.DataType]; DataColumn isAutoIncermentableColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsAutoIncrementable]; DataColumn isCaseSensitiveColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsCaseSensitive]; DataColumn isFixedLengthColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedLength]; DataColumn isFixedPrecisionScaleColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedPrecisionScale]; DataColumn isLongColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsLong]; DataColumn isNullableColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsNullable]; DataColumn isSearchableColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchable]; DataColumn isSearchableWithLikeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchableWithLike]; DataColumn isUnsignedColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsUnsigned]; DataColumn maximumScaleColumn = dataTypesTable.Columns[DbMetaDataColumnNames.MaximumScale]; DataColumn minimumScaleColumn = dataTypesTable.Columns[DbMetaDataColumnNames.MinimumScale]; DataColumn literalPrefixColumn = dataTypesTable.Columns[DbMetaDataColumnNames.LiteralPrefix]; DataColumn literalSuffixColumn = dataTypesTable.Columns[DbMetaDataColumnNames.LiteralSuffix]; DataColumn SQLTypeNameColumn = dataTypesTable.Columns[OdbcMetaDataColumnNames.SQLType]; const int indexTYPE_NAME = 0; const int indexDATA_TYPE = 1; const int indexCOLUMN_SIZE = 2; const int indexCREATE_PARAMS = 5; const int indexAUTO_UNIQUE_VALUE = 11; const int indexCASE_SENSITIVE = 7; const int indexFIXED_PREC_SCALE = 10; const int indexNULLABLE = 6; const int indexSEARCHABLE = 8; const int indexUNSIGNED_ATTRIBUTE = 9; const int indexMAXIMUM_SCALE = 14; const int indexMINIMUM_SCALE = 13; const int indexLITERAL_PREFIX = 3; const int indexLITERAL_SUFFIX = 4; const int SQL_DATE_V2 = 9; const int SQL_TIME_V2 = 10; TypeMap typeMap; while (dataReader.Read()) { dataReader.GetValues(getTypeInfoValues); dataTypesRow = dataTypesTable.NewRow(); ODBC32.SQL_TYPE sqlType; dataTypesRow[typeNameColumn] = getTypeInfoValues[indexTYPE_NAME]; dataTypesRow[SQLTypeNameColumn] = getTypeInfoValues[indexDATA_TYPE]; sqlType = (ODBC32.SQL_TYPE)(int)Convert.ChangeType(getTypeInfoValues[indexDATA_TYPE], typeof(int), (System.IFormatProvider)null); // if the driver is pre version 3 and it returned the v2 SQL_DATE or SQL_TIME types they need // to be mapped to thier v3 equlivants if (connection.IsV3Driver == false) { if ((int)sqlType == SQL_DATE_V2) { sqlType = ODBC32.SQL_TYPE.TYPE_DATE; } else if ((int)sqlType == SQL_TIME_V2) { sqlType = ODBC32.SQL_TYPE.TYPE_TIME; } } try { typeMap = TypeMap.FromSqlType(sqlType); } // FromSqlType will throw an argument exception if it does not recognize the SqlType. // This is not an error since the GetTypeInfo DATA_TYPE may be a SQL data type or a driver specific // type. If there is no TypeMap for the type its not an error but it will degrade our level of // understanding of/ support for the type. catch (ArgumentException) { typeMap = null; } // if we have a type map we can determine the dbType and the CLR type if not leave them null if (typeMap != null) { dataTypesRow[providerDbTypeColumn] = typeMap._odbcType; dataTypesRow[dataTypeColumn] = typeMap._type.FullName; // setting isLong and isFixedLength only if we have a type map because for provider // specific types we have no idea what the types attributes are if GetTypeInfo did not // tell us switch (sqlType) { case ODBC32.SQL_TYPE.LONGVARCHAR: case ODBC32.SQL_TYPE.WLONGVARCHAR: case ODBC32.SQL_TYPE.LONGVARBINARY: case ODBC32.SQL_TYPE.SS_XML: dataTypesRow[isLongColumn] = true; dataTypesRow[isFixedLengthColumn] = false; break; case ODBC32.SQL_TYPE.VARCHAR: case ODBC32.SQL_TYPE.WVARCHAR: case ODBC32.SQL_TYPE.VARBINARY: dataTypesRow[isLongColumn] = false; dataTypesRow[isFixedLengthColumn] = false; break; case ODBC32.SQL_TYPE.CHAR: case ODBC32.SQL_TYPE.WCHAR: case ODBC32.SQL_TYPE.DECIMAL: case ODBC32.SQL_TYPE.NUMERIC: case ODBC32.SQL_TYPE.SMALLINT: case ODBC32.SQL_TYPE.INTEGER: case ODBC32.SQL_TYPE.REAL: case ODBC32.SQL_TYPE.FLOAT: case ODBC32.SQL_TYPE.DOUBLE: case ODBC32.SQL_TYPE.BIT: case ODBC32.SQL_TYPE.TINYINT: case ODBC32.SQL_TYPE.BIGINT: case ODBC32.SQL_TYPE.TYPE_DATE: case ODBC32.SQL_TYPE.TYPE_TIME: case ODBC32.SQL_TYPE.TIMESTAMP: case ODBC32.SQL_TYPE.TYPE_TIMESTAMP: case ODBC32.SQL_TYPE.GUID: case ODBC32.SQL_TYPE.SS_VARIANT: case ODBC32.SQL_TYPE.SS_UTCDATETIME: case ODBC32.SQL_TYPE.SS_TIME_EX: case ODBC32.SQL_TYPE.BINARY: dataTypesRow[isLongColumn] = false; dataTypesRow[isFixedLengthColumn] = true; break; case ODBC32.SQL_TYPE.SS_UDT: default: // for User defined types don't know if its long or if it is // varaible length or not so leave the fields null break; } } dataTypesRow[columnSizeColumn] = getTypeInfoValues[indexCOLUMN_SIZE]; dataTypesRow[createParametersColumn] = getTypeInfoValues[indexCREATE_PARAMS]; if ((getTypeInfoValues[indexAUTO_UNIQUE_VALUE] == DBNull.Value) || (Convert.ToInt16(getTypeInfoValues[indexAUTO_UNIQUE_VALUE], null) == 0)) { dataTypesRow[isAutoIncermentableColumn] = false; } else { dataTypesRow[isAutoIncermentableColumn] = true; } dataTypesRow[isCaseSensitiveColumn] = BooleanFromODBC(getTypeInfoValues[indexCASE_SENSITIVE]); dataTypesRow[isFixedPrecisionScaleColumn] = BooleanFromODBC(getTypeInfoValues[indexFIXED_PREC_SCALE]); if (getTypeInfoValues[indexNULLABLE] != DBNull.Value) { //Use Convert.ToInt16 instead of direct cast to short because the value will be Int32 in some cases switch ((ODBC32.SQL_NULLABILITY)Convert.ToInt16(getTypeInfoValues[indexNULLABLE], null)) { case ODBC32.SQL_NULLABILITY.NO_NULLS: dataTypesRow[isNullableColumn] = false; break; case ODBC32.SQL_NULLABILITY.NULLABLE: dataTypesRow[isNullableColumn] = true; break; case ODBC32.SQL_NULLABILITY.UNKNOWN: dataTypesRow[isNullableColumn] = DBNull.Value; break; } } if (DBNull.Value != getTypeInfoValues[indexSEARCHABLE]) { //Use Convert.ToInt16 instead of direct cast to short because the value will be Int32 in some cases short searchableValue = Convert.ToInt16(getTypeInfoValues[indexSEARCHABLE], null); switch (searchableValue) { case (short)ODBC32.SQL_SEARCHABLE.UNSEARCHABLE: dataTypesRow[isSearchableColumn] = false; dataTypesRow[isSearchableWithLikeColumn] = false; break; case (short)ODBC32.SQL_SEARCHABLE.LIKE_ONLY: dataTypesRow[isSearchableColumn] = false; dataTypesRow[isSearchableWithLikeColumn] = true; break; case (short)ODBC32.SQL_SEARCHABLE.ALL_EXCEPT_LIKE: dataTypesRow[isSearchableColumn] = true; dataTypesRow[isSearchableWithLikeColumn] = false; break; case (short)ODBC32.SQL_SEARCHABLE.SEARCHABLE: dataTypesRow[isSearchableColumn] = true; dataTypesRow[isSearchableWithLikeColumn] = true; break; } } dataTypesRow[isUnsignedColumn] = BooleanFromODBC(getTypeInfoValues[indexUNSIGNED_ATTRIBUTE]); //For assignment to the DataSet, don't cast the data types -- let the DataSet take care of any conversion if (getTypeInfoValues[indexMAXIMUM_SCALE] != DBNull.Value) { dataTypesRow[maximumScaleColumn] = getTypeInfoValues[indexMAXIMUM_SCALE]; } if (getTypeInfoValues[indexMINIMUM_SCALE] != DBNull.Value) { dataTypesRow[minimumScaleColumn] = getTypeInfoValues[indexMINIMUM_SCALE]; } if (getTypeInfoValues[indexLITERAL_PREFIX] != DBNull.Value) { dataTypesRow[literalPrefixColumn] = getTypeInfoValues[indexLITERAL_PREFIX]; } if (getTypeInfoValues[indexLITERAL_SUFFIX] != DBNull.Value) { dataTypesRow[literalSuffixColumn] = getTypeInfoValues[indexLITERAL_SUFFIX]; } dataTypesTable.Rows.Add(dataTypesRow); } } private DataTable DataTableFromDataReaderIndex(IDataReader reader, string tableName, string restrictionIndexName) { // set up the column structure of the data table from the reader object[] values; DataTable resultTable = NewDataTableFromReader(reader, out values, tableName); // populate the data table from the data reader int positionOfType = 6; int positionOfIndexName = 5; while (reader.Read()) { reader.GetValues(values); if (IncludeIndexRow(values[positionOfIndexName], restrictionIndexName, Convert.ToInt16(values[positionOfType], null)) == true) { resultTable.Rows.Add(values); } } return resultTable; } private DataTable DataTableFromDataReaderProcedureColumns(IDataReader reader, string tableName, bool isColumn) { // set up the column structure of the data table from the reader object[] values; DataTable resultTable = NewDataTableFromReader(reader, out values, tableName); // populate the data table from the data reader int positionOfColumnType = 4; while (reader.Read()) { reader.GetValues(values); // the column type should always be short but need to check just in case if (values[positionOfColumnType].GetType() == typeof(short)) { if ((((short)values[positionOfColumnType] == ODBC32.SQL_RESULT_COL) && (isColumn == true)) || (((short)values[positionOfColumnType] != ODBC32.SQL_RESULT_COL) && (isColumn == false))) { resultTable.Rows.Add(values); } } } return resultTable; } private DataTable DataTableFromDataReaderProcedures(IDataReader reader, string tableName, short procedureType) { // Build a DataTable from the reader // set up the column structure of the data table from the reader object[] values; DataTable resultTable = NewDataTableFromReader(reader, out values, tableName); // populate the data table from the data reader int positionOfProcedureType = 7; while (reader.Read()) { reader.GetValues(values); // the column type should always be short but need to check just in case its null if (values[positionOfProcedureType].GetType() == typeof(short)) { if ((short)values[positionOfProcedureType] == procedureType) { resultTable.Rows.Add(values); } } } return resultTable; } private void FillOutRestrictions(int restrictionsCount, string[] restrictions, object[] allRestrictions, string collectionName) { Debug.Assert(allRestrictions.Length >= restrictionsCount); int i = 0; // if we have restrictions put them in the restrictions array if (restrictions != null) { if (restrictions.Length > restrictionsCount) { throw ADP.TooManyRestrictions(collectionName); } for (i = 0; i < restrictions.Length; i++) { if (restrictions[i] != null) { allRestrictions[i] = restrictions[i]; } } } // initalize the rest to no restrictions for (; i < restrictionsCount; i++) { allRestrictions[i] = null; } } private DataTable GetColumnsCollection(string[] restrictions, OdbcConnection connection) { OdbcCommand command = null; OdbcDataReader dataReader = null; DataTable resultTable = null; const int columnsRestrictionsCount = 4; try { command = GetCommand(connection); string[] allRestrictions = new string[columnsRestrictionsCount]; FillOutRestrictions(columnsRestrictionsCount, restrictions, allRestrictions, OdbcMetaDataCollectionNames.Columns); dataReader = command.ExecuteReaderFromSQLMethod(allRestrictions, ODBC32.SQL_API.SQLCOLUMNS); resultTable = DataTableFromDataReader(dataReader, OdbcMetaDataCollectionNames.Columns); } finally { if (dataReader != null) { dataReader.Dispose(); }; if (command != null) { command.Dispose(); }; } return resultTable; } private DataTable GetDataSourceInformationCollection(string[] restrictions, OdbcConnection connection) { if (ADP.IsEmptyArray(restrictions) == false) { throw ADP.TooManyRestrictions(DbMetaDataCollectionNames.DataSourceInformation); } // verify that the data source information table is in the data set DataTable dataSourceInformationTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataSourceInformation]; if (dataSourceInformationTable == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataSourceInformation); } // copy the table filtering out any rows that don't apply to the current version of the provider dataSourceInformationTable = CloneAndFilterCollection(DbMetaDataCollectionNames.DataSourceInformation, null); // after filtering there better be just one row if (dataSourceInformationTable.Rows.Count != 1) { throw ADP.IncorrectNumberOfDataSourceInformationRows(); } DataRow dataSourceInformation = dataSourceInformationTable.Rows[0]; string stringValue; short int16Value; int int32Value; ODBC32.RetCode retcode; // update the catalog separator stringValue = connection.GetInfoStringUnhandled(ODBC32.SQL_INFO.CATALOG_NAME_SEPARATOR); if (!string.IsNullOrEmpty(stringValue)) { StringBuilder patternEscaped = new StringBuilder(); ADP.EscapeSpecialCharacters(stringValue, patternEscaped); dataSourceInformation[DbMetaDataColumnNames.CompositeIdentifierSeparatorPattern] = patternEscaped.ToString(); } // get the DBMS Name stringValue = connection.GetInfoStringUnhandled(ODBC32.SQL_INFO.DBMS_NAME); if (stringValue != null) { dataSourceInformation[DbMetaDataColumnNames.DataSourceProductName] = stringValue; } // update the server version strings dataSourceInformation[DbMetaDataColumnNames.DataSourceProductVersion] = ServerVersion; dataSourceInformation[DbMetaDataColumnNames.DataSourceProductVersionNormalized] = ServerVersionNormalized; // values that are the same for all ODBC drivers. See bug 105333 dataSourceInformation[DbMetaDataColumnNames.ParameterMarkerFormat] = "?"; dataSourceInformation[DbMetaDataColumnNames.ParameterMarkerPattern] = "\\?"; dataSourceInformation[DbMetaDataColumnNames.ParameterNameMaxLength] = 0; // determine the supportedJoinOperators // leave the column null if the GetInfo fails. There is no explicit value for // unknown. if (connection.IsV3Driver) { retcode = connection.GetInfoInt32Unhandled(ODBC32.SQL_INFO.SQL_OJ_CAPABILITIES_30, out int32Value); } else { retcode = connection.GetInfoInt32Unhandled(ODBC32.SQL_INFO.SQL_OJ_CAPABILITIES_20, out int32Value); } if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)) { Common.SupportedJoinOperators supportedJoinOperators = Common.SupportedJoinOperators.None; if ((int32Value & (int)ODBC32.SQL_OJ_CAPABILITIES.LEFT) != 0) { supportedJoinOperators = supportedJoinOperators | Common.SupportedJoinOperators.LeftOuter; } if ((int32Value & (int)ODBC32.SQL_OJ_CAPABILITIES.RIGHT) != 0) { supportedJoinOperators = supportedJoinOperators | Common.SupportedJoinOperators.RightOuter; } if ((int32Value & (int)ODBC32.SQL_OJ_CAPABILITIES.FULL) != 0) { supportedJoinOperators = supportedJoinOperators | Common.SupportedJoinOperators.FullOuter; } if ((int32Value & (int)ODBC32.SQL_OJ_CAPABILITIES.INNER) != 0) { supportedJoinOperators = supportedJoinOperators | Common.SupportedJoinOperators.Inner; } dataSourceInformation[DbMetaDataColumnNames.SupportedJoinOperators] = supportedJoinOperators; } // determine the GroupByBehavior retcode = connection.GetInfoInt16Unhandled(ODBC32.SQL_INFO.GROUP_BY, out int16Value); Common.GroupByBehavior groupByBehavior = Common.GroupByBehavior.Unknown; if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)) { switch (int16Value) { case (short)ODBC32.SQL_GROUP_BY.NOT_SUPPORTED: groupByBehavior = Common.GroupByBehavior.NotSupported; break; case (short)ODBC32.SQL_GROUP_BY.GROUP_BY_EQUALS_SELECT: groupByBehavior = Common.GroupByBehavior.ExactMatch; break; case (short)ODBC32.SQL_GROUP_BY.GROUP_BY_CONTAINS_SELECT: groupByBehavior = Common.GroupByBehavior.MustContainAll; break; case (short)ODBC32.SQL_GROUP_BY.NO_RELATION: groupByBehavior = Common.GroupByBehavior.Unrelated; break; /* COLLATE is new in ODBC 3.0 and GroupByBehavior does not have a value for it. case ODBC32.SQL_GROUP_BY.COLLATE: groupByBehavior = Common.GroupByBehavior.Unknown; break; */ } } dataSourceInformation[DbMetaDataColumnNames.GroupByBehavior] = groupByBehavior; // determine the identifier case retcode = connection.GetInfoInt16Unhandled(ODBC32.SQL_INFO.IDENTIFIER_CASE, out int16Value); Common.IdentifierCase identifierCase = Common.IdentifierCase.Unknown; if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)) { switch (int16Value) { case (short)ODBC32.SQL_IDENTIFIER_CASE.SENSITIVE: identifierCase = Common.IdentifierCase.Sensitive; break; case (short)ODBC32.SQL_IDENTIFIER_CASE.UPPER: case (short)ODBC32.SQL_IDENTIFIER_CASE.LOWER: case (short)ODBC32.SQL_IDENTIFIER_CASE.MIXED: identifierCase = Common.IdentifierCase.Insensitive; break; } } dataSourceInformation[DbMetaDataColumnNames.IdentifierCase] = identifierCase; // OrderByColumnsInSelect stringValue = connection.GetInfoStringUnhandled(ODBC32.SQL_INFO.ORDER_BY_COLUMNS_IN_SELECT); if (stringValue != null) { if (stringValue == "Y") { dataSourceInformation[DbMetaDataColumnNames.OrderByColumnsInSelect] = true; } else if (stringValue == "N") { dataSourceInformation[DbMetaDataColumnNames.OrderByColumnsInSelect] = false; } } // build the QuotedIdentifierPattern using the quote prefix and suffix from the provider and // assuming that the quote suffix is escaped via repetion (i.e " becomes "") stringValue = connection.QuoteChar(ADP.GetSchema); if (stringValue != null) { // by spec a blank identifier quote char indicates that the provider does not suppport // quoted identifiers if (stringValue != " ") { // only know how to build the parttern if the quote characters is 1 character // in all other cases just leave the field null if (stringValue.Length == 1) { StringBuilder scratchStringBuilder = new StringBuilder(); ADP.EscapeSpecialCharacters(stringValue, scratchStringBuilder); string escapedQuoteSuffixString = scratchStringBuilder.ToString(); scratchStringBuilder.Length = 0; ADP.EscapeSpecialCharacters(stringValue, scratchStringBuilder); scratchStringBuilder.Append("(([^"); scratchStringBuilder.Append(escapedQuoteSuffixString); scratchStringBuilder.Append("]|"); scratchStringBuilder.Append(escapedQuoteSuffixString); scratchStringBuilder.Append(escapedQuoteSuffixString); scratchStringBuilder.Append(")*)"); scratchStringBuilder.Append(escapedQuoteSuffixString); dataSourceInformation[DbMetaDataColumnNames.QuotedIdentifierPattern] = scratchStringBuilder.ToString(); } } } // determine the quoted identifier case retcode = connection.GetInfoInt16Unhandled(ODBC32.SQL_INFO.QUOTED_IDENTIFIER_CASE, out int16Value); Common.IdentifierCase quotedIdentifierCase = Common.IdentifierCase.Unknown; if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)) { switch (int16Value) { case (short)ODBC32.SQL_IDENTIFIER_CASE.SENSITIVE: quotedIdentifierCase = Common.IdentifierCase.Sensitive; break; case (short)ODBC32.SQL_IDENTIFIER_CASE.UPPER: case (short)ODBC32.SQL_IDENTIFIER_CASE.LOWER: case (short)ODBC32.SQL_IDENTIFIER_CASE.MIXED: quotedIdentifierCase = Common.IdentifierCase.Insensitive; break; } } dataSourceInformation[DbMetaDataColumnNames.QuotedIdentifierCase] = quotedIdentifierCase; dataSourceInformationTable.AcceptChanges(); return dataSourceInformationTable; } private DataTable GetDataTypesCollection(string[] restrictions, OdbcConnection connection) { if (ADP.IsEmptyArray(restrictions) == false) { throw ADP.TooManyRestrictions(DbMetaDataCollectionNames.DataTypes); } // verify the existance of the table in the data set DataTable dataTypesTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataTypes]; if (dataTypesTable == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataTypes); } // copy the data table it dataTypesTable = CloneAndFilterCollection(DbMetaDataCollectionNames.DataTypes, null); OdbcCommand command = null; OdbcDataReader dataReader = null; object[] allArguments = new object[1]; allArguments[0] = ODBC32.SQL_ALL_TYPES; try { command = GetCommand(connection); dataReader = command.ExecuteReaderFromSQLMethod(allArguments, ODBC32.SQL_API.SQLGETTYPEINFO); DataTableFromDataReaderDataTypes(dataTypesTable, dataReader, connection); } finally { if (dataReader != null) { dataReader.Dispose(); }; if (command != null) { command.Dispose(); }; } dataTypesTable.AcceptChanges(); return dataTypesTable; } private DataTable GetIndexCollection(string[] restrictions, OdbcConnection connection) { OdbcCommand command = null; OdbcDataReader dataReader = null; DataTable resultTable = null; const int nativeRestrictionsCount = 5; const int indexRestrictionsCount = 4; const int indexOfTableName = 2; const int indexOfIndexName = 3; try { command = GetCommand(connection); object[] allRestrictions = new object[nativeRestrictionsCount]; FillOutRestrictions(indexRestrictionsCount, restrictions, allRestrictions, OdbcMetaDataCollectionNames.Indexes); if (allRestrictions[indexOfTableName] == null) { throw ODBC.GetSchemaRestrictionRequired(); } allRestrictions[3] = (short)ODBC32.SQL_INDEX.ALL; allRestrictions[4] = (short)ODBC32.SQL_STATISTICS_RESERVED.ENSURE; dataReader = command.ExecuteReaderFromSQLMethod(allRestrictions, ODBC32.SQL_API.SQLSTATISTICS); string indexName = null; if (restrictions != null) { if (restrictions.Length >= indexOfIndexName + 1) { indexName = restrictions[indexOfIndexName]; } } resultTable = DataTableFromDataReaderIndex(dataReader, OdbcMetaDataCollectionNames.Indexes, indexName); } finally { if (dataReader != null) { dataReader.Dispose(); }; if (command != null) { command.Dispose(); }; } return resultTable; } private DataTable GetProcedureColumnsCollection(string[] restrictions, OdbcConnection connection, bool isColumns) { OdbcCommand command = null; OdbcDataReader dataReader = null; DataTable resultTable = null; const int procedureColumnsRestrictionsCount = 4; try { command = GetCommand(connection); string[] allRestrictions = new string[procedureColumnsRestrictionsCount]; FillOutRestrictions(procedureColumnsRestrictionsCount, restrictions, allRestrictions, OdbcMetaDataCollectionNames.Columns); dataReader = command.ExecuteReaderFromSQLMethod(allRestrictions, ODBC32.SQL_API.SQLPROCEDURECOLUMNS); string collectionName; if (isColumns == true) { collectionName = OdbcMetaDataCollectionNames.ProcedureColumns; } else { collectionName = OdbcMetaDataCollectionNames.ProcedureParameters; } resultTable = DataTableFromDataReaderProcedureColumns(dataReader, collectionName, isColumns); } finally { if (dataReader != null) { dataReader.Dispose(); }; if (command != null) { command.Dispose(); }; } return resultTable; } private DataTable GetProceduresCollection(string[] restrictions, OdbcConnection connection) { OdbcCommand command = null; OdbcDataReader dataReader = null; DataTable resultTable = null; const int columnsRestrictionsCount = 4; const int indexOfProcedureType = 3; try { command = GetCommand(connection); string[] allRestrictions = new string[columnsRestrictionsCount]; FillOutRestrictions(columnsRestrictionsCount, restrictions, allRestrictions, OdbcMetaDataCollectionNames.Procedures); dataReader = command.ExecuteReaderFromSQLMethod(allRestrictions, ODBC32.SQL_API.SQLPROCEDURES); if (allRestrictions[indexOfProcedureType] == null) { resultTable = DataTableFromDataReader(dataReader, OdbcMetaDataCollectionNames.Procedures); } else { short procedureType; if ((restrictions[indexOfProcedureType] == "SQL_PT_UNKNOWN") || (restrictions[indexOfProcedureType] == "0" /*ODBC32.SQL_PROCEDURETYPE.UNKNOWN*/)) { procedureType = (short)ODBC32.SQL_PROCEDURETYPE.UNKNOWN; } else if ((restrictions[indexOfProcedureType] == "SQL_PT_PROCEDURE") || (restrictions[indexOfProcedureType] == "1" /*ODBC32.SQL_PROCEDURETYPE.PROCEDURE*/)) { procedureType = (short)ODBC32.SQL_PROCEDURETYPE.PROCEDURE; } else if ((restrictions[indexOfProcedureType] == "SQL_PT_FUNCTION") || (restrictions[indexOfProcedureType] == "2" /*ODBC32.SQL_PROCEDURETYPE.FUNCTION*/)) { procedureType = (short)ODBC32.SQL_PROCEDURETYPE.FUNCTION; } else { throw ADP.InvalidRestrictionValue(OdbcMetaDataCollectionNames.Procedures, "PROCEDURE_TYPE", restrictions[indexOfProcedureType]); } resultTable = DataTableFromDataReaderProcedures(dataReader, OdbcMetaDataCollectionNames.Procedures, procedureType); } } finally { if (dataReader != null) { dataReader.Dispose(); }; if (command != null) { command.Dispose(); }; } return resultTable; } private DataTable GetReservedWordsCollection(string[] restrictions, OdbcConnection connection) { if (ADP.IsEmptyArray(restrictions) == false) { throw ADP.TooManyRestrictions(DbMetaDataCollectionNames.ReservedWords); } // verify the existance of the table in the data set DataTable reservedWordsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.ReservedWords]; if (reservedWordsTable == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords); } // copy the table filtering out any rows that don't apply to tho current version of the prrovider reservedWordsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.ReservedWords, null); DataColumn reservedWordColumn = reservedWordsTable.Columns[DbMetaDataColumnNames.ReservedWord]; if (reservedWordColumn == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords); } string keywords = connection.GetInfoStringUnhandled(ODBC32.SQL_INFO.KEYWORDS); if (null != keywords) { string[] values = keywords.Split(KeywordSeparatorChar); for (int i = 0; i < values.Length; ++i) { DataRow row = reservedWordsTable.NewRow(); row[reservedWordColumn] = values[i]; reservedWordsTable.Rows.Add(row); row.AcceptChanges(); } } return reservedWordsTable; } private DataTable GetTablesCollection(string[] restrictions, OdbcConnection connection, bool isTables) { OdbcCommand command = null; OdbcDataReader dataReader = null; DataTable resultTable = null; const int tablesRestrictionsCount = 3; const string includedTableTypesTables = "TABLE,SYSTEM TABLE"; const string includedTableTypesViews = "VIEW"; string includedTableTypes; string dataTableName; try { //command = (OdbcCommand) connection.CreateCommand(); command = GetCommand(connection); string[] allArguments = new string[tablesRestrictionsCount + 1]; if (isTables == true) { includedTableTypes = includedTableTypesTables; dataTableName = OdbcMetaDataCollectionNames.Tables; } else { includedTableTypes = includedTableTypesViews; dataTableName = OdbcMetaDataCollectionNames.Views; } FillOutRestrictions(tablesRestrictionsCount, restrictions, allArguments, dataTableName); allArguments[tablesRestrictionsCount] = includedTableTypes; dataReader = command.ExecuteReaderFromSQLMethod(allArguments, ODBC32.SQL_API.SQLTABLES); resultTable = DataTableFromDataReader(dataReader, dataTableName); } finally { if (dataReader != null) { dataReader.Dispose(); }; if (command != null) { command.Dispose(); }; } return resultTable; } private bool IncludeIndexRow(object rowIndexName, string restrictionIndexName, short rowIndexType) { // never include table statictics rows if (rowIndexType == (short)ODBC32.SQL_STATISTICSTYPE.TABLE_STAT) { return false; } if ((restrictionIndexName != null) && (restrictionIndexName != (string)rowIndexName)) { return false; } return true; } private DataTable NewDataTableFromReader(IDataReader reader, out object[] values, string tableName) { DataTable resultTable = new DataTable(tableName); resultTable.Locale = System.Globalization.CultureInfo.InvariantCulture; DataTable schemaTable = reader.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { resultTable.Columns.Add(row["ColumnName"] as string, (Type)row["DataType"] as Type); } values = new object[resultTable.Columns.Count]; return resultTable; } protected override DataTable PrepareCollection(string collectionName, string[] restrictions, DbConnection connection) { DataTable resultTable = null; OdbcConnection odbcConnection = (OdbcConnection)connection; if (collectionName == OdbcMetaDataCollectionNames.Tables) { resultTable = GetTablesCollection(restrictions, odbcConnection, true); } else if (collectionName == OdbcMetaDataCollectionNames.Views) { resultTable = GetTablesCollection(restrictions, odbcConnection, false); } else if (collectionName == OdbcMetaDataCollectionNames.Columns) { resultTable = GetColumnsCollection(restrictions, odbcConnection); } else if (collectionName == OdbcMetaDataCollectionNames.Procedures) { resultTable = GetProceduresCollection(restrictions, odbcConnection); } else if (collectionName == OdbcMetaDataCollectionNames.ProcedureColumns) { resultTable = GetProcedureColumnsCollection(restrictions, odbcConnection, true); } else if (collectionName == OdbcMetaDataCollectionNames.ProcedureParameters) { resultTable = GetProcedureColumnsCollection(restrictions, odbcConnection, false); } else if (collectionName == OdbcMetaDataCollectionNames.Indexes) { resultTable = GetIndexCollection(restrictions, odbcConnection); } else if (collectionName == DbMetaDataCollectionNames.DataTypes) { resultTable = GetDataTypesCollection(restrictions, odbcConnection); } else if (collectionName == DbMetaDataCollectionNames.DataSourceInformation) { resultTable = GetDataSourceInformationCollection(restrictions, odbcConnection); } else if (collectionName == DbMetaDataCollectionNames.ReservedWords) { resultTable = GetReservedWordsCollection(restrictions, odbcConnection); } if (resultTable == null) { throw ADP.UnableToBuildCollection(collectionName); } return resultTable; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Specialized producer/consumer queues. // // // ************<IMPORTANT NOTE>************* // // src\ndp\clr\src\bcl\system\threading\tasks\producerConsumerQueue.cs // src\ndp\fx\src\dataflow\system\threading\tasks\dataflow\internal\producerConsumerQueue.cs // Keep both of them consistent by changing the other file when you change this one, also avoid: // 1- To reference interneal types in mscorlib // 2- To reference any dataflow specific types // This should be fixed post Dev11 when this class becomes public. // // ************</IMPORTANT NOTE>************* // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Threading.Tasks { /// <summary>Represents a producer/consumer queue used internally by dataflow blocks.</summary> /// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam> internal interface IProducerConsumerQueue<T> : IEnumerable<T> { /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> /// <remarks>This method is meant to be thread-safe subject to the particular nature of the implementation.</remarks> void Enqueue(T item); /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> /// <remarks>This method is meant to be thread-safe subject to the particular nature of the implementation.</remarks> bool TryDequeue(out T result); /// <summary>Gets whether the collection is currently empty.</summary> /// <remarks>This method may or may not be thread-safe.</remarks> bool IsEmpty { get; } /// <summary>Gets the number of items in the collection.</summary> /// <remarks>In many implementations, this method will not be thread-safe.</remarks> int Count { get; } /// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary> /// <param name="syncObj">The sync object used to lock</param> /// <returns>The collection count</returns> int GetCountSafe(object syncObj); } /// <summary> /// Provides a producer/consumer queue safe to be used by any number of producers and consumers concurrently. /// </summary> /// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam> [DebuggerDisplay("Count = {Count}")] internal sealed class MultiProducerMultiConsumerQueue<T> : LowLevelConcurrentQueue<T>, IProducerConsumerQueue<T> { /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> void IProducerConsumerQueue<T>.Enqueue(T item) { base.Enqueue(item); } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> bool IProducerConsumerQueue<T>.TryDequeue(out T result) { return base.TryDequeue(out result); } /// <summary>Gets whether the collection is currently empty.</summary> bool IProducerConsumerQueue<T>.IsEmpty { get { return base.IsEmpty; } } /// <summary>Gets the number of items in the collection.</summary> int IProducerConsumerQueue<T>.Count { get { return base.Count; } } /// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary> /// <remarks>ConcurrentQueue.Count is thread safe, no need to acquire the lock.</remarks> int IProducerConsumerQueue<T>.GetCountSafe(object syncObj) { return base.Count; } } /// <summary> /// Provides a producer/consumer queue safe to be used by only one producer and one consumer concurrently. /// </summary> /// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SingleProducerSingleConsumerQueue<>.SingleProducerSingleConsumerQueue_DebugView))] internal sealed class SingleProducerSingleConsumerQueue<T> : IProducerConsumerQueue<T> { // Design: // // SingleProducerSingleConsumerQueue (SPSCQueue) is a concurrent queue designed to be used // by one producer thread and one consumer thread. SPSCQueue does not work correctly when used by // multiple producer threads concurrently or multiple consumer threads concurrently. // // SPSCQueue is based on segments that behave like circular buffers. Each circular buffer is represented // as an array with two indexes: m_first and m_last. m_first is the index of the array slot for the consumer // to read next, and m_last is the slot for the producer to write next. The circular buffer is empty when // (m_first == m_last), and full when ((m_last+1) % m_array.Length == m_first). // // Since m_first is only ever modified by the consumer thread and m_last by the producer, the two indices can // be updated without interlocked operations. As long as the queue size fits inside a single circular buffer, // enqueues and dequeues simply advance the corresponding indices around the circular buffer. If an enqueue finds // that there is no room in the existing buffer, however, a new circular buffer is allocated that is twice as big // as the old buffer. From then on, the producer will insert values into the new buffer. The consumer will first // empty out the old buffer and only then follow the producer into the new (larger) buffer. // // As described above, the enqueue operation on the fast path only modifies the m_first field of the current segment. // However, it also needs to read m_last in order to verify that there is room in the current segment. Similarly, the // dequeue operation on the fast path only needs to modify m_last, but also needs to read m_first to verify that the // queue is non-empty. This results in true cache line sharing between the producer and the consumer. // // The cache line sharing issue can be mitigating by having a possibly stale copy of m_first that is owned by the producer, // and a possibly stale copy of m_last that is owned by the consumer. So, the consumer state is described using // (m_first, m_lastCopy) and the producer state using (m_firstCopy, m_last). The consumer state is separated from // the producer state by padding, which allows fast-path enqueues and dequeues from hitting shared cache lines. // m_lastCopy is the consumer's copy of m_last. Whenever the consumer can tell that there is room in the buffer // simply by observing m_lastCopy, the consumer thread does not need to read m_last and thus encounter a cache miss. Only // when the buffer appears to be empty will the consumer refresh m_lastCopy from m_last. m_firstCopy is used by the producer // in the same way to avoid reading m_first on the hot path. /// <summary>The initial size to use for segments (in number of elements).</summary> private const int INIT_SEGMENT_SIZE = 32; // must be a power of 2 /// <summary>The maximum size to use for segments (in number of elements).</summary> private const int MAX_SEGMENT_SIZE = 0x1000000; // this could be made as large as Int32.MaxValue / 2 /// <summary>The head of the linked list of segments.</summary> private volatile Segment m_head; /// <summary>The tail of the linked list of segments.</summary> private volatile Segment m_tail; /// <summary>Initializes the queue.</summary> internal SingleProducerSingleConsumerQueue() { // Validate constants in ctor rather than in an explicit cctor that would cause perf degradation Debug.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0."); Debug.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2"); Debug.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum."); Debug.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur."); // Initialize the queue m_head = m_tail = new Segment(INIT_SEGMENT_SIZE); } /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> public void Enqueue(T item) { Segment segment = m_tail; var array = segment.m_array; int last = segment.m_state.m_last; // local copy to avoid multiple volatile reads // Fast path: there's obviously room in the current segment int tail2 = (last + 1) & (array.Length - 1); if (tail2 != segment.m_state.m_firstCopy) { array[last] = item; segment.m_state.m_last = tail2; } // Slow path: there may not be room in the current segment. else EnqueueSlow(item, ref segment); } /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> /// <param name="segment">The segment in which to first attempt to store the item.</param> private void EnqueueSlow(T item, ref Segment segment) { Debug.Assert(segment != null, "Expected a non-null segment."); if (segment.m_state.m_firstCopy != segment.m_state.m_first) { segment.m_state.m_firstCopy = segment.m_state.m_first; Enqueue(item); // will only recur once for this enqueue operation return; } int newSegmentSize = m_tail.m_array.Length << 1; // double size Debug.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow."); if (newSegmentSize > MAX_SEGMENT_SIZE) newSegmentSize = MAX_SEGMENT_SIZE; var newSegment = new Segment(newSegmentSize); newSegment.m_array[0] = item; newSegment.m_state.m_last = 1; newSegment.m_state.m_lastCopy = 1; try { } finally { // Finally block to protect against corruption due to a thread abort // between setting m_next and setting m_tail. Volatile.Write(ref m_tail.m_next, newSegment); // ensure segment not published until item is fully stored m_tail = newSegment; } } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> public bool TryDequeue(out T result) { Segment segment = m_head; var array = segment.m_array; int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads // Fast path: there's obviously data available in the current segment if (first != segment.m_state.m_lastCopy) { result = array[first]; array[first] = default(T); // Clear the slot to release the element segment.m_state.m_first = (first + 1) & (array.Length - 1); return true; } // Slow path: there may not be data available in the current segment else return TryDequeueSlow(ref segment, ref array, out result); } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="array">The array from which the item was dequeued.</param> /// <param name="segment">The segment from which the item was dequeued.</param> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> private bool TryDequeueSlow(ref Segment segment, ref T[] array, out T result) { Debug.Assert(segment != null, "Expected a non-null segment."); Debug.Assert(array != null, "Expected a non-null item array."); if (segment.m_state.m_last != segment.m_state.m_lastCopy) { segment.m_state.m_lastCopy = segment.m_state.m_last; return TryDequeue(out result); // will only recur once for this dequeue operation } if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last) { segment = segment.m_next; array = segment.m_array; m_head = segment; } var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads if (first == segment.m_state.m_last) { result = default(T); return false; } result = array[first]; array[first] = default(T); // Clear the slot to release the element segment.m_state.m_first = (first + 1) & (segment.m_array.Length - 1); segment.m_state.m_lastCopy = segment.m_state.m_last; // Refresh m_lastCopy to ensure that m_first has not passed m_lastCopy return true; } /// <summary>Attempts to peek at an item in the queue.</summary> /// <param name="result">The peeked item.</param> /// <returns>true if an item could be peeked; otherwise, false.</returns> public bool TryPeek(out T result) { Segment segment = m_head; var array = segment.m_array; int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads // Fast path: there's obviously data available in the current segment if (first != segment.m_state.m_lastCopy) { result = array[first]; return true; } // Slow path: there may not be data available in the current segment else return TryPeekSlow(ref segment, ref array, out result); } /// <summary>Attempts to peek at an item in the queue.</summary> /// <param name="array">The array from which the item is peeked.</param> /// <param name="segment">The segment from which the item is peeked.</param> /// <param name="result">The peeked item.</param> /// <returns>true if an item could be peeked; otherwise, false.</returns> private bool TryPeekSlow(ref Segment segment, ref T[] array, out T result) { Debug.Assert(segment != null, "Expected a non-null segment."); Debug.Assert(array != null, "Expected a non-null item array."); if (segment.m_state.m_last != segment.m_state.m_lastCopy) { segment.m_state.m_lastCopy = segment.m_state.m_last; return TryPeek(out result); // will only recur once for this peek operation } if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last) { segment = segment.m_next; array = segment.m_array; m_head = segment; } var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads if (first == segment.m_state.m_last) { result = default(T); return false; } result = array[first]; return true; } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="predicate">The predicate that must return true for the item to be dequeued. If null, all items implicitly return true.</param> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> public bool TryDequeueIf(Predicate<T> predicate, out T result) { Segment segment = m_head; var array = segment.m_array; int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads // Fast path: there's obviously data available in the current segment if (first != segment.m_state.m_lastCopy) { result = array[first]; if (predicate == null || predicate(result)) { array[first] = default(T); // Clear the slot to release the element segment.m_state.m_first = (first + 1) & (array.Length - 1); return true; } else { result = default(T); return false; } } // Slow path: there may not be data available in the current segment else return TryDequeueIfSlow(predicate, ref segment, ref array, out result); } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="predicate">The predicate that must return true for the item to be dequeued. If null, all items implicitly return true.</param> /// <param name="array">The array from which the item was dequeued.</param> /// <param name="segment">The segment from which the item was dequeued.</param> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> private bool TryDequeueIfSlow(Predicate<T> predicate, ref Segment segment, ref T[] array, out T result) { Debug.Assert(segment != null, "Expected a non-null segment."); Debug.Assert(array != null, "Expected a non-null item array."); if (segment.m_state.m_last != segment.m_state.m_lastCopy) { segment.m_state.m_lastCopy = segment.m_state.m_last; return TryDequeueIf(predicate, out result); // will only recur once for this dequeue operation } if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last) { segment = segment.m_next; array = segment.m_array; m_head = segment; } var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads if (first == segment.m_state.m_last) { result = default(T); return false; } result = array[first]; if (predicate == null || predicate(result)) { array[first] = default(T); // Clear the slot to release the element segment.m_state.m_first = (first + 1) & (segment.m_array.Length - 1); segment.m_state.m_lastCopy = segment.m_state.m_last; // Refresh m_lastCopy to ensure that m_first has not passed m_lastCopy return true; } else { result = default(T); return false; } } public void Clear() { T ignored; while (TryDequeue(out ignored)) ; } /// <summary>Gets whether the collection is currently empty.</summary> /// <remarks>WARNING: This should not be used concurrently without further vetting.</remarks> public bool IsEmpty { // This implementation is optimized for calls from the consumer. get { var head = m_head; if (head.m_state.m_first != head.m_state.m_lastCopy) return false; // m_first is volatile, so the read of m_lastCopy cannot get reordered if (head.m_state.m_first != head.m_state.m_last) return false; return head.m_next == null; } } /// <summary>Gets an enumerable for the collection.</summary> /// <remarks>WARNING: This should only be used for debugging purposes. It is not safe to be used concurrently.</remarks> public IEnumerator<T> GetEnumerator() { for (Segment segment = m_head; segment != null; segment = segment.m_next) { for (int pt = segment.m_state.m_first; pt != segment.m_state.m_last; pt = (pt + 1) & (segment.m_array.Length - 1)) { yield return segment.m_array[pt]; } } } /// <summary>Gets an enumerable for the collection.</summary> /// <remarks>WARNING: This should only be used for debugging purposes. It is not safe to be used concurrently.</remarks> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary>Gets the number of items in the collection.</summary> /// <remarks>WARNING: This should only be used for debugging purposes. It is not meant to be used concurrently.</remarks> public int Count { get { int count = 0; for (Segment segment = m_head; segment != null; segment = segment.m_next) { int arraySize = segment.m_array.Length; int first, last; while (true) // Count is not meant to be used concurrently, but this helps to avoid issues if it is { first = segment.m_state.m_first; last = segment.m_state.m_last; if (first == segment.m_state.m_first) break; } count += (last - first) & (arraySize - 1); } return count; } } /// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary> /// <remarks>The Count is not thread safe, so we need to acquire the lock.</remarks> int IProducerConsumerQueue<T>.GetCountSafe(object syncObj) { Debug.Assert(syncObj != null, "The syncObj parameter is null."); lock (syncObj) { return Count; } } /// <summary>A segment in the queue containing one or more items.</summary> [StructLayout(LayoutKind.Sequential)] private sealed class Segment { /// <summary>The next segment in the linked list of segments.</summary> internal Segment m_next; /// <summary>The data stored in this segment.</summary> internal readonly T[] m_array; /// <summary>Details about the segment.</summary> internal SegmentState m_state; // separated out to enable StructLayout attribute to take effect /// <summary>Initializes the segment.</summary> /// <param name="size">The size to use for this segment.</param> internal Segment(int size) { Debug.Assert((size & (size - 1)) == 0, "Size must be a power of 2"); m_array = new T[size]; } } /// <summary>Stores information about a segment.</summary> [StructLayout(LayoutKind.Sequential)] // enforce layout so that padding reduces false sharing private struct SegmentState { /// <summary>Padding to reduce false sharing between the segment's array and m_first.</summary> internal PaddingFor32 m_pad0; /// <summary>The index of the current head in the segment.</summary> internal volatile int m_first; /// <summary>A copy of the current tail index.</summary> internal int m_lastCopy; // not volatile as read and written by the producer, except for IsEmpty, and there m_lastCopy is only read after reading the volatile m_first /// <summary>Padding to reduce false sharing between the first and last.</summary> internal PaddingFor32 m_pad1; /// <summary>A copy of the current head index.</summary> internal int m_firstCopy; // not voliatle as only read and written by the consumer thread /// <summary>The index of the current tail in the segment.</summary> internal volatile int m_last; /// <summary>Padding to reduce false sharing with the last and what's after the segment.</summary> internal PaddingFor32 m_pad2; } /// <summary>Debugger type proxy for a SingleProducerSingleConsumerQueue of T.</summary> private sealed class SingleProducerSingleConsumerQueue_DebugView { /// <summary>The queue being visualized.</summary> private readonly SingleProducerSingleConsumerQueue<T> m_queue; /// <summary>Initializes the debug view.</summary> /// <param name="enumerable">The queue being debugged.</param> public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue<T> queue) { Debug.Assert(queue != null, "Expected a non-null queue."); m_queue = queue; } /// <summary>Gets the contents of the list.</summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get { LowLevelList<T> list = new LowLevelList<T>(); foreach (T item in m_queue) list.Add(item); return list.ToArray(); } } } } /// <summary>A placeholder class for common padding constants and eventually routines.</summary> internal static class PaddingHelpers { /// <summary>A size greater than or equal to the size of the most common CPU cache lines.</summary> internal const int CACHE_LINE_SIZE = 128; } /// <summary>Padding structure used to minimize false sharing in SingleProducerSingleConsumerQueue{T}.</summary> [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(Int32))] // Based on common case of 64-byte cache lines internal struct PaddingFor32 { } }
//----------------------------------------------------------------------- // <copyright file="BasicServer.cs" company="AllSeen Alliance."> // Copyright (c) 2012, AllSeen Alliance. All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // </copyright> //----------------------------------------------------------------------- using UnityEngine; using AllJoynUnity; using System.Runtime.InteropServices; namespace basic_server { class BasicServer { private const string INTERFACE_NAME = "org.alljoyn.Bus.sample"; private const string SERVICE_NAME = "org.alljoyn.Bus.sample"; private const string SERVICE_PATH = "/sample"; private const ushort SERVICE_PORT = 25; private static readonly string[] connectArgs = {"null:"}; private AllJoyn.BusAttachment msgBus; private MyBusListener busListener; private MySessionPortListener sessionPortListener; private TestBusObject testObj; private AllJoyn.InterfaceDescription testIntf; public static string serverText; public AllJoyn.SessionOpts opts; private static bool sJoinComplete = false; class TestBusObject : AllJoyn.BusObject { public TestBusObject (AllJoyn.BusAttachment bus, string path) : base(path, false) { AllJoyn.InterfaceDescription exampleIntf = bus.GetInterface (INTERFACE_NAME); AllJoyn.QStatus status = AddInterface (exampleIntf); if (!status) { serverText += "Server Failed to add interface " + status.ToString () + "\n"; Debug.Log ("Server Failed to add interface " + status.ToString ()); } AllJoyn.InterfaceDescription.Member catMember = exampleIntf.GetMember ("cat"); status = AddMethodHandler (catMember, this.Cat); if (!status) { serverText += "Server Failed to add method handler " + status.ToString () + "\n"; Debug.Log ("Server Failed to add method handler " + status.ToString ()); } } protected override void OnObjectRegistered () { serverText += "Server ObjectRegistered has been called\n"; Debug.Log ("Server ObjectRegistered has been called"); } protected void Cat (AllJoyn.InterfaceDescription.Member member, AllJoyn.Message message) { string outStr = (string)message [0] + (string)message [1]; AllJoyn.MsgArg outArgs = new AllJoyn.MsgArg(); outArgs = outStr; AllJoyn.QStatus status = MethodReply (message, outArgs); if (!status) { serverText += "Server Ping: Error sending reply\n"; Debug.Log ("Server Ping: Error sending reply"); } } } class MyBusListener : AllJoyn.BusListener { protected override void ListenerRegistered (AllJoyn.BusAttachment busAttachment) { serverText += "Server ListenerRegistered: busAttachment=" + busAttachment + "\n"; Debug.Log ("Server ListenerRegistered: busAttachment=" + busAttachment); } protected override void NameOwnerChanged (string busName, string previousOwner, string newOwner) { if (string.Compare (SERVICE_NAME, busName) == 0) { serverText += "Server NameOwnerChanged: name=" + busName + ", oldOwner=" + previousOwner + ", newOwner=" + newOwner + "\n"; Debug.Log ("Server NameOwnerChanged: name=" + busName + ", oldOwner=" + previousOwner + ", newOwner=" + newOwner); } } } class MySessionPortListener : AllJoyn.SessionPortListener { protected override bool AcceptSessionJoiner (ushort sessionPort, string joiner, AllJoyn.SessionOpts opts) { if (sessionPort != SERVICE_PORT) { serverText += "Server Rejecting join attempt on unexpected session port " + sessionPort + "\n"; Debug.Log ("Server Rejecting join attempt on unexpected session port " + sessionPort); return false; } serverText += "Server Accepting join session request from " + joiner + " (opts.proximity=" + opts.Proximity + ", opts.traffic=" + opts.Traffic + ", opts.transports=" + opts.Transports + ")\n"; Debug.Log ("Server Accepting join session request from " + joiner + " (opts.proximity=" + opts.Proximity + ", opts.traffic=" + opts.Traffic + ", opts.transports=" + opts.Transports + ")"); return true; } protected override void SessionJoined (ushort sessionPort, uint sessionId, string joiner) { Debug.Log ("Session Joined!!!!!!"); theSessionId = sessionId; sJoinComplete = true; } } private static uint theSessionId = 0; public BasicServer () { serverText = ""; // Create message bus msgBus = new AllJoyn.BusAttachment ("myApp", true); // Add org.alljoyn.Bus.method_sample interface AllJoyn.QStatus status = msgBus.CreateInterface (INTERFACE_NAME, false, out testIntf); if (status) { serverText += "Server Interface Created.\n"; Debug.Log ("Server Interface Created."); testIntf.AddMember (AllJoyn.Message.Type.MethodCall, "cat", "ss", "s", "inStr1,inStr2,outStr"); testIntf.Activate (); } else { serverText += "Failed to create interface 'org.alljoyn.Bus.method_sample'\n"; Debug.Log ("Failed to create interface 'org.alljoyn.Bus.method_sample'"); } // Create a bus listener busListener = new MyBusListener (); if (status) { msgBus.RegisterBusListener (busListener); serverText += "Server BusListener Registered.\n"; Debug.Log ("Server BusListener Registered."); } // Set up bus object testObj = new TestBusObject ( msgBus, SERVICE_PATH); // Start the msg bus if (status) { status = msgBus.Start (); if (status) { serverText += "Server BusAttachment started.\n"; Debug.Log ("Server BusAttachment started."); msgBus.RegisterBusObject (testObj); for (int i = 0; i < connectArgs.Length; ++i) { status = msgBus.Connect (connectArgs [i]); if (status) { serverText += "BusAttchement.Connect(" + connectArgs [i] + ") SUCCEDED.\n"; Debug.Log ("BusAttchement.Connect(" + connectArgs [i] + ") SUCCEDED."); break; } else { serverText += "BusAttachment.Connect(" + connectArgs [i] + ") failed.\n"; Debug.Log ("BusAttachment.Connect(" + connectArgs [i] + ") failed."); } } if (!status) { serverText += "BusAttachment.Connect failed.\n"; Debug.Log ("BusAttachment.Connect failed."); } } else { serverText += "Server BusAttachment.Start failed.\n"; Debug.Log ("Server BusAttachment.Start failed."); } } // Request name if (status) { status = msgBus.RequestName (SERVICE_NAME, AllJoyn.DBus.NameFlags.ReplaceExisting | AllJoyn.DBus.NameFlags.DoNotQueue); if (!status) { serverText += "Server RequestName(" + SERVICE_NAME + ") failed (status=" + status + ")\n"; Debug.Log ("Server RequestName(" + SERVICE_NAME + ") failed (status=" + status + ")"); } } // Create session opts = new AllJoyn.SessionOpts (AllJoyn.SessionOpts.TrafficType.Messages, true, AllJoyn.SessionOpts.ProximityType.Any, AllJoyn.TransportMask.Any); if (status) { ushort sessionPort = SERVICE_PORT; sessionPortListener = new MySessionPortListener (); status = msgBus.BindSessionPort (ref sessionPort, opts, sessionPortListener); if (!status || sessionPort != SERVICE_PORT) { serverText += "Server BindSessionPort failed (" + status + ")\n"; Debug.Log ("Server BindSessionPort failed (" + status + ")"); } } // Advertise name if (status) { status = msgBus.AdvertiseName (SERVICE_NAME, opts.Transports); if (!status) { serverText += "Server Failed to advertise name " + SERVICE_NAME + " (" + status + ")\n"; Debug.Log ("Server Failed to advertise name " + SERVICE_NAME + " (" + status + ")"); } } serverText += "Completed BasicService Constructor\n"; Debug.Log ("Completed BasicService Constructor"); } public bool KeepRunning { get { return true; } } public bool Connected { get { return sJoinComplete; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Analysis { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// The Azure Analysis Services Web API provides a RESTful set of web /// services that enables users to create, retrieve, update, and delete /// Analysis Services servers /// </summary> public partial class AnalysisServicesManagementClient : ServiceClient<AnalysisServicesManagementClient>, IAnalysisServicesManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// A unique identifier for a Microsoft Azure subscription. The subscription ID /// forms part of the URI for every service call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The client API version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IServersOperations. /// </summary> public virtual IServersOperations Servers { get; private set; } /// <summary> /// Initializes a new instance of the AnalysisServicesManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AnalysisServicesManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AnalysisServicesManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AnalysisServicesManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AnalysisServicesManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AnalysisServicesManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AnalysisServicesManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AnalysisServicesManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AnalysisServicesManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AnalysisServicesManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AnalysisServicesManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AnalysisServicesManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AnalysisServicesManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AnalysisServicesManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AnalysisServicesManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AnalysisServicesManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Servers = new ServersOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2016-05-16"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// corewlan.cs: bindings for CoreWLAN // // Author: // Ashok Gelal // // 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 MonoMac.Foundation; using MonoMac.CoreFoundation; using System; namespace MonoMac.CoreWlan { [BaseType (typeof (NSObject))] interface CW8021XProfile { [Export ("userDefinedName")] string UserDefinedName { get; set; } [Export ("ssid")] string Ssid { get; set; } [Export ("username")] string Username { get; set; } [Export ("password")] string Password { get; set; } [Export ("alwaysPromptForPassword")] bool AlwaysPromptForPassword{ get; set; } [Static] [Export ("profile")] CW8021XProfile Profile { get; } [Export ("isEqualToProfile:")] bool IsEqualToProfile (CW8021XProfile profile); [Static] [Export ("allUser8021XProfiles")] CW8021XProfile[] AllUser8021XProfiles { get; } } [BaseType (typeof (NSObject))] interface CWConfiguration { [Export ("rememberedNetworks")] NSSet RememberedNetworks { get; set; } [Export ("preferredNetworks")] CWWirelessProfile[] PreferredNetworks { get; set; } [Export ("alwaysRememberNetworks")] bool AlwaysRememberNetworks{ get; set; } [Export ("disconnectOnLogout")] bool DisconnectOnLogout{ get; set; } [Export ("requireAdminForNetworkChange")] bool RequireAdminForNetworkChange { get; set; } [Export ("requireAdminForPowerChange")] bool RequireAdminForPowerChange { get; set; } [Export ("requireAdminForIBSSCreation")] bool RequireAdminForIBSSCreation { get; set; } [Export ("isEqualToConfiguration:")] bool IsEqualToConfiguration (CWConfiguration configuration); } [BaseType (typeof (NSObject))] interface CWInterface { [Export ("supportsWoW")] bool SupportsWow { get; } [Export ("supportsWEP")] bool SupportsWep { get; } [Export ("supportsAES_CCM")] bool SupportsAesCcm { get; } [Export ("supportsIBSS")] bool SupportsIbss { get; } [Export ("supportsTKIP")] bool SupportsTkip { get; } [Export ("supportsPMGT")] bool SupportsPmgt { get; } [Export ("supportsHostAP")] bool SupportsHostAP { get; } [Export ("supportsMonitorMode")] bool SupportsMonitorMode { get; } [Export ("supportsWPA")] bool SupportsWpa { get; } [Export ("supportsWPA2")] bool SupportsWpa2 { get; } [Export ("supportsWME")] bool SupportsWme { get; } [Export ("supportsShortGI40MHz")] bool SupportsShortGI40MHz { get; } [Export ("supportsShortGI20MHz")] bool SupportsShortGI20MHz { get; } [Export ("supportsTSN")] bool SupportsTsn { get; } [Export ("power")] bool Power { get; } [Export ("powerSave")] bool PowerSave { get; } [Export ("name")] string Name { get; } [Export ("supportedChannels")] NSNumber[] SupportedChannels { get; } [Export ("supportedPHYModes")] NSNumber[] SupportedPhyModes { get; } [Export ("channel")] NSNumber Channel { get; } [Export ("phyMode")] NSNumber PhyMode { get; } [Export ("ssid")] string Ssid { get; } [Export ("bssid")] string Bssid { get; } [Export ("bssidData")] NSData BssidData { get; } [Export ("rssi")] NSNumber Rssi { get; } [Export ("noise")] NSNumber Noise { get; } [Export ("txRate")] NSNumber TxRate { get; } [Export ("securityMode")] NSNumber SecurityMode { get; } [Export ("interfaceState")] NSNumber InterfaceState { get; } [Export ("countryCode")] string CountryCode { get; } [Export ("opMode")] NSNumber OpMode { get; } [Export ("txPower")] NSNumber TxPower { get; } [Export ("configuration")] CWConfiguration Configuration { get; } [Static] [Export ("supportedInterfaces")] string[] SupportedInterfaces { get; } [Static] [Export ("interface")] CWInterface MainInterface { get; } [Static] [Export ("interfaceWithName:")] CWInterface FromName (string name); [Export ("initWithInterfaceName:")] IntPtr Constructor (string name); [Export ("isEqualToInterface:")] bool IsEqualToInterface (CWInterface intface); [Export ("setPower:error:")] bool TrySetPower (bool power, out NSError error); [Export ("setChannel:error:")] bool TrySetChannel (uint channel, out NSError error); [Export ("scanForNetworksWithParameters:error:")] CWNetwork[] TryScanForNetworksWithParameters([NullAllowed] NSDictionary parameters, out NSError error); [Export ("associateToNetwork:parameters:error:")] bool TryAssociateToNetwork(CWNetwork network, [NullAllowed] NSDictionary parameters, out NSError error); [Export ("disassociate")] void Disassociate (); [Export ("enableIBSSWithParameters:error:")] bool TryEnableIBSSWithParameters([NullAllowed] NSDictionary parameters, out NSError error); [Export ("commitConfiguration:error:")] bool TryCommitConfiguration (CWConfiguration config, out NSError error); } [BaseType (typeof (NSObject))] interface CWWirelessProfile { [Export ("ssid")] string Ssid { get; set; } [Export ("securityMode")] NSNumber SecurityMode { get; set; } [Export ("passphrase")] string Passphrase { get; set; } [Export ("user8021XProfile")] CW8021XProfile User8021XProfile { get; set; } [Export ("isEqualToProfile:")] bool IsEqualToProfile (CWWirelessProfile profile); } [BaseType (typeof (NSObject))] interface CWNetwork { [Export ("ssid")] string Ssid { get; } [Export ("bssid")] string Bssid { get; } [Export ("bssidData")] NSData BssidData { get; } [Export ("securityMode")] NSNumber SecurityMode { get; } [Export ("phyMode")] NSNumber PhyMode { get; } [Export ("channel")] NSNumber Channel { get; } [Export ("rssi")] NSNumber Rssi { get; } [Export ("noise")] NSNumber Noise { get; } [Export ("ieData")] NSData IeData { get; } [Export ("isIBSS")] bool IsIBSS { get; } [Export ("wirelessProfile")] CWWirelessProfile WirelessProfile { get; } [Export ("isEqualToNetwork:")] bool IsEqualToNetwork (CWNetwork network); } }
using System; using System.IO; using System.Runtime.InteropServices; namespace Arika { public class ArikaLoader { public interface DllLoadUtils { IntPtr LoadLibrary(string fileName); void FreeLibrary(IntPtr handle); IntPtr GetProcAddress(IntPtr dllHandle, string name); } public static T LoadFunction<T>(string name, DllLoadUtils utils, IntPtr handle) where T : class { IntPtr address = utils.GetProcAddress(handle, name); System.Delegate fn_ptr = Marshal.GetDelegateForFunctionPointer(address, typeof(T)); return fn_ptr as T; } /* internal delegate void MyCrossplatformBar(int a, int b); DllLoadUtils dllLoadUtils = IsLinux() ? (DllLoadUtils) new DllLoadUtilsLinux() : new DllLoadUtilsWindows(); string libraryName; if (IsLinux()) { libraryName = IntPtr.Size == 8 ? "mylib64.so" : "mylib32.so"; } else { libraryName = IntPtr.Size == 8 ? "mylib64.dll" : "mylib32.dll"; } var dllHandle = dllLoadUtils.LoadLibrary(libraryName); var functionHandle = dllLoadUtils.GetProcAddress(dllHandle, "MyCrossplatformBar"); var method = (MyCrossplatformBar) Marshal.GetDelegateForFunctionPointer( functionHandle, typeof (MyCrossplatformBar)); method(10, 15); } */ public static bool LoadLibrary(string name) { DllLoadUtils dllLoadUtils = null; switch (RunningPlatform()) { case PlatformID.MacOSX : dllLoadUtils = (DllLoadUtils) new DllLoadUtilsMac(); break; case PlatformID.Unix : dllLoadUtils = (DllLoadUtils) new DllLoadUtilsUnix(); break; default : dllLoadUtils = (DllLoadUtils) new DllLoadUtilsWindows(); break; } IntPtr dllHandle; dllHandle = dllLoadUtils.LoadLibrary(name); if (dllHandle == IntPtr.Zero) { Console.WriteLine("Unable to load dll {0}", name); return false; } ArikaRaw.ResolveSymbols(dllLoadUtils, dllHandle); return true; } public static PlatformID RunningPlatform() { switch (Environment.OSVersion.Platform) { case PlatformID.Unix: // Well, there are chances MacOSX is reported as Unix instead of MacOSX. // Instead of platform check, we'll do a feature checks (Mac specific root folders) if (Directory.Exists("/Applications") & Directory.Exists("/System") & Directory.Exists("/Users") & Directory.Exists("/Volumes")) return PlatformID.MacOSX; else return PlatformID.Unix; case PlatformID.MacOSX: return PlatformID.MacOSX; default: return PlatformID.Win32NT; } } // Windows version private class DllLoadUtilsWindows : DllLoadUtils { void DllLoadUtils.FreeLibrary(IntPtr handle) { FreeLibrary(handle); } IntPtr DllLoadUtils.GetProcAddress(IntPtr dllHandle, string name) { return GetProcAddress(dllHandle, name); } IntPtr DllLoadUtils.LoadLibrary(string fileName) { return LoadLibrary(fileName); } [DllImport("kernel32")] private static extern IntPtr LoadLibrary(string fileName); [DllImport("kernel32.dll")] private static extern int FreeLibrary(IntPtr handle); [DllImport("kernel32.dll")] private static extern IntPtr GetProcAddress(IntPtr handle, string procedureName); } // *Nix version private class DllLoadUtilsUnix : DllLoadUtils { public IntPtr LoadLibrary(string fileName) { return dlopen(fileName, RTLD_NOW); } public void FreeLibrary(IntPtr handle) { dlclose(handle); } public IntPtr GetProcAddress(IntPtr dllHandle, string name) { // clear previous errors if any dlerror(); var res = dlsym(dllHandle, name); var errPtr = dlerror(); if (errPtr != IntPtr.Zero) throw new Exception("dlsym: " + Marshal.PtrToStringAnsi(errPtr)); return res; } const int RTLD_NOW = 2; [DllImport("libdl.so")] private static extern IntPtr dlopen(String fileName, int flags); [DllImport("libdl.so")] private static extern IntPtr dlsym(IntPtr handle, String symbol); [DllImport("libdl.so")] private static extern int dlclose(IntPtr handle); [DllImport("libdl.so")] private static extern IntPtr dlerror(); } // Mac version private class DllLoadUtilsMac : DllLoadUtils { public IntPtr LoadLibrary(string fileName) { return dlopen(fileName, RTLD_NOW); } public void FreeLibrary(IntPtr handle) { dlclose(handle); } public IntPtr GetProcAddress(IntPtr dllHandle, string name) { // clear previous errors if any dlerror(); var res = dlsym(dllHandle, name); var errPtr = dlerror(); if (errPtr != IntPtr.Zero) throw new Exception("dlsym: " + Marshal.PtrToStringAnsi(errPtr)); return res; } const int RTLD_NOW = 2; [DllImport("libc.dylib")] private static extern IntPtr dlopen(String fileName, int flags); [DllImport("libc.dylib")] private static extern IntPtr dlsym(IntPtr handle, String symbol); [DllImport("libc.dylib")] private static extern int dlclose(IntPtr handle); [DllImport("libc.dylib")] private static extern IntPtr dlerror(); } } }
using System.IO; using Newtonsoft.Json; namespace Tests.Go2.Architecture.Domain.DomainModel { using global::Go2.Architecture.Domain.DomainModel; using NUnit.Framework; using global::Go2.Architecture.Testing.NUnit; using global::Go2.Architecture.Testing.NUnit.Helpers; [TestFixture] public class EntityTests { private MockEntityObjectWithDefaultId _diffObj; private MockEntityObjectWithSetId _diffObjWithId; private MockEntityObjectWithDefaultId _obj; private MockEntityObjectWithSetId _objWithId; private MockEntityObjectWithDefaultId _sameObj; private MockEntityObjectWithSetId _sameObjWithId; [Test] public void CanCompareDomainObjectsWithAllPropertiesBeingPartOfDomainSignature() { var object1 = new ObjectWithAllDomainSignatureProperty(); var object2 = new ObjectWithAllDomainSignatureProperty(); Assert.That(object1, Is.EqualTo(object2)); object1.Age = 13; object2.Age = 13; object1.Name = "Foo"; object2.Name = "Foo"; Assert.That(object1, Is.EqualTo(object2)); object1.Name = "Bar"; Assert.That(object1, Is.Not.EqualTo(object2)); object1.Name = null; Assert.That(object1, Is.Not.EqualTo(object2)); object2.Name = null; Assert.That(object1, Is.EqualTo(object2)); } [Test] public void CanCompareDomainObjectsWithOnlySomePropertiesBeingPartOfDomainSignature() { var object1 = new ObjectWithOneDomainSignatureProperty(); var object2 = new ObjectWithOneDomainSignatureProperty(); Assert.That(object1, Is.EqualTo(object2)); object1.Age = 13; object2.Age = 13; // Name property isn't included in comparison object1.Name = "Foo"; object2.Name = "Bar"; Assert.That(object1, Is.EqualTo(object2)); object1.Age = 14; Assert.That(object1, Is.Not.EqualTo(object2)); } [Test] public void CanCompareEntitiesWithAssignedIds() { var object1 = new ObjectWithAssignedId { Name = "Acme" }; var object2 = new ObjectWithAssignedId { Name = "Anvil" }; Assert.That(object1, Is.Not.EqualTo(null)); Assert.That(object1, Is.Not.EqualTo(object2)); object1.SetAssignedIdTo("AAAAA"); object2.SetAssignedIdTo("AAAAA"); // Even though the "business value signatures" are different, the persistent Ids // were the same. Call me crazy, but I put that much trust into persisted Ids. Assert.That(object1, Is.EqualTo(object2)); var object3 = new ObjectWithAssignedId { Name = "Acme" }; // Since object1 has an Id but object3 doesn't, they won't be equal // even though their signatures are the same Assert.That(object1, Is.Not.EqualTo(object3)); var object4 = new ObjectWithAssignedId { Name = "Acme" }; // object3 and object4 are both transient and share the same signature Assert.That(object3, Is.EqualTo(object4)); } [Test] public void CanCompareEntitys() { var object1 = new ObjectWithIntId { Name = "Acme" }; var object2 = new ObjectWithIntId { Name = "Anvil" }; Assert.That(object1, Is.Not.EqualTo(null)); Assert.That(object1, Is.Not.EqualTo(object2)); EntityIdSetter.SetIdOf(object1, 10); EntityIdSetter.SetIdOf(object2, 10); // Even though the "business value signatures" are different, the persistent Ids // were the same. Call me crazy, but I put that much trust into persisted Ids. Assert.That(object1, Is.EqualTo(object2)); Assert.That(object1.GetHashCode(), Is.EqualTo(object2.GetHashCode())); var object3 = new ObjectWithIntId { Name = "Acme" }; // Since object1 has an Id but object3 doesn't, they won't be equal // even though their signatures are the same Assert.That(object1, Is.Not.EqualTo(object3)); var object4 = new ObjectWithIntId { Name = "Acme" }; // object3 and object4 are both transient and share the same signature Assert.That(object3, Is.EqualTo(object4)); } [Test] public void CanCompareInheritedDomainObjects() { var object1 = new InheritedObjectWithExtraDomainSignatureProperty(); var object2 = new InheritedObjectWithExtraDomainSignatureProperty(); Assert.That(object1, Is.EqualTo(object2)); object1.Age = 13; object1.IsLiving = true; object2.Age = 13; object2.IsLiving = true; // Address property isn't included in comparison object1.Address = "123 Oak Ln."; object2.Address = "Nightmare on Elm St."; Assert.That(object1, Is.EqualTo(object2)); object1.IsLiving = false; Assert.That(object1, Is.Not.EqualTo(object2)); } [Test] public void CanCompareObjectsWithComplexProperties() { var object1 = new ObjectWithComplexProperties(); var object2 = new ObjectWithComplexProperties(); Assert.AreEqual(object1, object2); object1.Address = new AddressBeingDomainSignatureComparble { Address1 = "123 Smith Ln.", Address2 = "Suite 201", ZipCode = 12345 }; Assert.AreNotEqual(object1, object2); // Set the address of the 2nd to be different to the address of the first object2.Address = new AddressBeingDomainSignatureComparble { Address1 = "123 Smith Ln.", // Address2 isn't marked as being part of the domain signature; // therefore, it WON'T be used in the equality comparison Address2 = "Suite 402", ZipCode = 98765 }; Assert.AreNotEqual(object1, object2); // Set the address of the 2nd to be the same as the first object2.Address.ZipCode = 12345; Assert.AreEqual(object1, object2); object1.Phone = new PhoneBeingNotDomainObject { PhoneNumber = "(555) 555-5555" }; Assert.AreNotEqual(object1, object2); // IMPORTANT: Note that even though the phone number below has the same value as the // phone number on object1, they're not domain signature comparable; therefore, the // "out of the box" equality will be used which shows them as being different objects. object2.Phone = new PhoneBeingNotDomainObject { PhoneNumber = "(555) 555-5555" }; Assert.AreNotEqual(object1, object2); // Observe as we replace the object1.Phone with an object that isn't domain-signature // comparable, but DOES have an overridden Equals which will return true if the phone // number properties are equal. object1.Phone = new PhoneBeingNotDomainObjectButWithOverriddenEquals { PhoneNumber = "(555) 555-5555" }; Assert.AreEqual(object1, object2); } [Test] public void CanHaveEntityWithoutDomainSignatureProperties() { var invalidEntity = new ObjectWithNoDomainSignatureProperties(); invalidEntity.GetSignatureProperties(); } [Test] public void CannotEquateObjectsWithSameIdButDifferentTypes() { var object1Type = new Object1(); var object2Type = new Object2(); EntityIdSetter.SetIdOf(object1Type, 1); EntityIdSetter.SetIdOf(object2Type, 1); Assert.That(object1Type, Is.Not.EqualTo(object2Type)); } [Test] public void DoDefaultEntityEqualsOverrideWorkWhenIdIsAssigned() { this._obj.SetAssignedIdTo(1); this._diffObj.SetAssignedIdTo(1); Assert.That(this._obj.Equals(this._diffObj)); } [Test] public void DoEntityEqualsOverrideWorkWhenIdIsAssigned() { this._objWithId.SetAssignedIdTo("1"); this._diffObjWithId.SetAssignedIdTo("1"); Assert.That(this._objWithId.Equals(this._diffObjWithId)); } [Test] public void DoEqualDefaultEntitiesWithMatchingIdsGenerateDifferentHashCodes() { Assert.That(!this._obj.GetHashCode().Equals(this._diffObj.GetHashCode())); } [Test] public void DoEqualDefaultEntitiesWithNoIdsGenerateSameHashCodes() { Assert.That(this._obj.GetHashCode().Equals(this._sameObj.GetHashCode())); } [Test] public void DoEqualEntitiesWithMatchingIdsGenerateDifferentHashCodes() { Assert.That(!this._objWithId.GetHashCode().Equals(this._diffObjWithId.GetHashCode())); } [Test] public void DoEqualEntitiesWithNoIdsGenerateSameHashCodes() { Assert.That(this._objWithId.GetHashCode().Equals(this._sameObjWithId.GetHashCode())); } [Test] public void DoesDefaultEntityEqualsOverrideWorkWhenNoIdIsAssigned() { Assert.That(this._obj.Equals(this._sameObj)); Assert.That(!this._obj.Equals(this._diffObj)); Assert.That(!this._obj.Equals(new MockEntityObjectWithDefaultId())); } [Test] public void DoesEntityEqualsOverrideWorkWhenNoIdIsAssigned() { Assert.That(this._objWithId.Equals(this._sameObjWithId)); Assert.That(!this._objWithId.Equals(this._diffObjWithId)); Assert.That(!this._objWithId.Equals(new MockEntityObjectWithSetId())); } [Test] public void Entity_with_domain_signature_preserves_hashcode_when_transitioning_from_transient_to_persistent() { var sut = new ObjectWithOneDomainSignatureProperty { Age = 1 }; Assert.That(sut.IsTransient()); var hashcodeWhenTransient = sut.GetHashCode(); sut.SetIdTo(1); Assert.That(sut.IsTransient(), Is.False); Assert.That(sut.GetHashCode(), Is.EqualTo(hashcodeWhenTransient)); } [Test] public void Entity_with_no_signature_properties_preserves_hashcode_when_transitioning_from_transient_to_persistent() { var sut = new ObjectWithNoDomainSignatureProperties(); Assert.That(sut.IsTransient()); var hashcodeWhenTransient = sut.GetHashCode(); sut.SetIdTo(1); Assert.That(sut.IsTransient(), Is.False); Assert.That(sut.GetHashCode(), Is.EqualTo(hashcodeWhenTransient)); } [Test] public void KeepsConsistentHashThroughLifetimeOfPersistentObject() { var object1 = new ObjectWithOneDomainSignatureProperty(); EntityIdSetter.SetIdOf(object1, 1); var initialHash = object1.GetHashCode(); object1.Age = 13; object1.Name = "Foo"; Assert.AreEqual(initialHash, object1.GetHashCode()); object1.Age = 14; Assert.AreEqual(initialHash, object1.GetHashCode()); } [Test] public void KeepsConsistentHashThroughLifetimeOfTransientObject() { var object1 = new ObjectWithOneDomainSignatureProperty(); var initialHash = object1.GetHashCode(); object1.Age = 13; object1.Name = "Foo"; Assert.AreEqual(initialHash, object1.GetHashCode()); object1.Age = 14; Assert.AreEqual(initialHash, object1.GetHashCode()); } [Test] public void EntitySerializesAsJsonProperly() { var object1 = new ObjectWithOneDomainSignatureProperty(); object1.SetIdTo(999); object1.Age = 13; object1.Name = "Foo"; var jsonSerializer = new JsonSerializer(); string jsonString; using (var stringWriter = new StringWriter()) { jsonSerializer.Serialize(stringWriter, object1); jsonString = stringWriter.ToString(); } using (var stringReader = new StringReader(jsonString)) using (var jsonReader = new JsonTextReader(stringReader)) { var deserialized = jsonSerializer.Deserialize<ObjectWithOneDomainSignatureProperty>(jsonReader); Assert.IsNotNull(deserialized); Assert.AreEqual(999, deserialized.Id); Assert.AreEqual(13, deserialized.Age); Assert.AreEqual("Foo", deserialized.Name); } } [SetUp] public void Setup() { this._obj = new MockEntityObjectWithDefaultId { FirstName = "FName1", LastName = "LName1", Email = "testus...@mail.com" }; this._sameObj = new MockEntityObjectWithDefaultId { FirstName = "FName1", LastName = "LName1", Email = "testus...@mail.com" }; this._diffObj = new MockEntityObjectWithDefaultId { FirstName = "FName2", LastName = "LName2", Email = "testuse...@mail.com" }; this._objWithId = new MockEntityObjectWithSetId { FirstName = "FName1", LastName = "LName1", Email = "testus...@mail.com" }; this._sameObjWithId = new MockEntityObjectWithSetId { FirstName = "FName1", LastName = "LName1", Email = "testus...@mail.com" }; this._diffObjWithId = new MockEntityObjectWithSetId { FirstName = "FName2", LastName = "LName2", Email = "testuse...@mail.com" }; } [TearDown] public void Teardown() { this._obj = null; this._sameObj = null; this._diffObj = null; } [Test] public void Transient_entity_with_domain_signature_preserves_hashcode_temporarily_when_its_domain_signature_changes() { var sut = new ObjectWithOneDomainSignatureProperty { Age = 1 }; var initialHashcode = sut.GetHashCode(); sut.Age = 2; Assert.That(sut.GetHashCode(), Is.EqualTo(initialHashcode)); } [Test] public void Transient_entity_with_domain_signature_should_return_consistent_hashcode() { var sut = new ObjectWithOneDomainSignatureProperty { Age = 1 }; Assert.That(sut.GetHashCode(), Is.EqualTo(sut.GetHashCode())); } [Test] public void Transient_entity_without_domain_signature_should_return_consistent_hashcode() { var sut = new ObjectWithNoDomainSignatureProperties(); Assert.That(sut.GetHashCode(), Is.EqualTo(sut.GetHashCode())); } [Test] public void Two_persistent_entities_with_different_domain_signature_and_equal_ids_generate_equal_hashcodes() { var sut1 = new ObjectWithOneDomainSignatureProperty { Age = 1 }.SetIdTo(1); var sut2 = new ObjectWithOneDomainSignatureProperty { Age = 2 }.SetIdTo(1); Assert.That(sut1.GetHashCode(), Is.EqualTo(sut2.GetHashCode())); } [Test] public void Two_persistent_entities_with_equal_domain_signature_and_different_ids_generate_different_hashcodes() { var sut1 = new ObjectWithOneDomainSignatureProperty { Age = 1 }.SetIdTo(1); var sut2 = new ObjectWithOneDomainSignatureProperty { Age = 1 }.SetIdTo(2); Assert.That(sut1.GetHashCode(), Is.Not.EqualTo(sut2.GetHashCode())); } [Test] public void Two_persistent_entities_with_no_signature_properties_and_different_ids_generate_different_hashcodes( ) { var sut1 = new ObjectWithNoDomainSignatureProperties().SetIdTo(1); var sut2 = new ObjectWithNoDomainSignatureProperties().SetIdTo(2); Assert.That(sut1.GetHashCode(), Is.Not.EqualTo(sut2.GetHashCode())); } [Test] public void Two_persistent_entities_with_no_signature_properties_and_equal_ids_generate_equal_hashcodes() { var sut1 = new ObjectWithNoDomainSignatureProperties().SetIdTo(1); var sut2 = new ObjectWithNoDomainSignatureProperties().SetIdTo(1); Assert.That(sut1.GetHashCode(), Is.EqualTo(sut2.GetHashCode())); } [Test] public void Two_transient_entities_with_different_values_of_domain_signature_generate_different_hashcodes() { var sut1 = new ObjectWithOneDomainSignatureProperty { Age = 1 }; var sut2 = new ObjectWithOneDomainSignatureProperty { Age = 2 }; Assert.That(sut1.GetHashCode(), Is.Not.EqualTo(sut2.GetHashCode())); } [Test] public void Two_transient_entities_without_signature_properties_generate_different_hashcodes() { var sut1 = new ObjectWithNoDomainSignatureProperties(); var sut2 = new ObjectWithNoDomainSignatureProperties(); Assert.That(sut1.GetHashCode(), Is.Not.EqualTo(sut2.GetHashCode())); } [Test] public void Two_transient_entitites_with_equal_values_of_domain_signature_generate_equal_hashcodes() { var sut1 = new ObjectWithOneDomainSignatureProperty { Age = 1 }; var sut2 = new ObjectWithOneDomainSignatureProperty { Age = 1 }; Assert.That(sut1.GetHashCode(), Is.EqualTo(sut2.GetHashCode())); } [Test] public void WontGetConfusedWithOutsideCases() { var object1 = new ObjectWithIdenticalTypedProperties(); var object2 = new ObjectWithIdenticalTypedProperties(); object1.Address = "Henry"; object1.Name = "123 Lane St."; object2.Address = "123 Lane St."; object2.Name = "Henry"; Assert.That(object1, Is.Not.EqualTo(object2)); object1.Address = "Henry"; object1.Name = null; object2.Address = "Henri"; object2.Name = null; Assert.That(object1, Is.Not.EqualTo(object2)); object1.Address = null; object1.Name = "Supercalifragilisticexpialidocious"; object2.Address = null; object2.Name = "Supercalifragilisticexpialidocious"; Assert.That(object1, Is.EqualTo(object2)); object1.Name = "Supercalifragilisticexpialidocious"; object2.Name = "Supercalifragilisticexpialidociouz"; Assert.That(object1, Is.Not.EqualTo(object2)); } [Test] public void CanSerializeEntityToJson() { var object1 = new Contact() { EmailAddress = "serialize@this.net" }; string result = JsonConvert.SerializeObject(object1); result.ShouldContain("serialize@this.net"); } public class MockEntityObjectBase<T> : EntityWithTypedId<T> { public string Email { get; set; } [DomainSignature] public string FirstName { get; set; } [DomainSignature] public string LastName { get; set; } } public class ObjectWithOneDomainSignatureProperty : Entity { [DomainSignature] public int Age { get; set; } public string Name { get; set; } } private class AddressBeingDomainSignatureComparble : Entity { [DomainSignature] public string Address1 { get; set; } public string Address2 { get; set; } [DomainSignature] public int ZipCode { get; set; } } private class InheritedObjectWithExtraDomainSignatureProperty : ObjectWithOneDomainSignatureProperty { public string Address { get; set; } [DomainSignature] public bool IsLiving { get; set; } } private class MockEntityObjectBase : MockEntityObjectBase<int> { } private class MockEntityObjectWithDefaultId : MockEntityObjectBase, IHasAssignedId<int> { public void SetAssignedIdTo(int assignedId) { this.Id = assignedId; } } private class MockEntityObjectWithSetId : MockEntityObjectBase<string>, IHasAssignedId<string> { public void SetAssignedIdTo(string assignedId) { this.Id = assignedId; } } private class Object1 : Entity { } private class Object2 : Entity { } private class ObjectWithAllDomainSignatureProperty : Entity { [DomainSignature] public int Age { get; set; } [DomainSignature] public string Name { get; set; } } private class ObjectWithAssignedId : EntityWithTypedId<string>, IHasAssignedId<string> { [DomainSignature] public string Name { get; set; } public void SetAssignedIdTo(string assignedId) { this.Id = assignedId; } } private class ObjectWithComplexProperties : Entity { [DomainSignature] public AddressBeingDomainSignatureComparble Address { get; set; } [DomainSignature] public string Name { get; set; } [DomainSignature] public PhoneBeingNotDomainObject Phone { get; set; } } private class ObjectWithIdenticalTypedProperties : Entity { [DomainSignature] public string Address { get; set; } [DomainSignature] public string Name { get; set; } } private class ObjectWithIntId : Entity { [DomainSignature] public string Name { get; set; } } /// <summary> /// This is a nonsense object; i.e., it doesn't make sense to have /// an entity without a domain signature. /// </summary> private class ObjectWithNoDomainSignatureProperties : Entity { public int Age { get; set; } public string Name { get; set; } } private class PhoneBeingNotDomainObject { public string Extension { get; set; } public string PhoneNumber { get; set; } } private class PhoneBeingNotDomainObjectButWithOverriddenEquals : PhoneBeingNotDomainObject { public override bool Equals(object obj) { var compareTo = obj as PhoneBeingNotDomainObject; return compareTo != null && this.PhoneNumber.Equals(compareTo.PhoneNumber); } public override int GetHashCode() { return base.GetHashCode(); } } private class Contact : Entity { public virtual string EmailAddress { get; set; } } } }
/// Refly License /// /// Copyright (c) 2004 Jonathan de Halleux, http://www.dotnetwiki.org /// /// This software is provided 'as-is', without any express or implied warranty. /// In no event will the authors be held liable for any damages arising from /// the use of this software. /// /// Permission is granted to anyone to use this software for any purpose, /// including commercial applications, and to alter it and redistribute it /// freely, subject to the following restrictions: /// /// 1. The origin of this software must not be misrepresented; /// you must not claim that you wrote the original software. /// If you use this software in a product, an acknowledgment in the product /// documentation would be appreciated but is not required. /// /// 2. Altered source versions must be plainly marked as such, /// and must not be misrepresented as being the original software. /// ///3. This notice may not be removed or altered from any source distribution. using System; using System.CodeDom; namespace Refly.CodeDom { using Refly.CodeDom.Expressions; using Refly.CodeDom.Collections; using Refly.CodeDom.Statements; /// <summary> /// Helper containing static methods for creating statements. /// </summary> public sealed class Stm { #region Constructors private Stm(){} #endregion /// <summary> /// Creates an assign statement: <c>left = right</c> /// </summary> /// <param name="left"> /// Left <see cref="Expression"/> instance</param> /// <param name="right"> /// Right <see cref="Expression"/> instance /// </param> /// <returns> /// A <see cref="AssignStatement"/> instance. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="left"/> or <paramref name="right"/> /// is a null reference (Nothing in Visual Basic) /// </exception> static public AssignStatement Assign(Expression left, Expression right) { if (left==null) throw new ArgumentNullException("left"); if (right==null) throw new ArgumentNullException("right"); return new AssignStatement(left,right); } static public ExpressionStatement ToStm(Expression expr) { if (expr==null) throw new ArgumentNullException("expr"); return new ExpressionStatement(expr); } static public MethodReturnStatement Return(Expression expr) { if (expr==null) throw new ArgumentNullException("expr"); return new MethodReturnStatement(expr); } static public MethodReturnStatement Return() { return new MethodReturnStatement(); } static public NativeStatement Comment(string comment) { if (comment==null) throw new ArgumentNullException("comment"); return new NativeStatement( new CodeCommentStatement(comment,false) ); } static public ConditionStatement If(Expression condition, params Statement[] trueStatements) { if (condition==null) throw new ArgumentNullException("condition"); return new ConditionStatement(condition,trueStatements); } static public ConditionStatement IfIdentity(Expression left, Expression right, params Statement[] trueStatements) { if (left==null) throw new ArgumentNullException("left"); if (right==null) throw new ArgumentNullException("right"); return If( left.Identity(right), trueStatements ); } static public ConditionStatement ThrowIfNull(Expression condition, Expression toThrow) { if (condition==null) throw new ArgumentNullException("condition"); if (toThrow==null) throw new ArgumentNullException("toThrow"); return IfNull(condition, Stm.Throw(toThrow) ); } static public ConditionStatement ThrowIfNull(Expression condition, string message) { if (condition==null) throw new ArgumentNullException("condition"); if (message==null) throw new ArgumentNullException("message"); return ThrowIfNull( condition, Expr.New(typeof(NullReferenceException),Expr.Prim(message)) ); } static public ConditionStatement ThrowIfNull(ParameterDeclaration param) { if (param==null) throw new ArgumentNullException("param"); return ThrowIfNull( Expr.Arg(param), Expr.New(typeof(ArgumentNullException),Expr.Prim(param.Name)) ); } static public ConditionStatement IfNotIdentity(Expression left, Expression right, params Statement[] trueStatements) { if (left==null) throw new ArgumentNullException("left"); if (right==null) throw new ArgumentNullException("right"); return If( left.NotIdentity(right), trueStatements ); } static public ConditionStatement IfNull(Expression left,params Statement[] trueStatements) { if (left==null) throw new ArgumentNullException("left"); return IfIdentity( left,Expr.Null, trueStatements ); } static public ConditionStatement IfNotNull(Expression left,params Statement[] trueStatements) { if (left==null) throw new ArgumentNullException("left"); return IfNotIdentity( left,Expr.Null, trueStatements ); } static public NativeStatement Snippet(string snippet) { if (snippet==null) throw new ArgumentNullException("snippet"); return new NativeStatement( new CodeSnippetStatement(snippet) ); } static public ThrowExceptionStatement Throw(Expression toThrow) { if (toThrow==null) throw new ArgumentNullException("toThrow"); return new ThrowExceptionStatement(toThrow); } static public ThrowExceptionStatement Throw(String t, params Expression[] args) { return Throw(new StringTypeDeclaration(t),args); } static public ThrowExceptionStatement Throw(Type t, params Expression[] args) { return Throw(new TypeTypeDeclaration(t),args); } static public ThrowExceptionStatement Throw(ITypeDeclaration t, params Expression[] args) { return new ThrowExceptionStatement( Expr.New(t,args) ); } static public TryCatchFinallyStatement Try() { return new TryCatchFinallyStatement(); } static public CatchClause Catch(ParameterDeclaration localParam) { return new CatchClause(localParam); } static public CatchClause Catch(String t, string name) { return Catch(new StringTypeDeclaration(t),name); } static public CatchClause Catch(Type t, string name) { return Catch(new TypeTypeDeclaration(t),name); } static public CatchClause Catch(ITypeDeclaration t, string name) { return Catch(new ParameterDeclaration(t,name,false)); } static public TryCatchFinallyStatement Guard(Type expectedExceptionType) { TryCatchFinallyStatement try_ = Try(); try_.CatchClauses.Add( Catch(expectedExceptionType,"") ); return try_; } static public VariableDeclarationStatement Var(String type, string name) { return Var(new StringTypeDeclaration(type),name); } static public VariableDeclarationStatement Var(Type type, string name) { return Var(new TypeTypeDeclaration(type),name); } static public VariableDeclarationStatement Var(ITypeDeclaration type, string name) { return new VariableDeclarationStatement(type,name); } static public VariableDeclarationStatement Var(String type, string name,Expression initExpression) { return Var(new StringTypeDeclaration(type),name,initExpression); } static public VariableDeclarationStatement Var(Type type, string name,Expression initExpression) { return Var(new TypeTypeDeclaration(type),name,initExpression); } static public VariableDeclarationStatement Var(ITypeDeclaration type, string name,Expression initExpression) { VariableDeclarationStatement var = Var(type,name); var.InitExpression = initExpression; return var; } static public IterationStatement For( Statement initStatement, Expression testExpression, Statement incrementStatement ) { return new IterationStatement(initStatement,testExpression,incrementStatement); } static public IterationStatement While( Expression testExpression ) { return new IterationStatement( new SnippetStatement(""), testExpression, new SnippetStatement("") ); } public static ForEachStatement ForEach( String localType, string localName, Expression collection, bool enumeratorDisposable ) { return ForEach(new StringTypeDeclaration(localType),localName,collection,enumeratorDisposable); } public static ForEachStatement ForEach( Type localType, string localName, Expression collection, bool enumeratorDisposable ) { return ForEach(new TypeTypeDeclaration(localType),localName,collection,enumeratorDisposable); } public static ForEachStatement ForEach( ITypeDeclaration localType, string localName, Expression collection, bool enumeratorDisposable ) { return new ForEachStatement(localType,localName,collection ,enumeratorDisposable ); } public static AttachRemoveEventStatement Attach( EventReferenceExpression eventRef, Expression listener) { return new AttachRemoveEventStatement(eventRef,listener,true); } public static AttachRemoveEventStatement Remove( EventReferenceExpression eventRef, Expression listener) { return new AttachRemoveEventStatement(eventRef,listener,false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System; using System.Diagnostics.Contracts; namespace System.Text { // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // internal class DecoderNLS : Decoder { // Remember our encoding protected Encoding m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_bytesUsed; internal DecoderNLS(Encoding encoding) { this.m_encoding = encoding; this.m_fallback = this.m_encoding.DecoderFallback; this.Reset(); } // This is used by our child deserializers internal DecoderNLS() { this.m_encoding = null; this.Reset(); } public override void Reset() { if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } public override unsafe int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid null fixed problem if (bytes.Length == 0) bytes = new byte[1]; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, flush); } internal unsafe override int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Remember the flush this.m_mustFlush = flush; this.m_throwOnOverflow = true; // By default just call the encoding version, no flush by default return m_encoding.GetCharCount(bytes, count, this); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // Avoid empty input fixed problem if (bytes.Length == 0) bytes = new byte[1]; int charCount = chars.Length - charIndex; if (chars.Length == 0) chars = new char[1]; // Just call pointer version fixed (byte* pBytes = bytes) fixed (char* pChars = chars) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } internal unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? "byteCount" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Remember our flush m_mustFlush = flush; m_throwOnOverflow = true; // By default just call the encoding's version return m_encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException((bytes == null ? "bytes" : "chars"), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid empty input problem if (bytes.Length == 0) bytes = new byte[1]; if (chars.Length == 0) chars = new char[1]; // Just call the pointer version (public overrides can't do this) fixed (byte* pBytes = bytes) { fixed (char* pChars = chars) { Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars internal unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? "chars" : "bytes", SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? "byteCount" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // We don't want to throw this.m_mustFlush = flush; this.m_throwOnOverflow = false; this.m_bytesUsed = 0; // Do conversion charsUsed = this.m_encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = this.m_bytesUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !this.HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); // Our data thingys are now full, we can return } public bool MustFlush { get { return m_mustFlush; } } // Anything left in our decoder? internal virtual bool HasState { get { return false; } } // Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow) internal void ClearMustFlush() { m_mustFlush = false; } } }
#if !(UNITY_4_3 || UNITY_4_5) using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using PixelCrushers.DialogueSystem; namespace PixelCrushers.DialogueSystem { /// <summary> /// This is an implementation of the abstract QuestLogWindow class for the Unity UI. /// </summary> [AddComponentMenu("Dialogue System/UI/Unity UI/Quest/Quest Log Window")] public class UnityUIQuestLogWindow : QuestLogWindow { /// <summary> /// The main quest log window panel. /// </summary> public UnityEngine.UI.Graphic mainPanel; /// <summary> /// The active quests button. /// </summary> public UnityEngine.UI.Button activeQuestsButton; /// <summary> /// The completed quests button. /// </summary> public UnityEngine.UI.Button completedQuestsButton; /// <summary> /// The quest table. /// </summary> public UnityEngine.UI.Graphic questTable; /// <summary> /// The quest template. /// </summary> public UnityUIQuestTemplate questTemplate; /// <summary> /// The confirmation popup to use if the player clicks the abandon quest button. /// It should send ClickConfirmAbandonQuest if the player confirms, or /// ClickCancelAbandonQuest if the player cancels. /// </summary> public UnityEngine.UI.Graphic abandonPopup; /// <summary> /// The quest title label to set in the abandon quest dialog popup. /// </summary> public UnityEngine.UI.Text abandonQuestTitle; /// <summary> /// Set <c>true</c> to always keep a control focused; useful for gamepads. /// </summary> public bool autoFocus = false; [Serializable] public class AnimationTransitions { public string showTrigger = "Show"; public string hideTrigger = "Hide"; } public AnimationTransitions animationTransitions = new AnimationTransitions(); /// <summary> /// This handler is called if the player confirms abandonment of a quest. /// </summary> private Action confirmAbandonQuestHandler = null; private Animator animator = null; public override void Awake() { animator = GetComponent<Animator>(); if (animator == null && mainPanel != null) animator = mainPanel.GetComponent<Animator>(); } /// <summary> /// Hide the main panel and all of the templates on start. /// </summary> public virtual void Start() { Tools.SetGameObjectActive(mainPanel, false); Tools.SetGameObjectActive(abandonPopup, false); Tools.SetGameObjectActive(questTemplate, false); SetStateButtonListeners(); SetStateToggleButtons(); if (DialogueDebug.LogWarnings) { if (mainPanel == null) Debug.LogWarning(string.Format("{0}: {1} Main Panel is unassigned", new object[] { DialogueDebug.Prefix, name })); if (questTable == null) Debug.LogWarning(string.Format("{0}: {1} Quest Table is unassigned", new object[] { DialogueDebug.Prefix, name })); if (questTemplate == null || !questTemplate.ArePropertiesAssigned) { Debug.LogWarning(string.Format("{0}: {1} Quest Template or one of its properties is unassigned", new object[] { DialogueDebug.Prefix, name })); } } } public void Update() { if (autoFocus && (UnityEngine.EventSystems.EventSystem.current != null)) { if (UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject == null) { GameObject go = completedQuestsButton.gameObject.activeSelf ? completedQuestsButton.gameObject : activeQuestsButton.gameObject; UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject(go, null); } } } /// <summary> /// Open the window by showing the main panel. The bark UI may conflict with the quest /// log window, so temporarily disable it. /// </summary> /// <param name="openedWindowHandler">Opened window handler.</param> public override void OpenWindow(Action openedWindowHandler) { Tools.SetGameObjectActive(mainPanel, true); if (CanTriggerAnimations()) { DialogueManager.Instance.StartCoroutine(OpenAfterAnimation(openedWindowHandler)); } else { openedWindowHandler(); } } /// <summary> /// Close the window by hiding the main panel. Re-enable the bark UI. /// </summary> /// <param name="closedWindowHandler">Closed window handler.</param> public override void CloseWindow(Action closedWindowHandler) { if (CanTriggerAnimations()) { DialogueManager.Instance.StartCoroutine(CloseAfterAnimation(closedWindowHandler)); } else { Tools.SetGameObjectActive(mainPanel, false); closedWindowHandler(); } } private bool CanTriggerAnimations() { return (animator != null) && (animationTransitions != null); } private IEnumerator OpenAfterAnimation(Action openedWindowHandler) { if (animator != null) { if (pauseWhileOpen) Time.timeScale = 1; animator.SetTrigger(animationTransitions.showTrigger); const float maxWaitDuration = 10; float timeout = Time.realtimeSinceStartup + maxWaitDuration; var oldHashId = UITools.GetAnimatorNameHash(animator.GetCurrentAnimatorStateInfo(0)); while ((UITools.GetAnimatorNameHash(animator.GetCurrentAnimatorStateInfo(0)) == oldHashId) && (Time.realtimeSinceStartup < timeout)) { yield return null; } yield return new WaitForSeconds(animator.GetCurrentAnimatorStateInfo(0).length); if (pauseWhileOpen) Time.timeScale = 0; } openedWindowHandler(); } private IEnumerator CloseAfterAnimation(Action closedWindowHandler) { if (animator != null) { if (pauseWhileOpen) Time.timeScale = 1; animator.SetTrigger(animationTransitions.hideTrigger); const float maxWaitDuration = 10; float timeout = Time.realtimeSinceStartup + maxWaitDuration; var oldHashId = UITools.GetAnimatorNameHash(animator.GetCurrentAnimatorStateInfo(0)); while ((UITools.GetAnimatorNameHash(animator.GetCurrentAnimatorStateInfo(0)) == oldHashId) && (Time.realtimeSinceStartup < timeout)) { yield return null; } yield return new WaitForSeconds(animator.GetCurrentAnimatorStateInfo(0).length); } Tools.SetGameObjectActive(mainPanel, false); closedWindowHandler(); } /// <summary> /// Whenever the quest list is updated, repopulate the scroll panel. /// </summary> public override void OnQuestListUpdated() { if (questTable == null) return; ClearQuestTable(); if (Quests.Length == 0) { AddQuestToTable(new QuestInfo(string.Empty, new FormattedText(NoQuestsMessage), FormattedText.empty, new FormattedText[0], new QuestState[0], false, false, false), 0); } else { AddQuestsToTable(); } SetStateToggleButtons(); } private void SetStateButtonListeners() { if (activeQuestsButton != null) { activeQuestsButton.onClick.RemoveListener(() => ClickShowActiveQuestsButton()); activeQuestsButton.onClick.AddListener(() => ClickShowActiveQuestsButton()); } if (completedQuestsButton != null) { completedQuestsButton.onClick.RemoveListener(() => ClickShowCompletedQuestsButton()); completedQuestsButton.onClick.AddListener(() => ClickShowCompletedQuestsButton()); } } private void SetStateToggleButtons() { if (activeQuestsButton != null) activeQuestsButton.interactable = !IsShowingActiveQuests; if (completedQuestsButton != null) completedQuestsButton.interactable = IsShowingActiveQuests; } private void ClearQuestTable() { if (questTable == null) return; foreach (Transform child in questTable.transform) { if (child.gameObject.activeSelf) { Destroy(child.gameObject); } } } private void AddQuestsToTable() { if (questTable == null) return; for (int i = 0; i < Quests.Length; i++) { AddQuestToTable(Quests[i], i); } } /// <summary> /// Adds a quest to the table using the template. /// </summary> /// <param name="questInfo">Quest info.</param> private void AddQuestToTable(QuestInfo questInfo, int questIndex) { if ((questTable == null) || (questTemplate == null) || !questTemplate.ArePropertiesAssigned) return; // Instantiate a copy of the template: GameObject questGameObject = Instantiate(questTemplate.gameObject) as GameObject; if (questGameObject == null) { Debug.LogError(string.Format("{0}: {1} couldn't instantiate quest template", new object[] { DialogueDebug.Prefix, name })); } questGameObject.name = questInfo.Heading.text; questGameObject.transform.SetParent(questTable.transform, false); questGameObject.SetActive(true); UnityUIQuestTemplate questControl = questGameObject.GetComponent<UnityUIQuestTemplate>(); // Set the heading button: var questHeadingButton = questControl.heading; questHeadingButton.GetComponentInChildren<UnityEngine.UI.Text>().text = questInfo.Heading.text; questHeadingButton.onClick.AddListener(() => ClickQuestFoldout(questInfo.Title)); // Set details if this is the selected quest: if (IsSelectedQuest(questInfo)) { // Set the description: if (questHeadingSource == QuestHeadingSource.Name) { questControl.description.text = questInfo.Description.text; } else { Tools.SetGameObjectActive(questControl.description, false); } // Set the entry description: if (questInfo.EntryStates.Length > 0) { string entryDescription = string.Empty; for (int i = 0; i < questInfo.Entries.Length; i++) { if (questInfo.EntryStates[i] != QuestState.Unassigned) { if (!string.IsNullOrEmpty(entryDescription)) { entryDescription += "\n"; } entryDescription += questInfo.Entries[i].text; } } questControl.entryDescription.text = entryDescription; } else { Tools.SetGameObjectActive(questControl.entryDescription, false); } UnityUIQuestTitle unityUIQuestTitle = null; // Set the track button: if (questControl.trackButton != null) { unityUIQuestTitle = questControl.trackButton.gameObject.AddComponent<UnityUIQuestTitle>(); unityUIQuestTitle.questTitle = questInfo.Title; questControl.trackButton.onClick.RemoveListener(() => ClickTrackQuestButton()); questControl.trackButton.onClick.AddListener(() => ClickTrackQuestButton()); Tools.SetGameObjectActive(questControl.trackButton, questInfo.Trackable); } // Set the abandon button: if (questControl.abandonButton != null) { unityUIQuestTitle = questControl.abandonButton.gameObject.AddComponent<UnityUIQuestTitle>(); unityUIQuestTitle.questTitle = questInfo.Title; questControl.abandonButton.onClick.RemoveListener(() => ClickAbandonQuestButton()); questControl.abandonButton.onClick.AddListener(() => ClickAbandonQuestButton()); Tools.SetGameObjectActive(questControl.abandonButton, questInfo.Abandonable); } } else { Tools.SetGameObjectActive(questControl.description, false); Tools.SetGameObjectActive(questControl.entryDescription, false); Tools.SetGameObjectActive(questControl.trackButton, false); Tools.SetGameObjectActive(questControl.abandonButton, false); } } public void ClickQuestFoldout(string questTitle) { ClickQuest(questTitle); } /// <summary> /// Track button clicked event that sets SelectedQuest first. /// </summary> /// <param name="button">Button.</param> private void OnTrackButtonClicked(GameObject button) { SelectedQuest = button.GetComponent<UnityUIQuestTitle>().questTitle; ClickTrackQuest(SelectedQuest); } /// <summary> /// Abandon button clicked event that sets SelectedQuest first. /// </summary> /// <param name="button">Button.</param> private void OnAbandonButtonClicked(GameObject button) { SelectedQuest = button.GetComponent<UnityUIQuestTitle>().questTitle; ClickAbandonQuest(SelectedQuest); } /// <summary> /// Opens the abandon confirmation popup. /// </summary> /// <param name="title">Quest title.</param> /// <param name="confirmAbandonQuestHandler">Confirm abandon quest handler.</param> public override void ConfirmAbandonQuest(string title, Action confirmAbandonQuestHandler) { this.confirmAbandonQuestHandler = confirmAbandonQuestHandler; OpenAbandonPopup(title); } /// <summary> /// Opens the abandon popup modally if assigned; otherwise immediately confirms. /// </summary> /// <param name="title">Quest title.</param> private void OpenAbandonPopup(string title) { if (abandonPopup != null) { Tools.SetGameObjectActive(abandonPopup, true); if (abandonQuestTitle != null) abandonQuestTitle.text = title; } else { this.confirmAbandonQuestHandler(); } } /// <summary> /// Closes the abandon popup. /// </summary> private void CloseAbandonPopup() { Tools.SetGameObjectActive(abandonPopup, false); } public void ClickConfirmAbandonQuestButton() { CloseAbandonPopup(); confirmAbandonQuestHandler(); } public void ClickCancelAbandonQuestButton() { CloseAbandonPopup(); } } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.ComponentModel; namespace CommonTools.TreeList { public class HitInfo { public enum eHitType { kColumnHeader = 0x0001, kColumnHeaderResize = 0x0002, } public eHitType HitType = 0; public TreeListColumn Column = null; } /// <summary> /// DesignTimeVisible(false) prevents the columns from showing in the component tray (bottom of screen) /// If the class implement IComponent it must also implement default (void) constructor and when overriding /// the collection editors CreateInstance the return object must be used (if implementing IComponent), the reason /// is that ISite is needed, and ISite is set when base.CreateInstance is called. /// If no default constructor then the object will not be added to the collection in the initialize. /// In addition if implementing IComponent then name and generatemember is shown in the property grid /// Columns should just be added to the collection, no need for member, so no need to implement IComponent /// </summary> [DesignTimeVisible(false)] [TypeConverter(typeof(ColumnConverter))] public class TreeListColumn { TreeList.TextFormatting m_headerFormat = new TreeList.TextFormatting(); TreeList.TextFormatting m_cellFormat = new TreeList.TextFormatting(); [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public TreeList.TextFormatting HeaderFormat { get { return m_headerFormat; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public TreeList.TextFormatting CellFormat { get { return m_cellFormat; } } TreeListColumnCollection m_owner = null; Rectangle m_calculatedRect; int m_visibleIndex = -1; int m_colIndex = -1; int m_width = 50; string m_fieldName = string.Empty; string m_caption = string.Empty; internal TreeListColumnCollection Owner { get { return m_owner; } set { m_owner = value; } } internal Rectangle internalCalculatedRect { get { return m_calculatedRect; } set { m_calculatedRect = value; } } internal int internalVisibleIndex { get { return m_visibleIndex; } set { m_visibleIndex = value; } } internal int internalIndex { get { return m_colIndex; } set { m_colIndex = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Rectangle CalculatedRect { get { return internalCalculatedRect; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public TreeListView TreeList { get { if (Owner == null) return null; return Owner.Owner; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Font Font { get { return m_owner.Font; } } public int Width { get { return m_width; } set { if (m_width == value) return; m_width = value; if (m_owner != null && m_owner.DesignMode) m_owner.RecalcVisibleColumsRect(); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Caption { get { return m_caption; } set { m_caption = value; if (m_owner != null) m_owner.Invalidate(); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Fieldname { get { return m_fieldName; } set { if (m_owner == null || m_owner.DesignMode == false) throw new Exception("Fieldname can only be set at design time, Use Constructor to set programatically"); if (value.Length == 0) throw new Exception("empty Fieldname not value"); if (m_owner[value] != null) throw new Exception("fieldname already exist in collection"); m_fieldName = value; } } public TreeListColumn(string fieldName) { m_fieldName = fieldName; } public TreeListColumn(string fieldName, string caption) { m_fieldName = fieldName; m_caption = caption; } public TreeListColumn(string fieldName, string caption, int width) { m_fieldName = fieldName; m_caption = caption; m_width = width; } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int VisibleIndex { get { return internalVisibleIndex; } set { if (m_owner != null) m_owner.SetVisibleIndex(this, value); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int Index { get { return internalIndex; } } public bool ishot = false; public virtual void Draw(Graphics dc, ColumnHeaderPainter painter, Rectangle r) { painter.DrawHeader(dc, r, this, this.HeaderFormat, ishot); } bool m_autoSize = false; float m_autoSizeRatio = 100; int m_autoSizeMinSize; [DefaultValue(false)] public bool AutoSize { get { return m_autoSize; } set { m_autoSize = value; } } [DefaultValue(100f)] public float AutoSizeRatio { get { return m_autoSizeRatio; } set { m_autoSizeRatio = value; } } public int AutoSizeMinSize { get { return m_autoSizeMinSize; } set { m_autoSizeMinSize = value; } } int m_calculatedAutoSize; internal int CalculatedAutoSize { get { return m_calculatedAutoSize; } set { m_calculatedAutoSize = value; } } } [Description("This is the columns collection")] //[TypeConverterAttribute(typeof(ColumnsTypeConverter))] [Editor(typeof(ColumnCollectionEditor),typeof(System.Drawing.Design.UITypeEditor))] public class TreeListColumnCollection : IList<TreeListColumn>, IList { ColumnHeaderPainter m_painter = new ColumnHeaderPainter(); TreeList.CollumnSetting m_options; TreeListView m_owner; List<TreeListColumn> m_columns = new List<TreeListColumn>(); List<TreeListColumn> m_visibleCols = new List<TreeListColumn>(); Dictionary<string, TreeListColumn> m_columnMap = new Dictionary<string,TreeListColumn>(); [Browsable(false)] public TreeList.CollumnSetting Options { get { return m_options; } } [Browsable(false)] public ColumnHeaderPainter Painter { get { return m_painter; } set { m_painter = value; } } [Browsable(false)] public TreeListView Owner { get { return m_owner; } } [Browsable(false)] public Font Font { get { return m_owner.Font; } } [Browsable(false)] public TreeListColumn[] VisibleColumns { get { return m_visibleCols.ToArray(); } } [Browsable(false)] public int ColumnsWidth { get { int width = 0; foreach (TreeListColumn col in m_visibleCols) { if (col.AutoSize) width += col.CalculatedAutoSize; else width += col.Width; } return width; } } public TreeListColumnCollection(TreeListView owner) { m_owner = owner; m_options = new TreeList.CollumnSetting(owner); } public TreeListColumn this[int index] { get { return m_columns[index]; } set { m_columns[index] = value; } } public TreeListColumn this[string fieldname] { get { TreeListColumn col; m_columnMap.TryGetValue(fieldname, out col); return col; } } public void SetVisibleIndex(TreeListColumn col, int index) { m_visibleCols.Remove(col); if (index >= 0) { if (index < m_visibleCols.Count) m_visibleCols.Insert(index, col); else m_visibleCols.Add(col); } RecalcVisibleColumsRect(); } public HitInfo CalcHitInfo(Point point, int horzOffset) { HitInfo info = new HitInfo(); info.Column = CalcHitColumn(point, horzOffset); if ((info.Column != null) && (point.Y < Options.HeaderHeight)) { info.HitType |= HitInfo.eHitType.kColumnHeader; int right = info.Column.CalculatedRect.Right - horzOffset; if (info.Column.AutoSize == false) { if (point.X >= right - 4 && point.X <= right) info.HitType |= HitInfo.eHitType.kColumnHeaderResize; } } return info; } public TreeListColumn CalcHitColumn(Point point, int horzOffset) { if (point.X < Options.LeftMargin) return null; foreach (TreeListColumn col in m_visibleCols) { int left = col.CalculatedRect.Left - horzOffset; int right = col.CalculatedRect.Right - horzOffset; if (point.X >= left && point.X <= right) return col; } return null; } public void RecalcVisibleColumsRect() { RecalcVisibleColumsRect(false); } public void RecalcVisibleColumsRect(bool isDoingColumnResizing) { if (IsInitializing) return; int x = 0;//m_leftMargin; if (m_owner.RowOptions.ShowHeader) x = m_owner.RowOptions.HeaderWidth; int y = 0; int h = Options.HeaderHeight; int index = 0; foreach(TreeListColumn col in m_columns) { col.internalVisibleIndex = -1; col.internalIndex = index++; } // calculate size requierd by fix columns and auto adjusted columns // at the same time calculate total ratio value int widthFixedColumns = 0; int widthAutoSizeColumns = 0; float totalRatio = 0; foreach (TreeListColumn col in m_visibleCols) { if (col.AutoSize) { widthAutoSizeColumns += col.AutoSizeMinSize; totalRatio += col.AutoSizeRatio; } else widthFixedColumns += col.Width; } /* CommonTools.Tracing.WriteLine(0, "\nRecalcVisibleColumsRect"); CommonTools.Tracing.WriteLine(0, "WidthRequired, auto {0}, fixed {1}, total {2}", widthAutoSizeColumns, widthFixedColumns, widthAutoSizeColumns + widthFixedColumns); */ int clientWidth = m_owner.ClientRectangle.Width - m_owner.RowHeaderWidth(); // find ratio 'unit' value float remainingWidth = clientWidth - (widthFixedColumns + widthAutoSizeColumns); float ratioUnit = 0; if (totalRatio > 0 && remainingWidth > 0) ratioUnit = remainingWidth / totalRatio; /* CommonTools.Tracing.WriteLine(0, "ClientWidth {0}", clientWidth); CommonTools.Tracing.WriteLine(0, "RemainngWidth {0}, TotalRatio {1}, RatioUnits {2}", remainingWidth, totalRatio, ratioUnit); */ for (index = 0; index < m_visibleCols.Count; index++) { TreeListColumn col = m_visibleCols[index]; int width = col.Width; if (col.AutoSize) { // if doing column resizing then keep adjustable columns fixed at last width if (isDoingColumnResizing) width = col.CalculatedAutoSize; else width = col.AutoSizeMinSize + (int)(ratioUnit * col.AutoSizeRatio) - 1; col.CalculatedAutoSize = width; } col.internalCalculatedRect = new Rectangle(x, y, width, h); col.internalVisibleIndex = index; x += width; } Invalidate(); } public void Draw(Graphics dc, Rectangle rect, int horzOffset) { foreach (TreeListColumn col in m_visibleCols) { Rectangle r = col.CalculatedRect; r.X -= horzOffset; if (r.Left > rect.Right) break; col.Draw(dc, m_painter, r); } // drwa row header filler if (m_owner.RowOptions.ShowHeader) { Rectangle r = new Rectangle(0, 0, m_owner.RowOptions.HeaderWidth, Options.HeaderHeight); m_painter.DrawHeaderFiller(dc, r); } } public void AddRange(IEnumerable<TreeListColumn> columns) { foreach (TreeListColumn col in columns) Add(col); } /// <summary> /// AddRange(Item[]) is required for the designer. /// </summary> /// <param name="columns"></param> public void AddRange(TreeListColumn[] columns) { foreach (TreeListColumn col in columns) Add(col); } public void Add(TreeListColumn item) { bool designmode = Owner.DesignMode; if (!designmode) { Debug.Assert(m_columnMap.ContainsKey(item.Fieldname) == false); Debug.Assert(item.Owner == null, "column.Owner == null"); } else { m_columns.Remove(item); m_visibleCols.Remove(item); } item.Owner = this; m_columns.Add(item); m_visibleCols.Add(item); m_columnMap[item.Fieldname] = item; RecalcVisibleColumsRect(); //return item; } public void Clear() { m_columnMap.Clear(); m_columns.Clear(); m_visibleCols.Clear(); } public bool Contains(TreeListColumn item) { return m_columns.Contains(item); } [Browsable(false)] public int Count { get { return m_columns.Count; } } [Browsable(false)] public bool IsReadOnly { get { return false; } } #region IList<TreeListColumn> Members public int IndexOf(TreeListColumn item) { return m_columns.IndexOf(item); } public void Insert(int index, TreeListColumn item) { m_columns.Insert(index, item); } public void RemoveAt(int index) { m_columns.RemoveAt(index); } #endregion #region ICollection<TreeListColumn> Members public void CopyTo(TreeListColumn[] array, int arrayIndex) { m_columns.CopyTo(array, arrayIndex); } public bool Remove(TreeListColumn item) { return m_columns.Remove(item); } #endregion #region IEnumerable<TreeListColumn> Members public IEnumerator<TreeListColumn> GetEnumerator() { return m_columns.GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region IList Members int IList.Add(object value) { Add((TreeListColumn)value); return Count - 1; } bool IList.Contains(object value) { return Contains((TreeListColumn)value); } int IList.IndexOf(object value) { return IndexOf((TreeListColumn)value); } void IList.Insert(int index, object value) { Insert(index, (TreeListColumn)value); } bool IList.IsFixedSize { get { return false; } } void IList.Remove(object value) { Remove((TreeListColumn)value); } object IList.this[int index] { get { throw new Exception("The method or operation is not implemented."); } set { throw new Exception("The method or operation is not implemented."); } } #endregion #region ICollection Members public void CopyTo(Array array, int index) { throw new Exception("The method or operation is not implemented."); } public bool IsSynchronized { get { throw new Exception("The method or operation is not implemented."); } } public object SyncRoot { get { throw new Exception("The method or operation is not implemented."); } } #endregion internal bool DesignMode { get { if (m_owner != null) return m_owner.DesignMode; return false; } } internal void Invalidate() { if (m_owner != null) m_owner.Invalidate(); } bool IsInitializing = false; internal void BeginInit() { IsInitializing = true; } internal void EndInit() { IsInitializing = false; RecalcVisibleColumsRect(); } } }
//Copyright (C) 2006 Richard J. Northedge // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //This file is based on the MaxentResolver.java source file found in the //original java implementation of OpenNLP. That source file contains the following header: //Copyright (C) 2003 Thomas Morton // //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of the License, or (at your option) any later version. // //This library is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public //License along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. using System; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; using SharpEntropy.IO; using System.IO; namespace OpenNLP.Tools.Coreference.Resolver { /// <summary> /// Provides common functionality used by classes which implement the {@link IResolver} interface /// and use maximum entropy models to make resolution decisions. /// </summary> public abstract class MaximumEntropyResolver : AbstractResolver { /// <summary> /// Outcomes when two mentions are coreferent. /// </summary> public const string Same = "same"; /// <summary> /// Outcome when two mentions are not coreferent. /// </summary> public const string Diff = "diff"; /// <summary> /// Default feature value. /// </summary> public const string Default = "default"; private static readonly Regex EndsWithPeriod = new Regex("\\.$", RegexOptions.Compiled); private const double MinimumSimilarityProbability = 0.60; private const string SimilarityCompatible = "sim.compatible"; private const string SimilarityIncompatible = "sim.incompatible"; private const string SimilarityUnknown = "sim.unknown"; private const string NumberCompatible = "num.compatible"; private const string NumberIncompatible = "num.incompatible"; private const string NumberUnknown = "num.unknown"; private const string GenderCompatible = "gen.compatible"; private const string GenderIncompatible = "gen.incompatible"; private const string GenderUnknown = "gen.unknown"; private const bool DebugOn = false; private readonly string _modelName; private readonly SharpEntropy.IMaximumEntropyModel _model; private readonly double[] _candidateProbabilities; private readonly int _sameIndex; private readonly ResolverMode _resolverMode; private readonly List<SharpEntropy.TrainingEvent> _events; private const string ModelExtension = ".nbin"; public static Similarity.ITestSimilarityModel SimilarityModel { get; set; } /// <summary> /// When true, this designates that the resolver should use the first referent encountered which it /// more preferable than non-reference. When false, all non-excluded referents within this resolver's range /// are considered. /// </summary> protected internal bool PreferFirstReferent { get; set; } /// <summary> /// When true, this designates that training should consist of a single positive and a single negative example /// (when possible) for each mention. /// </summary> protected internal bool PairedSampleSelection { get; set; } /// <summary> /// When true, this designates that the same maximum entropy model should be used non-reference /// events (the pairing of a mention and the "null" reference) as is used for potentially /// referential pairs. When false a seperate model is created for these events. /// </summary> protected internal bool UseSameModelForNonRef { get; set; } /// <summary> /// The model for computing non-referential probabilities. /// </summary> protected internal INonReferentialResolver NonReferentialResolver { get; set; } /// <summary> /// Creates a maximum-entropy-based resolver which will look the specified number of entities back /// for a referent. /// This constructor is only used for unit testing. /// </summary> /// <param name="numberOfEntitiesBack"> /// </param> /// <param name="preferFirstReferent"> /// </param> protected MaximumEntropyResolver(int numberOfEntitiesBack, bool preferFirstReferent) : base(numberOfEntitiesBack) { PreferFirstReferent = preferFirstReferent; } /// <summary> /// Creates a maximum-entropy-based resolver with the specified model name, using the /// specified mode, which will look the specified number of entities back for a referent and /// prefer the first referent if specified. /// </summary> /// <param name="modelDirectory"> /// The name of the directory where the resover models are stored. /// </param> /// <param name="name"> /// The name of the file where this model will be read or written. /// </param> /// <param name="mode"> /// The mode this resolver is being using in (training, testing). /// </param> /// <param name="numberOfEntitiesBack"> /// The number of entities back in the text that this resolver will look /// for a referent. /// </param> /// <param name="preferFirstReferent"> /// Set to true if the resolver should prefer the first referent which is more /// likly than non-reference. This only affects testing. /// </param> /// <param name="nonReferentialResolver"> /// Determines how likly it is that this entity is non-referential. /// </param> protected MaximumEntropyResolver(string modelDirectory, string name, ResolverMode mode, int numberOfEntitiesBack, bool preferFirstReferent, INonReferentialResolver nonReferentialResolver): base(numberOfEntitiesBack) { PreferFirstReferent = preferFirstReferent; NonReferentialResolver = nonReferentialResolver; _resolverMode = mode; _modelName = modelDirectory + "/" + name; if (_resolverMode == ResolverMode.Test) { _model = new SharpEntropy.GisModel(new BinaryGisModelReader(_modelName + ModelExtension)); _sameIndex = _model.GetOutcomeIndex(Same); } else if (_resolverMode == ResolverMode.Train) { _events = new List<SharpEntropy.TrainingEvent>(); } else { Console.Error.WriteLine("Unknown mode: " + _resolverMode); } //add one for non-referent possibility _candidateProbabilities = new double[GetNumberEntitiesBack() + 1]; } /// <summary> /// Creates a maximum-entropy-based resolver with the specified model name, using the /// specified mode, which will look the specified number of entities back for a referent. /// </summary> /// <param name="modelDirectory"> /// The name of the directory where the resolver models are stored. /// </param> /// <param name="modelName"> /// The name of the file where this model will be read or written. /// </param> /// <param name="mode"> /// The mode this resolver is being using in (training, testing). /// </param> /// <param name="numberEntitiesBack"> /// The number of entities back in the text that this resolver will look /// for a referent. /// </param> protected MaximumEntropyResolver(string modelDirectory, string modelName, ResolverMode mode, int numberEntitiesBack): this(modelDirectory, modelName, mode, numberEntitiesBack, false){} protected MaximumEntropyResolver(string modelDirectory, string modelName, ResolverMode mode, int numberEntitiesBack, INonReferentialResolver nonReferentialResolver): this(modelDirectory, modelName, mode, numberEntitiesBack, false, nonReferentialResolver){} protected MaximumEntropyResolver(string modelDirectory, string modelName, ResolverMode mode, int numberEntitiesBack, bool preferFirstReferent): this(modelDirectory, modelName, mode, numberEntitiesBack, preferFirstReferent, new DefaultNonReferentialResolver(modelDirectory, modelName, mode)){} protected MaximumEntropyResolver(string modelDirectory, string modelName, ResolverMode mode, int numberEntitiesBack, bool preferFirstReferent, double nonReferentialProbability): this(modelDirectory, modelName, mode, numberEntitiesBack, preferFirstReferent, new FixedNonReferentialResolver(nonReferentialProbability)){} public override DiscourseEntity Resolve(Mention.MentionContext expression, DiscourseModel discourseModel) { DiscourseEntity discourseEntity; int entityIndex = 0; double nonReferentialProbability = NonReferentialResolver.GetNonReferentialProbability(expression); if (DebugOn) { System.Console.Error.WriteLine(this.ToString() + ".resolve: " + expression.ToText() + " -> " + "null " + nonReferentialProbability); } for (; entityIndex < GetNumberEntitiesBack(discourseModel); entityIndex++) { discourseEntity = discourseModel.GetEntity(entityIndex); if (IsOutOfRange(expression, discourseEntity)) { break; } if (IsExcluded(expression, discourseEntity)) { _candidateProbabilities[entityIndex] = 0; if (DebugOn) { Console.Error.WriteLine("excluded " + this.ToString() + ".resolve: " + expression.ToText() + " -> " + discourseEntity + " " + _candidateProbabilities[entityIndex]); } } else { string[] features = GetFeatures(expression, discourseEntity).ToArray(); try { _candidateProbabilities[entityIndex] = _model.Evaluate(features)[_sameIndex]; } catch (IndexOutOfRangeException) { _candidateProbabilities[entityIndex] = 0; } if (DebugOn) { Console.Error.WriteLine(this + ".resolve: " + expression.ToText() + " -> " + discourseEntity + " (" + expression.GetGender() + "," + discourseEntity.Gender + ") " + _candidateProbabilities[entityIndex] + " " + string.Join(",", features)); //SupportClass.CollectionToString(lfeatures)); } } if (PreferFirstReferent && _candidateProbabilities[entityIndex] > nonReferentialProbability) { entityIndex++; //update for nonRef assignment break; } } _candidateProbabilities[entityIndex] = nonReferentialProbability; // find max int maximumCandidateIndex = 0; for (int currentCandidate = 1; currentCandidate <= entityIndex; currentCandidate++) { if (_candidateProbabilities[currentCandidate] > _candidateProbabilities[maximumCandidateIndex]) { maximumCandidateIndex = currentCandidate; } } if (maximumCandidateIndex == entityIndex) { // no referent return null; } else { discourseEntity = discourseModel.GetEntity(maximumCandidateIndex); return discourseEntity; } } /* protected double getNonReferentialProbability(MentionContext ec) { if (useFixedNonReferentialProbability) { return fixedNonReferentialProbability; } List lfeatures = getFeatures(ec, null); string[] features = (string[]) lfeatures.toArray(new string[lfeatures.size()]); double[] dist = nrModel.eval(features); return (dist[nrSameIndex]); } */ /// <summary> /// Returns whether the specified entity satisfies the criteria for being a default referent. /// This criteria is used to perform sample selection on the training data and to select a single /// non-referent entity. Typically the criteria is a hueristic for a likely referent. /// </summary> /// <param name="discourseEntity"> /// The discourse entity being considered for non-reference. /// </param> /// <returns> /// True if the entity should be used as a default referent, false otherwise. /// </returns> protected internal virtual bool defaultReferent(DiscourseEntity discourseEntity) { Mention.MentionContext entityContext = discourseEntity.LastExtent; if (entityContext.NounPhraseSentenceIndex == 0) { return true; } return false; } public override DiscourseEntity Retain(Mention.MentionContext mention, DiscourseModel discourseModel) { if (_resolverMode == ResolverMode.Train) { DiscourseEntity discourseEntity = null; bool referentFound = false; bool hasReferentialCandidate = false; bool nonReferentFound = false; for (int entityIndex = 0; entityIndex < GetNumberEntitiesBack(discourseModel); entityIndex++) { DiscourseEntity currentDiscourseEntity = discourseModel.GetEntity(entityIndex); Mention.MentionContext entityMention = currentDiscourseEntity.LastExtent; if (IsOutOfRange(mention, currentDiscourseEntity)) { break; } if (IsExcluded(mention, currentDiscourseEntity)) { if (ShowExclusions) { if (mention.Id != - 1 && entityMention.Id == mention.Id) { System.Console.Error.WriteLine(this + ".retain: Referent excluded: (" + mention.Id + ") " + mention.ToText() + " " + mention.IndexSpan + " -> (" + entityMention.Id + ") " + entityMention.ToText() + " " + entityMention.Span + " " + this); } } } else { hasReferentialCandidate = true; bool useAsDifferentExample = defaultReferent(currentDiscourseEntity); //if (!sampleSelection || (mention.getId() != -1 && entityMention.getId() == mention.getId()) || (!nonReferentFound && useAsDifferentExample)) { List<string> features = GetFeatures(mention, currentDiscourseEntity); //add Event to Model if (DebugOn) { Console.Error.WriteLine(this + ".retain: " + mention.Id + " " + mention.ToText() + " -> " + entityMention.Id + " " + currentDiscourseEntity); } if (mention.Id != - 1 && entityMention.Id == mention.Id) { referentFound = true; _events.Add(new SharpEntropy.TrainingEvent(Same, features.ToArray())); discourseEntity = currentDiscourseEntity; Distances.Add(entityIndex); } else if (!PairedSampleSelection || (!nonReferentFound && useAsDifferentExample)) { nonReferentFound = true; _events.Add(new SharpEntropy.TrainingEvent(Diff, features.ToArray())); } //} } if (PairedSampleSelection && referentFound && nonReferentFound) { break; } if (PreferFirstReferent && referentFound) { break; } } // doesn't refer to anything if (hasReferentialCandidate) { NonReferentialResolver.AddEvent(mention); } return discourseEntity; } else { return base.Retain(mention, discourseModel); } } protected internal virtual string GetMentionCountFeature(DiscourseEntity discourseEntity) { if (discourseEntity.MentionCount >= 5) { return ("mc=5+"); } else { return ("mc=" + discourseEntity.MentionCount); } } /// <summary> /// Returns a list of features for deciding whether the specified mention refers to the specified discourse entity. /// </summary> /// <param name="mention"> /// the mention being considers as possibly referential. /// </param> /// <param name="entity"> /// The discourse entity with which the mention is being considered referential. /// </param> /// <returns> /// a list of features used to predict reference between the specified mention and entity. /// </returns> protected internal virtual List<string> GetFeatures(Mention.MentionContext mention, DiscourseEntity entity) { List<string> features = new List<string>(); features.Add(Default); features.AddRange(GetCompatibilityFeatures(mention, entity)); return features; } public override void Train() { if (_resolverMode == ResolverMode.Train) { if (DebugOn) { Console.Error.WriteLine(this.ToString() + " referential"); using (var fileStream = new FileStream(_modelName + ".events", FileMode.Create)){ using (var writer = new StreamWriter(fileStream, Encoding.GetEncoding(0))) { foreach (SharpEntropy.TrainingEvent e in _events) { writer.Write(e.ToString() + "\n"); } } } } var trainer = new SharpEntropy.GisTrainer(); trainer.TrainModel(new Util.CollectionEventReader(_events), 100, 10); new BinaryGisModelWriter().Persist(new SharpEntropy.GisModel(trainer), _modelName + ModelExtension); NonReferentialResolver.Train(); } } private string GetSemanticCompatibilityFeature(Mention.MentionContext entityContext, DiscourseEntity discourseEntity) { if (SimilarityModel != null) { double best = 0; foreach (Mention.MentionContext checkEntityContext in discourseEntity.Mentions) { double sim = SimilarityModel.AreCompatible(entityContext, checkEntityContext); if (DebugOn) { Console.Error.WriteLine("MaxentResolver.GetSemanticCompatibilityFeature: sem-compat " + sim + " " + entityContext.ToText() + " " + checkEntityContext.ToText()); } if (sim > best) { best = sim; } } if (best > MinimumSimilarityProbability) { return SimilarityCompatible; } else if (best > (1 - MinimumSimilarityProbability)) { return SimilarityUnknown; } else { return SimilarityIncompatible; } } else { Console.Error.WriteLine("MaxentResolver: Uninitialized Semantic Model"); return SimilarityUnknown; } } private string GetGenderCompatibilityFeature(Mention.MentionContext entityContext, DiscourseEntity discourseEntity) { Similarity.GenderEnum entityGender = discourseEntity.Gender; if (entityGender == Similarity.GenderEnum.Unknown || entityContext.GetGender() == Similarity.GenderEnum.Unknown) { return GenderUnknown; } else if (entityContext.GetGender() == entityGender) { return GenderCompatible; } else { return GenderIncompatible; } } private string GetNumberCompatibilityFeature(Mention.MentionContext entityContext, DiscourseEntity discourseEntity) { Similarity.NumberEnum entityNumber = discourseEntity.Number; if (entityNumber == Similarity.NumberEnum.Unknown || entityContext.GetNumber() == Similarity.NumberEnum.Unknown) { return NumberUnknown; } else if (entityContext.GetNumber() == entityNumber) { return NumberCompatible; } else { return NumberIncompatible; } } /// <summary> /// Returns features indicating whether the specified mention and the specified entity are compatible. /// </summary> /// <param name="mention"> /// The mention. /// </param> /// <param name="entity"> /// The entity. /// </param> /// <returns> /// list of features indicating whether the specified mention and the specified entity are compatible. /// </returns> private IEnumerable<string> GetCompatibilityFeatures(Mention.MentionContext mention, DiscourseEntity entity) { var compatibilityFeatures = new List<string>(); string semanticCompatibilityFeature = GetSemanticCompatibilityFeature(mention, entity); compatibilityFeatures.Add(semanticCompatibilityFeature); string genderCompatibilityFeature = GetGenderCompatibilityFeature(mention, entity); compatibilityFeatures.Add(genderCompatibilityFeature); string numberCompatibilityFeature = GetNumberCompatibilityFeature(mention, entity); compatibilityFeatures.Add(numberCompatibilityFeature); if (semanticCompatibilityFeature == SimilarityCompatible && genderCompatibilityFeature == GenderCompatible && numberCompatibilityFeature == NumberCompatible) { compatibilityFeatures.Add("all.compatible"); } else if (semanticCompatibilityFeature == SimilarityIncompatible || genderCompatibilityFeature == GenderIncompatible || numberCompatibilityFeature == NumberIncompatible) { compatibilityFeatures.Add("some.incompatible"); } return compatibilityFeatures; } /// <summary> /// Returns a list of features based on the surrounding context of the specified mention. /// </summary> /// <param name="mention"> /// the mention whose surround context the features model. /// </param> /// <returns> /// a list of features based on the surrounding context of the specified mention /// </returns> public static List<string> GetContextFeatures(Mention.MentionContext mention) { var features = new List<string>(); if (mention.PreviousToken != null) { features.Add("pt=" + mention.PreviousToken.SyntacticType); features.Add("pw=" + mention.PreviousToken); } else { features.Add("pt=BOS"); features.Add("pw=BOS"); } if (mention.NextToken != null) { features.Add("nt=" + mention.NextToken.SyntacticType); features.Add("nw=" + mention.NextToken); } else { features.Add("nt=EOS"); features.Add("nw=EOS"); } if (mention.NextTokenBasal != null) { features.Add("bnt=" + mention.NextTokenBasal.SyntacticType); features.Add("bnw=" + mention.NextTokenBasal); } else { features.Add("bnt=EOS"); features.Add("bnw=EOS"); } return features; } private Util.Set<string> ConstructModifierSet(Mention.IParse[] tokens, int headIndex) { Util.Set<string> modifierSet = new Util.HashSet<string>(); for (int tokenIndex = 0; tokenIndex < headIndex; tokenIndex++) { Mention.IParse token = tokens[tokenIndex]; modifierSet.Add(token.ToString().ToLower()); } return modifierSet; } /// <summary> /// Returns whether the specified token is a definite article.</summary> /// <param name="token"> /// The token. /// </param> /// <param name="tag"> /// The pos-tag for the specified token. /// </param> /// <returns> /// whether the specified token is a definite article. /// </returns> protected internal virtual bool IsDefiniteArticle(string token, string tag) { token = token.ToLower(); if (token == "the" || token == "these" || token == "these" || tag == PartsOfSpeech.PossessivePronoun) { return true; } return false; } private bool IsSubstring(string mentionStrip, string entityMentionStrip) { int index = entityMentionStrip.IndexOf(mentionStrip); if (index != - 1) { //check boundries if (index != 0 && entityMentionStrip[index - 1] != ' ') { return false; } int end = index + mentionStrip.Length; if (end != entityMentionStrip.Length && entityMentionStrip[end] != ' ') { return false; } return true; } return false; } protected internal override bool IsExcluded(Mention.MentionContext entityContext, DiscourseEntity discourseEntity) { if (base.IsExcluded(entityContext, discourseEntity)) { return true; } return false; /* else { if (GEN_INCOMPATIBLE == getGenderCompatibilityFeature(ec,de)) { return true; } else if (NUM_INCOMPATIBLE == getNumberCompatibilityFeature(ec,de)) { return true; } else if (SIM_INCOMPATIBLE == getSemanticCompatibilityFeature(ec,de)) { return true; } return false; } */ } /// <summary> /// Returns distance features for the specified mention and entity. /// </summary> /// <param name="mention"> /// The mention. /// </param> /// <param name="entity"> /// The entity. /// </param> /// <returns> /// list of distance features for the specified mention and entity. /// </returns> protected internal virtual List<string> GetDistanceFeatures(Mention.MentionContext mention, DiscourseEntity entity) { var features = new List<string>(); Mention.MentionContext currentEntityContext = entity.LastExtent; int entityDistance = mention.NounPhraseDocumentIndex - currentEntityContext.NounPhraseDocumentIndex; int sentenceDistance = mention.SentenceNumber - currentEntityContext.SentenceNumber; int hobbsEntityDistance; if (sentenceDistance == 0) { hobbsEntityDistance = currentEntityContext.NounPhraseSentenceIndex; } else { //hobbsEntityDistance = entityDistance - (entities within sentence from mention to end) + (entities within sentence form start to mention) //hobbsEntityDistance = entityDistance - (cec.maxNounLocation - cec.getNounPhraseSentenceIndex) + cec.getNounPhraseSentenceIndex; hobbsEntityDistance = entityDistance + (2 * currentEntityContext.NounPhraseSentenceIndex) - currentEntityContext.MaxNounPhraseSentenceIndex; } features.Add("hd=" + hobbsEntityDistance); features.Add("de=" + entityDistance); features.Add("ds=" + sentenceDistance); //features.add("ds=" + sdist + pronoun); //features.add("dn=" + cec.sentenceNumber); //features.add("ep=" + cec.nounLocation); return features; } private Dictionary<string, string> GetPronounFeatureMap(string pronoun) { var pronounMap = new Dictionary<string, string>(); if (Linker.MalePronounPattern.IsMatch(pronoun)) { pronounMap["gender"] = "male"; } else if (Linker.FemalePronounPattern.IsMatch(pronoun)) { pronounMap["gender"] = "female"; } else if (Linker.NeuterPronounPattern.IsMatch(pronoun)) { pronounMap["gender"] = "neuter"; } if (Linker.SingularPronounPattern.IsMatch(pronoun)) { pronounMap["number"] = "singular"; } else if (Linker.PluralPronounPattern.IsMatch(pronoun)) { pronounMap["number"] = "plural"; } /* if (Linker.firstPersonPronounPattern.matcher(pronoun).matches()) { pronounMap.put("person","first"); } else if (Linker.secondPersonPronounPattern.matcher(pronoun).matches()) { pronounMap.put("person","second"); } else if (Linker.thirdPersonPronounPattern.matcher(pronoun).matches()) { pronounMap.put("person","third"); } */ return pronounMap; } /// <summary> /// Returns features indicating whether the specified mention is compatible with the pronouns /// of the specified entity. /// </summary> /// <param name="mention"> /// The mention. /// </param> /// <param name="entity"> /// The entity. /// </param> /// <returns> /// list of features indicating whether the specified mention is compatible with the pronouns /// of the specified entity. /// </returns> protected internal virtual List<string> GetPronounMatchFeatures(Mention.MentionContext mention, DiscourseEntity entity) { bool foundCompatiblePronoun = false; bool foundIncompatiblePronoun = false; if (PartsOfSpeech.IsPersOrPossPronoun(mention.HeadTokenTag)) { Dictionary<string, string> pronounMap = GetPronounFeatureMap(mention.HeadTokenText); foreach (Mention.MentionContext candidateMention in entity.Mentions) { if (PartsOfSpeech.IsPersOrPossPronoun(candidateMention.HeadTokenTag)) { if (mention.HeadTokenText.ToUpper() == candidateMention.HeadTokenText.ToUpper()) { foundCompatiblePronoun = true; break; } else { Dictionary<string, string> candidatePronounMap = GetPronounFeatureMap(candidateMention.HeadTokenText); bool allKeysMatch = true; foreach (string key in pronounMap.Keys) { if (candidatePronounMap.ContainsKey(key)) { if (pronounMap[key] != candidatePronounMap[key]) { foundIncompatiblePronoun = true; allKeysMatch = false; } } else { allKeysMatch = false; } } if (allKeysMatch) { foundCompatiblePronoun = true; } } } } } var pronounFeatures = new List<string>(); if (foundCompatiblePronoun) { pronounFeatures.Add("compatiblePronoun"); } if (foundIncompatiblePronoun) { pronounFeatures.Add("incompatiblePronoun"); } return pronounFeatures; } /// <summary> /// Returns string-match features for the the specified mention and entity.</summary> /// <param name="mention"> /// The mention. /// </param> /// <param name="entity"> /// The entity. /// </param> /// <returns> /// list of string-match features for the the specified mention and entity. /// </returns> protected internal virtual List<string> GetStringMatchFeatures(Mention.MentionContext mention, DiscourseEntity entity) { bool sameHead = false; bool modifersMatch = false; bool titleMatch = false; bool noTheModifiersMatch = false; var features = new List<string>(); Mention.IParse[] mentionTokens = mention.TokenParses; var entityContextModifierSet = ConstructModifierSet(mentionTokens, mention.HeadTokenIndex); string mentionHeadString = mention.HeadTokenText.ToLower(); Util.Set<string> featureSet = new Util.HashSet<string>(); foreach (Mention.MentionContext entityMention in entity.Mentions) { string exactMatchFeature = GetExactMatchFeature(entityMention, mention); if (exactMatchFeature != null) { featureSet.Add(exactMatchFeature); } else if (entityMention.Parse.IsCoordinatedNounPhrase && !mention.Parse.IsCoordinatedNounPhrase) { featureSet.Add("cmix"); } else { string mentionStrip = StripNounPhrase(mention); string entityMentionStrip = StripNounPhrase(entityMention); if (mentionStrip != null && entityMentionStrip != null) { if (IsSubstring(mentionStrip, entityMentionStrip)) { featureSet.Add("substring"); } } } Mention.IParse[] entityMentionTokens = entityMention.TokenParses; int headIndex = entityMention.HeadTokenIndex; //if (!mention.getHeadTokenTag().equals(entityMention.getHeadTokenTag())) { // continue; //} want to match NN NNP string entityMentionHeadString = entityMention.HeadTokenText.ToLower(); // model lexical similarity if (mentionHeadString == entityMentionHeadString) { sameHead = true; featureSet.Add("hds=" + mentionHeadString); if (!modifersMatch || !noTheModifiersMatch) { //only check if we haven't already found one which is the same modifersMatch = true; noTheModifiersMatch = true; Util.Set<string> entityMentionModifierSet = ConstructModifierSet(entityMentionTokens, headIndex); foreach (string modifierWord in entityContextModifierSet) { if (!entityMentionModifierSet.Contains(modifierWord)) { modifersMatch = false; if (modifierWord != "the") { noTheModifiersMatch = false; featureSet.Add("mmw=" + modifierWord); } } } } } Util.Set<string> descriptorModifierSet = ConstructModifierSet(entityMentionTokens, entityMention.NonDescriptorStart); if (descriptorModifierSet.Contains(mentionHeadString)) { titleMatch = true; } } if (featureSet.Count != 0) { features.AddRange(featureSet); } if (sameHead) { features.Add("sameHead"); if (modifersMatch) { features.Add("modsMatch"); } else if (noTheModifiersMatch) { features.Add("nonTheModsMatch"); } else { features.Add("modsMisMatch"); } } if (titleMatch) { features.Add("titleMatch"); } return features; } private string MentionString(Mention.MentionContext entityContext) { var output = new StringBuilder(); object[] mentionTokens = entityContext.Tokens; output.Append(mentionTokens[0].ToString()); for (int tokenIndex = 1; tokenIndex < mentionTokens.Length; tokenIndex++) { string token = mentionTokens[tokenIndex].ToString(); output.Append(" ").Append(token); } return output.ToString(); } private string ExcludedTheMentionString(Mention.MentionContext entityContext) { var output = new StringBuilder(); bool first = true; object[] mentionTokens = entityContext.Tokens; foreach (object tokenObj in mentionTokens) { string token = tokenObj.ToString(); if (token != "the" && token != "The" && token != "THE") { if (!first) { output.Append(" "); } output.Append(token); first = false; } } return output.ToString(); } private string ExcludedHonorificMentionString(Mention.MentionContext entityContext) { var output = new System.Text.StringBuilder(); bool first = true; object[] mentionTokens = entityContext.Tokens; for (int tokenIndex = 0; tokenIndex < mentionTokens.Length; tokenIndex++) { string token = mentionTokens[tokenIndex].ToString(); if (Linker.HonorificsPattern.Match(token).Value != token) { if (!first) { output.Append(" "); } output.Append(token); first = false; } } return output.ToString(); } private string ExcludedDeterminerMentionString(Mention.MentionContext entityContext) { var output = new StringBuilder(); bool first = true; Mention.IParse[] mentionTokenParses = entityContext.TokenParses; for (int tokenIndex = 0; tokenIndex < mentionTokenParses.Length; tokenIndex++) { Mention.IParse token = mentionTokenParses[tokenIndex]; string tag = token.SyntacticType; if (tag != PartsOfSpeech.Determiner) { if (!first) { output.Append(" "); } output.Append(token.ToString()); first = false; } } return output.ToString(); } private string GetExactMatchFeature(Mention.MentionContext entityContext, Mention.MentionContext compareContext) { if (MentionString(entityContext).Equals(MentionString(compareContext))) { return "exactMatch"; } else if (ExcludedHonorificMentionString(entityContext).Equals(ExcludedHonorificMentionString(compareContext))) { return "exactMatchNoHonor"; } else if (ExcludedTheMentionString(entityContext).Equals(ExcludedTheMentionString(compareContext))) { return "exactMatchNoThe"; } else if (ExcludedDeterminerMentionString(entityContext).Equals(ExcludedDeterminerMentionString(compareContext))) { return "exactMatchNoDT"; } return null; } /// <summary> /// Returns a list of word features for the specified tokens. /// </summary> /// <param name="token"> /// The token for which features are to be computed. /// </param> /// <returns> /// a list of word features for the specified tokens. /// </returns> public static List<string> GetWordFeatures(Mention.IParse token) { var wordFeatures = new List<string>(); string word = token.ToString().ToLower(); string wordFeature = string.Empty; if (EndsWithPeriod.IsMatch(word)) { wordFeature = @",endWithPeriod"; } string tokenTag = token.SyntacticType; wordFeatures.Add("w=" + word + ",t=" + tokenTag + wordFeature); wordFeatures.Add("t=" + tokenTag + wordFeature); return wordFeatures; } } }
using System; using System.Collections.Generic; using NUnit.Framework; using NServiceKit.Common.Extensions; namespace NServiceKit.Redis.Tests { [TestFixture] public class RedisClientHashTests : RedisClientTestsBase { private const string HashId = "rchtesthash"; Dictionary<string, string> stringMap; Dictionary<string, int> stringIntMap; public override void OnBeforeEachTest() { base.OnBeforeEachTest(); stringMap = new Dictionary<string, string> { {"one","a"}, {"two","b"}, {"three","c"}, {"four","d"} }; stringIntMap = new Dictionary<string, int> { {"one",1}, {"two",2}, {"three",3}, {"four",4} }; } public override void TearDown() { CleanMask = HashId + "*"; base.TearDown(); } [Test] public void Can_SetItemInHash_and_GetAllFromHash() { stringMap.ForEach(x => Redis.SetEntryInHash(HashId, x.Key, x.Value)); var members = Redis.GetAllEntriesFromHash(HashId); Assert.That(members, Is.EquivalentTo(stringMap)); } [Test] public void Can_RemoveFromHash() { const string removeMember = "two"; stringMap.ForEach(x => Redis.SetEntryInHash(HashId, x.Key, x.Value)); Redis.RemoveEntryFromHash(HashId, removeMember); stringMap.Remove(removeMember); var members = Redis.GetAllEntriesFromHash(HashId); Assert.That(members, Is.EquivalentTo(stringMap)); } [Test] public void Can_GetItemFromHash() { stringMap.ForEach(x => Redis.SetEntryInHash(HashId, x.Key, x.Value)); var hashValue = Redis.GetValueFromHash(HashId, "two"); Assert.That(hashValue, Is.EqualTo(stringMap["two"])); } [Test] public void Can_GetHashCount() { stringMap.ForEach(x => Redis.SetEntryInHash(HashId, x.Key, x.Value)); var hashCount = Redis.GetHashCount(HashId); Assert.That(hashCount, Is.EqualTo(stringMap.Count)); } [Test] public void Does_HashContainsKey() { const string existingMember = "two"; const string nonExistingMember = "five"; stringMap.ForEach(x => Redis.SetEntryInHash(HashId, x.Key, x.Value)); Assert.That(Redis.HashContainsEntry(HashId, existingMember), Is.True); Assert.That(Redis.HashContainsEntry(HashId, nonExistingMember), Is.False); } [Test] public void Can_GetHashKeys() { stringMap.ForEach(x => Redis.SetEntryInHash(HashId, x.Key, x.Value)); var expectedKeys = stringMap.ConvertAll(x => x.Key); var hashKeys = Redis.GetHashKeys(HashId); Assert.That(hashKeys, Is.EquivalentTo(expectedKeys)); } [Test] public void Can_GetHashValues() { stringMap.ForEach(x => Redis.SetEntryInHash(HashId, x.Key, x.Value)); var expectedValues = stringMap.ConvertAll(x => x.Value); var hashValues = Redis.GetHashValues(HashId); Assert.That(hashValues, Is.EquivalentTo(expectedValues)); } [Test] public void Can_enumerate_small_IDictionary_Hash() { stringMap.ForEach(x => Redis.SetEntryInHash(HashId, x.Key, x.Value)); var members = new List<string>(); foreach (var item in Redis.Hashes[HashId]) { Assert.That(stringMap.ContainsKey(item.Key), Is.True); members.Add(item.Key); } Assert.That(members.Count, Is.EqualTo(stringMap.Count)); } [Test] public void Can_Add_to_IDictionary_Hash() { var hash = Redis.Hashes[HashId]; stringMap.ForEach(x => hash.Add(x)); var members = Redis.GetAllEntriesFromHash(HashId); Assert.That(members, Is.EquivalentTo(stringMap)); } [Test] public void Can_Clear_IDictionary_Hash() { var hash = Redis.Hashes[HashId]; stringMap.ForEach(x => hash.Add(x)); Assert.That(hash.Count, Is.EqualTo(stringMap.Count)); hash.Clear(); Assert.That(hash.Count, Is.EqualTo(0)); } [Test] public void Can_Test_Contains_in_IDictionary_Hash() { var hash = Redis.Hashes[HashId]; stringMap.ForEach(x => hash.Add(x)); Assert.That(hash.ContainsKey("two"), Is.True); Assert.That(hash.ContainsKey("five"), Is.False); } [Test] public void Can_Remove_value_from_IDictionary_Hash() { var hash = Redis.Hashes[HashId]; stringMap.ForEach(x => hash.Add(x)); stringMap.Remove("two"); hash.Remove("two"); var members = Redis.GetAllEntriesFromHash(HashId); Assert.That(members, Is.EquivalentTo(stringMap)); } private static Dictionary<string, string> ToStringMap(Dictionary<string, int> stringIntMap) { var map = new Dictionary<string, string>(); foreach (var kvp in stringIntMap) { map[kvp.Key] = kvp.Value.ToString(); } return map; } [Test] public void Can_increment_Hash_field() { var hash = Redis.Hashes[HashId]; stringIntMap.ForEach(x => hash.Add(x.Key, x.Value.ToString())); stringIntMap["two"] += 10; Redis.IncrementValueInHash(HashId, "two", 10); var members = Redis.GetAllEntriesFromHash(HashId); Assert.That(members, Is.EquivalentTo(ToStringMap(stringIntMap))); } [Test] public void Can_increment_Hash_field_beyond_32_bits() { Redis.SetEntryInHash(HashId, "int", Int32.MaxValue.ToString()); Redis.IncrementValueInHash(HashId, "int", 1); long actual = Int64.Parse(Redis.GetValueFromHash(HashId, "int")); long expected = Int32.MaxValue + 1L; Assert.That(actual, Is.EqualTo(expected)); } [Test] public void Can_SetItemInHashIfNotExists() { stringMap.ForEach(x => Redis.SetEntryInHash(HashId, x.Key, x.Value)); Redis.SetEntryInHashIfNotExists(HashId, "two", "did not change existing item"); Redis.SetEntryInHashIfNotExists(HashId, "five", "changed non existing item"); stringMap["five"] = "changed non existing item"; var members = Redis.GetAllEntriesFromHash(HashId); Assert.That(members, Is.EquivalentTo(stringMap)); } [Test] public void Can_SetRangeInHash() { var newStringMap = new Dictionary<string, string> { {"five","e"}, {"six","f"}, {"seven","g"} }; stringMap.ForEach(x => Redis.SetEntryInHash(HashId, x.Key, x.Value)); Redis.SetRangeInHash(HashId, newStringMap); newStringMap.ForEach(x => stringMap.Add(x.Key, x.Value)); var members = Redis.GetAllEntriesFromHash(HashId); Assert.That(members, Is.EquivalentTo(stringMap)); } [Test] public void Can_GetItemsFromHash() { stringMap.ForEach(x => Redis.SetEntryInHash(HashId, x.Key, x.Value)); var expectedValues = new List<string> { stringMap["one"], stringMap["two"], null }; var hashValues = Redis.GetValuesFromHash(HashId, "one", "two", "not-exists"); Assert.That(hashValues.EquivalentTo(expectedValues), Is.True); } [Test] public void Can_hash_set() { var key = HashId + "key"; var field = GetBytes("foo"); var value = GetBytes("value"); Assert.AreEqual(Redis.HDel(key, field),0); Assert.AreEqual(Redis.HSet(key, field, value),1); Assert.AreEqual(Redis.HDel(key, field),1); } [Test] public void Can_hash_multi_set_and_get() { const string Key = HashId + "multitest"; Assert.That(Redis.GetValue(Key), Is.Null); var fields = new Dictionary<string,string> { {"field1", "1"},{"field2","2"}, {"field3","3"} }; Redis.SetRangeInHash(Key, fields); var members = Redis.GetAllEntriesFromHash(Key); foreach (var member in members) { Assert.IsTrue(fields.ContainsKey(member.Key)); Assert.AreEqual(fields[member.Key], member.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.IO; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel.Channels { /// <summary> /// This class is based on BufferedStream from the Desktop version of .Net. Only the write functionality /// is needed by WCF so the read capability has been removed. This allowed some extra logic to be removed /// from the write code path. Also some validation code has been removed as this class is no longer /// general purpose and is only used in pre-known scenarios and only called by WCF code. Some validation /// checks have been converted to only run on a debug build to allow catching code bugs in other WCF code, /// but not causing release build overhead. /// /// One of the design goals here is to prevent the buffer from getting in the way and slowing /// down underlying stream accesses when it is not needed. /// See a large comment in Write for the details of the write buffer heuristic. /// /// This class will never cache more bytes than the max specified buffer size. /// However, it may use a temporary buffer of up to twice the size in order to combine several IO operations on /// the underlying stream into a single operation. This is because we assume that memory copies are significantly /// faster than IO operations on the underlying stream (if this was not true, using buffering is never appropriate). /// The max size of this "shadow" buffer is limited as to not allocate it on the LOH. /// Shadowing is always transient. Even when using this technique, this class still guarantees that the number of /// bytes cached (not yet written to the target stream or not yet consumed by the user) is never larger than the /// actual specified buffer size. /// </summary> internal sealed class BufferedWriteStream : Stream { public const int DefaultBufferSize = 8192; private Stream _stream; // Underlying stream. Close sets _stream to null. private BufferManager _bufferManager; private byte[] _buffer; // Write buffer. private readonly int _bufferSize; // Length of internal buffer (not counting the shadow buffer). private int _writePos; // Write pointer within buffer. private readonly SemaphoreSlim _sem = new SemaphoreSlim(1, 1); public BufferedWriteStream(Stream stream) : this(stream, null, DefaultBufferSize) { } public BufferedWriteStream(Stream stream, BufferManager bufferManager) : this(stream, bufferManager, DefaultBufferSize) { } public BufferedWriteStream(Stream stream, BufferManager bufferManager, int bufferSize) { Contract.Assert(stream != Null, "stream != Stream.Null"); Contract.Assert(stream != null, "stream != null"); Contract.Assert(bufferSize > 0, "bufferSize > 0"); Contract.Assert(stream.CanWrite); _stream = stream; _bufferManager = bufferManager; _bufferSize = bufferSize; EnsureBufferAllocated(); } private void EnsureNotClosed() { if (_stream == null) { throw new ObjectDisposedException(nameof(BufferedWriteStream)); } } private void EnsureCanWrite() { Contract.Assert(_stream != null); Contract.Assert(_stream.CanWrite); } /// <summary><code>MaxShadowBufferSize</code> is chosen such that shadow buffers are not allocated on the Large Object Heap. /// Currently, an object is allocated on the LOH if it is larger than 85000 bytes. /// We will go with exactly 80 KBytes, although this is somewhat arbitrary.</summary> private const int MaxShadowBufferSize = 81920; // Make sure not to get to the Large Object Heap. private void EnsureShadowBufferAllocated() { Contract.Assert(_buffer != null); Contract.Assert(_bufferSize > 0); // Already have shadow buffer? if (_buffer.Length != _bufferSize || _bufferSize >= MaxShadowBufferSize) { return; } byte[] shadowBuffer = new byte[Math.Min(_bufferSize + _bufferSize, MaxShadowBufferSize)]; Array.Copy(_buffer, 0, shadowBuffer, 0, _writePos); _buffer = shadowBuffer; } private void EnsureBufferAllocated() { if (_buffer == null) { if (_bufferManager != null) { _buffer = _bufferManager.TakeBuffer(_bufferSize); } else { _buffer = new byte[_bufferSize]; } } } public override bool CanRead { get { return false; } } public override bool CanWrite { get { return _stream != null && _stream.CanWrite; } } public override bool CanSeek { get { return false; } } public override long Length { get { throw new NotSupportedException(nameof(Length)); } } public override long Position { get { throw new NotSupportedException(nameof(Position)); } set { throw new NotSupportedException(nameof(Position)); } } protected override void Dispose(bool disposing) { if (disposing) { try { _stream?.Dispose(); } finally { _stream = null; var tempBuffer = _buffer; _buffer = null; _bufferManager?.ReturnBuffer(tempBuffer); _bufferManager = null; } } // Call base.Dispose(bool) to cleanup async IO resources base.Dispose(disposing); } public override void Flush() { EnsureNotClosed(); // Has WRITE data in the buffer: if (_writePos > 0) { FlushWrite(); Contract.Assert(_writePos == 0); return; } // We had no data in the buffer, but we still need to tell the underlying stream to flush. _stream.Flush(); } public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } EnsureNotClosed(); return FlushAsyncInternal(cancellationToken); } private async Task FlushAsyncInternal(CancellationToken cancellationToken) { await _sem.WaitAsync().ConfigureAwait(false); try { if (_writePos > 0) { await FlushWriteAsync(cancellationToken).ConfigureAwait(false); Contract.Assert(_writePos == 0); return; } // We had no data in the buffer, but we still need to tell the underlying stream to flush. await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); // There was nothing in the buffer: Contract.Assert(_writePos == 0); } finally { _sem.Release(); } } private void FlushWrite() { Contract.Assert(_buffer != null && _bufferSize >= _writePos, "BufferedWriteStream: Write buffer must be allocated and write position must be in the bounds of the buffer in FlushWrite!"); _stream.Write(_buffer, 0, _writePos); _writePos = 0; _stream.Flush(); } private async Task FlushWriteAsync(CancellationToken cancellationToken) { Contract.Assert(_buffer != null && _bufferSize >= _writePos, "BufferedWriteStream: Write buffer must be allocated and write position must be in the bounds of the buffer in FlushWrite!"); await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false); _writePos = 0; await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); } public override int Read(byte[] array, int offset, int count) { throw new NotSupportedException(nameof(Read)); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { throw new NotSupportedException(nameof(ReadAsync)); } public override int ReadByte() { throw new NotSupportedException(nameof(ReadByte)); } private void WriteToBuffer(byte[] array, ref int offset, ref int count) { int bytesToWrite = Math.Min(_bufferSize - _writePos, count); if (bytesToWrite <= 0) { return; } Array.Copy(array, offset, _buffer, _writePos, bytesToWrite); _writePos += bytesToWrite; count -= bytesToWrite; offset += bytesToWrite; } private void WriteToBuffer(byte[] array, ref int offset, ref int count, out Exception error) { try { error = null; WriteToBuffer(array, ref offset, ref count); } catch (Exception ex) { error = ex; } } public override void Write(byte[] array, int offset, int count) { Contract.Assert(array != null); Contract.Assert(offset >= 0); Contract.Assert(count >= 0); Contract.Assert(count <= array.Length - offset); EnsureNotClosed(); EnsureCanWrite(); #region Write algorithm comment // We need to use the buffer, while avoiding unnecessary buffer usage / memory copies. // We ASSUME that memory copies are much cheaper than writes to the underlying stream, so if an extra copy is // guaranteed to reduce the number of writes, we prefer it. // We pick a simple strategy that makes degenerate cases rare if our assumptions are right. // // For every write, we use a simple heuristic (below) to decide whether to use the buffer. // The heuristic has the desirable property (*) that if the specified user data can fit into the currently available // buffer space without filling it up completely, the heuristic will always tell us to use the buffer. It will also // tell us to use the buffer in cases where the current write would fill the buffer, but the remaining data is small // enough such that subsequent operations can use the buffer again. // // Algorithm: // Determine whether or not to buffer according to the heuristic (below). // If we decided to use the buffer: // Copy as much user data as we can into the buffer. // If we consumed all data: We are finished. // Otherwise, write the buffer out. // Copy the rest of user data into the now cleared buffer (no need to write out the buffer again as the heuristic // will prevent it from being filled twice). // If we decided not to use the buffer: // Can the data already in the buffer and current user data be combines to a single write // by allocating a "shadow" buffer of up to twice the size of _bufferSize (up to a limit to avoid LOH)? // Yes, it can: // Allocate a larger "shadow" buffer and ensure the buffered data is moved there. // Copy user data to the shadow buffer. // Write shadow buffer to the underlying stream in a single operation. // No, it cannot (amount of data is still too large): // Write out any data possibly in the buffer. // Write out user data directly. // // Heuristic: // If the subsequent write operation that follows the current write operation will result in a write to the // underlying stream in case that we use the buffer in the current write, while it would not have if we avoided // using the buffer in the current write (by writing current user data to the underlying stream directly), then we // prefer to avoid using the buffer since the corresponding memory copy is wasted (it will not reduce the number // of writes to the underlying stream, which is what we are optimising for). // ASSUME that the next write will be for the same amount of bytes as the current write (most common case) and // determine if it will cause a write to the underlying stream. If the next write is actually larger, our heuristic // still yields the right behaviour, if the next write is actually smaller, we may making an unnecessary write to // the underlying stream. However, this can only occur if the current write is larger than half the buffer size and // we will recover after one iteration. // We have: // useBuffer = (_writePos + count + count < _bufferSize + _bufferSize) // // Example with _bufferSize = 20, _writePos = 6, count = 10: // // +---------------------------------------+---------------------------------------+ // | current buffer | next iteration's "future" buffer | // +---------------------------------------+---------------------------------------+ // |0| | | | | | | | | |1| | | | | | | | | |2| | | | | | | | | |3| | | | | | | | | | // |0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9| // +-----------+-------------------+-------------------+---------------------------+ // | _writePos | current count | assumed next count|avail buff after next write| // +-----------+-------------------+-------------------+---------------------------+ // // A nice property (*) of this heuristic is that it will always succeed if the user data completely fits into the // available buffer, i.e. if count < (_bufferSize - _writePos). #endregion Write algorithm comment Contract.Assert(_writePos < _bufferSize); int totalUserBytes; bool useBuffer; checked { // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early: totalUserBytes = _writePos + count; useBuffer = (totalUserBytes + count < (_bufferSize + _bufferSize)); } if (useBuffer) { WriteToBuffer(array, ref offset, ref count); if (_writePos < _bufferSize) { Contract.Assert(count == 0); return; } Contract.Assert(count >= 0); Contract.Assert(_writePos == _bufferSize); Contract.Assert(_buffer != null); _stream.Write(_buffer, 0, _writePos); _writePos = 0; WriteToBuffer(array, ref offset, ref count); Contract.Assert(count == 0); Contract.Assert(_writePos < _bufferSize); } else { // if (!useBuffer) // Write out the buffer if necessary. if (_writePos > 0) { Contract.Assert(_buffer != null); Contract.Assert(totalUserBytes >= _bufferSize); // Try avoiding extra write to underlying stream by combining previously buffered data with current user data: if (totalUserBytes <= (_bufferSize + _bufferSize) && totalUserBytes <= MaxShadowBufferSize) { EnsureShadowBufferAllocated(); Array.Copy(array, offset, _buffer, _writePos, count); _stream.Write(_buffer, 0, totalUserBytes); _writePos = 0; return; } _stream.Write(_buffer, 0, _writePos); _writePos = 0; } // Write out user data. _stream.Write(array, offset, count); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Contract.Assert(buffer != null); Contract.Assert(offset >= 0); Contract.Assert(count >= 0); Contract.Assert(count <= buffer.Length - offset); // Fast path check for cancellation already requested if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } EnsureNotClosed(); EnsureCanWrite(); // Try to satisfy the request from the buffer synchronously. But still need a sem-lock in case that another // Async IO Task accesses the buffer concurrently. If we fail to acquire the lock without waiting, make this // an Async operation. Task semaphoreLockTask = _sem.WaitAsync(cancellationToken); if (semaphoreLockTask.Status == TaskStatus.RanToCompletion) { bool completeSynchronously = true; try { Contract.Assert(_writePos < _bufferSize); // If the write completely fits into the buffer, we can complete synchronously: completeSynchronously = (count < _bufferSize - _writePos); if (completeSynchronously) { Exception error; WriteToBuffer(buffer, ref offset, ref count, out error); Contract.Assert(count == 0); return (error == null) ? Task.CompletedTask : Task.FromException(error); } } finally { if (completeSynchronously) { // if this is FALSE, we will be entering WriteToUnderlyingStreamAsync and releasing there. _sem.Release(); } } } // Delegate to the async implementation. return WriteToUnderlyingStreamAsync(buffer, offset, count, cancellationToken, semaphoreLockTask); } private async Task WriteToUnderlyingStreamAsync(byte[] array, int offset, int count, CancellationToken cancellationToken, Task semaphoreLockTask) { EnsureNotClosed(); EnsureCanWrite(); // See the LARGE COMMENT in Write(..) for the explanation of the write buffer algorithm. await semaphoreLockTask.ConfigureAwait(false); try { // The buffer might have been changed by another async task while we were waiting on the semaphore. // However, note that if we recalculate the sync completion condition to TRUE, then useBuffer will also be TRUE. int totalUserBytes; bool useBuffer; checked { // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early: totalUserBytes = _writePos + count; useBuffer = (totalUserBytes + count < (_bufferSize + _bufferSize)); } if (useBuffer) { WriteToBuffer(array, ref offset, ref count); if (_writePos < _bufferSize) { Contract.Assert(count == 0); return; } Contract.Assert(count >= 0); Contract.Assert(_writePos == _bufferSize); Contract.Assert(_buffer != null); await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false); _writePos = 0; WriteToBuffer(array, ref offset, ref count); Contract.Assert(count == 0); Contract.Assert(_writePos < _bufferSize); } else { // if (!useBuffer) // Write out the buffer if necessary. if (_writePos > 0) { Contract.Assert(_buffer != null); Contract.Assert(totalUserBytes >= _bufferSize); // Try avoiding extra write to underlying stream by combining previously buffered data with current user data: if (totalUserBytes <= (_bufferSize + _bufferSize) && totalUserBytes <= MaxShadowBufferSize) { EnsureShadowBufferAllocated(); Buffer.BlockCopy(array, offset, _buffer, _writePos, count); await _stream.WriteAsync(_buffer, 0, totalUserBytes, cancellationToken).ConfigureAwait(false); _writePos = 0; return; } await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false); _writePos = 0; } // Write out user data. await _stream.WriteAsync(array, offset, count, cancellationToken).ConfigureAwait(false); } } finally { _sem.Release(); } } public override void WriteByte(byte value) { EnsureNotClosed(); // We should not be flushing here, but only writing to the underlying stream, but previous version flushed, so we keep this. if (_writePos >= _bufferSize - 1) { FlushWrite(); } _buffer[_writePos++] = value; Contract.Assert(_writePos < _bufferSize); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(nameof(Seek)); } public override void SetLength(long value) { throw new NotSupportedException(nameof(SetLength)); } } }
using Content.Shared.Chemistry.Components; using Content.Shared.FixedPoint; using Robust.Shared.IoC; using Robust.Shared.Prototypes; using NUnit.Framework; namespace Content.Tests.Shared.Chemistry; [TestFixture, Parallelizable, TestOf(typeof(Solution))] public sealed class Solution_Tests : ContentUnitTest { [OneTimeSetUp] public void Setup() { IoCManager.Resolve<IPrototypeManager>().Initialize(); } [Test] public void AddReagentAndGetSolution() { var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(1000)); var quantity = solution.GetReagentQuantity("water"); Assert.That(quantity.Int(), Is.EqualTo(1000)); } [Test] public void ConstructorAddReagent() { var solution = new Solution("water", FixedPoint2.New(1000)); var quantity = solution.GetReagentQuantity("water"); Assert.That(quantity.Int(), Is.EqualTo(1000)); } [Test] public void NonExistingReagentReturnsZero() { var solution = new Solution(); var quantity = solution.GetReagentQuantity("water"); Assert.That(quantity.Int(), Is.EqualTo(0)); } [Test] public void AddLessThanZeroReagentReturnsZero() { var solution = new Solution("water", FixedPoint2.New(-1000)); var quantity = solution.GetReagentQuantity("water"); Assert.That(quantity.Int(), Is.EqualTo(0)); } [Test] public void AddingReagentsSumsProperly() { var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(1000)); solution.AddReagent("water", FixedPoint2.New(2000)); var quantity = solution.GetReagentQuantity("water"); Assert.That(quantity.Int(), Is.EqualTo(3000)); } [Test] public void ReagentQuantitiesStayUnique() { var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(1000)); solution.AddReagent("fire", FixedPoint2.New(2000)); Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(1000)); Assert.That(solution.GetReagentQuantity("fire").Int(), Is.EqualTo(2000)); } [Test] public void TotalVolumeIsCorrect() { var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(1000)); solution.AddReagent("fire", FixedPoint2.New(2000)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(3000)); } [Test] public void CloningSolutionIsCorrect() { var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(1000)); solution.AddReagent("fire", FixedPoint2.New(2000)); var newSolution = solution.Clone(); Assert.That(newSolution.GetReagentQuantity("water").Int(), Is.EqualTo(1000)); Assert.That(newSolution.GetReagentQuantity("fire").Int(), Is.EqualTo(2000)); Assert.That(newSolution.TotalVolume.Int(), Is.EqualTo(3000)); } [Test] public void RemoveSolutionRecalculatesProperly() { var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(1000)); solution.AddReagent("fire", FixedPoint2.New(2000)); solution.RemoveReagent("water", FixedPoint2.New(500)); Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(500)); Assert.That(solution.GetReagentQuantity("fire").Int(), Is.EqualTo(2000)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(2500)); } [Test] public void RemoveLessThanOneQuantityDoesNothing() { var solution = new Solution("water", FixedPoint2.New(100)); solution.RemoveReagent("water", FixedPoint2.New(-100)); Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(100)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(100)); } [Test] public void RemoveMoreThanTotalRemovesAllReagent() { var solution = new Solution("water", FixedPoint2.New(100)); solution.RemoveReagent("water", FixedPoint2.New(1000)); Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(0)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(0)); } [Test] public void RemoveNonExistReagentDoesNothing() { var solution = new Solution("water", FixedPoint2.New(100)); solution.RemoveReagent("fire", FixedPoint2.New(1000)); Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(100)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(100)); } [Test] public void RemoveSolution() { var solution = new Solution("water", FixedPoint2.New(700)); solution.RemoveSolution(FixedPoint2.New(500)); //Check that edited solution is correct Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(200)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(200)); } [Test] public void RemoveSolutionMoreThanTotalRemovesAll() { var solution = new Solution("water", FixedPoint2.New(800)); solution.RemoveSolution(FixedPoint2.New(1000)); //Check that edited solution is correct Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(0)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(0)); } [Test] public void RemoveSolutionRatioPreserved() { var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(1000)); solution.AddReagent("fire", FixedPoint2.New(2000)); solution.RemoveSolution(FixedPoint2.New(1500)); Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(500)); Assert.That(solution.GetReagentQuantity("fire").Int(), Is.EqualTo(1000)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(1500)); } [Test] public void RemoveSolutionLessThanOneDoesNothing() { var solution = new Solution("water", FixedPoint2.New(800)); solution.RemoveSolution(FixedPoint2.New(-200)); Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(800)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(800)); } [Test] public void SplitSolution() { var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(1000)); solution.AddReagent("fire", FixedPoint2.New(2000)); var splitSolution = solution.SplitSolution(FixedPoint2.New(750)); Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(750)); Assert.That(solution.GetReagentQuantity("fire").Int(), Is.EqualTo(1500)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(2250)); Assert.That(splitSolution.GetReagentQuantity("water").Int(), Is.EqualTo(250)); Assert.That(splitSolution.GetReagentQuantity("fire").Int(), Is.EqualTo(500)); Assert.That(splitSolution.TotalVolume.Int(), Is.EqualTo(750)); } [Test] public void SplitSolutionFractional() { var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(1)); solution.AddReagent("fire", FixedPoint2.New(2)); var splitSolution = solution.SplitSolution(FixedPoint2.New(1)); Assert.That(solution.GetReagentQuantity("water").Float(), Is.EqualTo(0.67f)); Assert.That(solution.GetReagentQuantity("fire").Float(), Is.EqualTo(1.33f)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(2)); Assert.That(splitSolution.GetReagentQuantity("water").Float(), Is.EqualTo(0.33f)); Assert.That(splitSolution.GetReagentQuantity("fire").Float(), Is.EqualTo(0.67f)); Assert.That(splitSolution.TotalVolume.Int(), Is.EqualTo(1)); } [Test] public void SplitSolutionFractionalOpposite() { var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(1)); solution.AddReagent("fire", FixedPoint2.New(2)); var splitSolution = solution.SplitSolution(FixedPoint2.New(2)); Assert.That(solution.GetReagentQuantity("water").Float(), Is.EqualTo(0.33f)); Assert.That(solution.GetReagentQuantity("fire").Float(), Is.EqualTo(0.67f)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(1)); Assert.That(splitSolution.GetReagentQuantity("water").Float(), Is.EqualTo(0.67f)); Assert.That(splitSolution.GetReagentQuantity("fire").Float(), Is.EqualTo(1.33f)); Assert.That(splitSolution.TotalVolume.Int(), Is.EqualTo(2)); } [Test] [TestCase(0.03f, 0.01f, 0.02f)] [TestCase(0.03f, 0.02f, 0.01f)] public void SplitSolutionTinyFractionalBigSmall(float initial, float reduce, float remainder) { var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(initial)); var splitSolution = solution.SplitSolution(FixedPoint2.New(reduce)); Assert.That(solution.GetReagentQuantity("water").Float(), Is.EqualTo(remainder)); Assert.That(solution.TotalVolume.Float(), Is.EqualTo(remainder)); Assert.That(splitSolution.GetReagentQuantity("water").Float(), Is.EqualTo(reduce)); Assert.That(splitSolution.TotalVolume.Float(), Is.EqualTo(reduce)); } [Test] [TestCase(2)] [TestCase(10)] [TestCase(100)] [TestCase(1000)] public void SplitRounding(int amount) { var solutionOne = new Solution(); solutionOne.AddReagent("foo", FixedPoint2.New(amount)); solutionOne.AddReagent("bar", FixedPoint2.New(amount)); solutionOne.AddReagent("baz", FixedPoint2.New(amount)); var splitAmount = FixedPoint2.New(5); var split = solutionOne.SplitSolution(splitAmount); Assert.That(split.TotalVolume, Is.EqualTo(splitAmount)); } [Test] public void SplitSolutionMoreThanTotalRemovesAll() { var solution = new Solution("water", FixedPoint2.New(800)); var splitSolution = solution.SplitSolution(FixedPoint2.New(1000)); Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(0)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(0)); Assert.That(splitSolution.GetReagentQuantity("water").Int(), Is.EqualTo(800)); Assert.That(splitSolution.TotalVolume.Int(), Is.EqualTo(800)); } [Test] public void SplitSolutionLessThanOneDoesNothing() { var solution = new Solution("water", FixedPoint2.New(800)); var splitSolution = solution.SplitSolution(FixedPoint2.New(-200)); Assert.That(solution.GetReagentQuantity("water").Int(), Is.EqualTo(800)); Assert.That(solution.TotalVolume.Int(), Is.EqualTo(800)); Assert.That(splitSolution.GetReagentQuantity("water").Int(), Is.EqualTo(0)); Assert.That(splitSolution.TotalVolume.Int(), Is.EqualTo(0)); } [Test] public void SplitSolutionZero() { var solution = new Solution(); solution.AddReagent("Impedrezene", FixedPoint2.New(0.01 + 0.19)); solution.AddReagent("Thermite", FixedPoint2.New(0.01 + 0.39)); solution.AddReagent("Li", FixedPoint2.New(0.01 + 0.17)); solution.AddReagent("F", FixedPoint2.New(0.01 + 0.17)); solution.AddReagent("Na", FixedPoint2.New(0 + 0.13)); solution.AddReagent("Hg", FixedPoint2.New(0.15 + 4.15)); solution.AddReagent("Cu", FixedPoint2.New(0 + 0.13)); solution.AddReagent("U", FixedPoint2.New(0.76 + 20.77)); solution.AddReagent("Fe", FixedPoint2.New(0.01 + 0.36)); solution.AddReagent("SpaceDrugs", FixedPoint2.New(0.02 + 0.41)); solution.AddReagent("Al", FixedPoint2.New(0)); solution.AddReagent("Glucose", FixedPoint2.New(0)); solution.AddReagent("O", FixedPoint2.New(0)); solution.SplitSolution(FixedPoint2.New(0.98)); } [Test] public void AddSolution() { var solutionOne = new Solution(); solutionOne.AddReagent("water", FixedPoint2.New(1000)); solutionOne.AddReagent("fire", FixedPoint2.New(2000)); var solutionTwo = new Solution(); solutionTwo.AddReagent("water", FixedPoint2.New(500)); solutionTwo.AddReagent("earth", FixedPoint2.New(1000)); solutionOne.AddSolution(solutionTwo); Assert.That(solutionOne.GetReagentQuantity("water").Int(), Is.EqualTo(1500)); Assert.That(solutionOne.GetReagentQuantity("fire").Int(), Is.EqualTo(2000)); Assert.That(solutionOne.GetReagentQuantity("earth").Int(), Is.EqualTo(1000)); Assert.That(solutionOne.TotalVolume.Int(), Is.EqualTo(4500)); } // Tests concerning thermal energy and temperature. #region Thermal Energy and Temperature [Test] public void EmptySolutionHasNoHeatCapacity() { var solution = new Solution(); Assert.That(solution.HeatCapacity, Is.EqualTo(0.0f)); } [Test] public void EmptySolutionHasNoThermalEnergy() { var solution = new Solution(); Assert.That(solution.ThermalEnergy, Is.EqualTo(0.0f)); } [Test] public void AddReagentToEmptySolutionSetsTemperature() { const float testTemp = 100.0f; var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(100), testTemp); Assert.That(solution.Temperature, Is.EqualTo(testTemp)); } [Test] public void AddReagentWithNullTemperatureDoesNotEffectTemperature() { const float initialTemp = 100.0f; var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(100), initialTemp); solution.AddReagent("water", FixedPoint2.New(100)); Assert.That(solution.Temperature, Is.EqualTo(initialTemp)); solution.AddReagent("earth", FixedPoint2.New(100)); Assert.That(solution.Temperature, Is.EqualTo(initialTemp)); } [Test] public void AddSolutionWithEqualTemperatureDoesNotChangeTemperature() { const float initialTemp = 100.0f; var solutionOne = new Solution(); solutionOne.AddReagent("water", FixedPoint2.New(100)); solutionOne.Temperature = initialTemp; var solutionTwo = new Solution(); solutionTwo.AddReagent("water", FixedPoint2.New(100)); solutionTwo.AddReagent("earth", FixedPoint2.New(100)); solutionTwo.Temperature = initialTemp; solutionOne.AddSolution(solutionTwo); Assert.That(solutionOne.Temperature, Is.EqualTo(initialTemp)); } [Test] public void RemoveReagentDoesNotEffectTemperature() { const float initialTemp = 100.0f; var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(100), initialTemp); solution.RemoveReagent("water", FixedPoint2.New(50)); Assert.That(solution.Temperature, Is.EqualTo(initialTemp)); } [Test] public void RemoveSolutionDoesNotEffectTemperature() { const float initialTemp = 100.0f; var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(100), initialTemp); solution.RemoveSolution(FixedPoint2.New(50)); Assert.That(solution.Temperature, Is.EqualTo(initialTemp)); } [Test] public void SplitSolutionDoesNotEffectTemperature() { const float initialTemp = 100.0f; var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(100), initialTemp); solution.SplitSolution(FixedPoint2.New(50)); Assert.That(solution.Temperature, Is.EqualTo(initialTemp)); } [Test] public void AddReagentWithSetTemperatureAdjustsTemperature() { const float temp = 100.0f; var solution = new Solution(); solution.AddReagent("water", FixedPoint2.New(100), temp * 1); Assert.That(solution.Temperature, Is.EqualTo(temp * 1)); solution.AddReagent("water", FixedPoint2.New(100), temp * 3); Assert.That(solution.Temperature, Is.EqualTo(temp * 2)); solution.AddReagent("earth", FixedPoint2.New(100), temp * 5); Assert.That(solution.Temperature, Is.EqualTo(temp * 3)); } [Test] public void AddSolutionCombinesThermalEnergy() { const float initialTemp = 100.0f; var solutionOne = new Solution(); solutionOne.AddReagent("water", FixedPoint2.New(100), initialTemp); var solutionTwo = new Solution(); solutionTwo.AddReagent("water", FixedPoint2.New(100), initialTemp); solutionTwo.AddReagent("earth", FixedPoint2.New(100)); var thermalEnergyOne = solutionOne.ThermalEnergy; var thermalEnergyTwo = solutionTwo.ThermalEnergy; solutionOne.AddSolution(solutionTwo); Assert.That(solutionOne.ThermalEnergy, Is.EqualTo(thermalEnergyOne + thermalEnergyTwo)); } #endregion Thermal Energy and Temperature }
// 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.IO.Pipelines; using System.Threading; using System.Threading.Tasks; using HtcSharp.HttpModule.Core.Internal.Infrastructure; using HtcSharp.HttpModule.Http; namespace HtcSharp.HttpModule.Core.Internal.Http { // SourceTools-Start // Remote-File C:\ASP\src\Servers\Kestrel\Core\src\Internal\Http\MessageBody.cs // Start-At-Remote-Line 11 // SourceTools-End internal abstract class MessageBody { private static readonly MessageBody _zeroContentLengthClose = new ZeroContentLengthMessageBody(keepAlive: false); private static readonly MessageBody _zeroContentLengthKeepAlive = new ZeroContentLengthMessageBody(keepAlive: true); private readonly HttpProtocol _context; private bool _send100Continue = true; private long _consumedBytes; private bool _stopped; protected bool _timingEnabled; protected bool _backpressure; protected long _alreadyTimedBytes; protected long _examinedUnconsumedBytes; protected MessageBody(HttpProtocol context) { _context = context; } public static MessageBody ZeroContentLengthClose => _zeroContentLengthClose; public static MessageBody ZeroContentLengthKeepAlive => _zeroContentLengthKeepAlive; public bool RequestKeepAlive { get; protected set; } public bool RequestUpgrade { get; protected set; } public virtual bool IsEmpty => false; protected IKestrelTrace Log => _context.ServiceContext.Log; public abstract void AdvanceTo(SequencePosition consumed); public abstract void AdvanceTo(SequencePosition consumed, SequencePosition examined); public abstract bool TryRead(out ReadResult readResult); public abstract void Complete(Exception exception); public abstract void CancelPendingRead(); public abstract ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default); public virtual Task ConsumeAsync() { TryStart(); return OnConsumeAsync(); } public virtual Task StopAsync() { TryStop(); return OnStopAsync(); } protected virtual Task OnConsumeAsync() => Task.CompletedTask; protected virtual Task OnStopAsync() => Task.CompletedTask; protected void TryProduceContinue() { if (_send100Continue) { _context.HttpResponseControl.ProduceContinue(); _send100Continue = false; } } protected void TryStart() { if (_context.HasStartedConsumingRequestBody) { return; } OnReadStarting(); _context.HasStartedConsumingRequestBody = true; if (!RequestUpgrade) { Log.RequestBodyStart(_context.ConnectionIdFeature, _context.TraceIdentifier); if (_context.MinRequestBodyDataRate != null) { _timingEnabled = true; _context.TimeoutControl.StartRequestBody(_context.MinRequestBodyDataRate); } } OnReadStarted(); } protected void TryStop() { if (_stopped) { return; } _stopped = true; if (!RequestUpgrade) { Log.RequestBodyDone(_context.ConnectionIdFeature, _context.TraceIdentifier); if (_timingEnabled) { if (_backpressure) { _context.TimeoutControl.StopTimingRead(); } _context.TimeoutControl.StopRequestBody(); } } } protected virtual void OnReadStarting() { } protected virtual void OnReadStarted() { } protected virtual void OnDataRead(long bytesRead) { } protected void AddAndCheckConsumedBytes(long consumedBytes) { _consumedBytes += consumedBytes; if (_consumedBytes > _context.MaxRequestBodySize) { BadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTooLarge); } } protected ValueTask<ReadResult> StartTimingReadAsync(ValueTask<ReadResult> readAwaitable, CancellationToken cancellationToken) { if (!readAwaitable.IsCompleted && _timingEnabled) { TryProduceContinue(); _backpressure = true; _context.TimeoutControl.StartTimingRead(); } return readAwaitable; } protected void CountBytesRead(long bytesInReadResult) { var numFirstSeenBytes = bytesInReadResult - _alreadyTimedBytes; if (numFirstSeenBytes > 0) { _context.TimeoutControl.BytesRead(numFirstSeenBytes); } } protected void StopTimingRead(long bytesInReadResult) { CountBytesRead(bytesInReadResult); if (_backpressure) { _backpressure = false; _context.TimeoutControl.StopTimingRead(); } } protected long OnAdvance(ReadResult readResult, SequencePosition consumed, SequencePosition examined) { // This code path is fairly hard to understand so let's break it down with an example // ReadAsync returns a ReadResult of length 50. // Advance(25, 40). The examined length would be 40 and consumed length would be 25. // _totalExaminedInPreviousReadResult starts at 0. newlyExamined is 40. // OnDataRead is called with length 40. // _totalExaminedInPreviousReadResult is now 40 - 25 = 15. // The next call to ReadAsync returns 50 again // Advance(5, 5) is called // newlyExamined is 5 - 15, or -10. // Update _totalExaminedInPreviousReadResult to 10 as we consumed 5. // The next call to ReadAsync returns 50 again // _totalExaminedInPreviousReadResult is 10 // Advance(50, 50) is called // newlyExamined = 50 - 10 = 40 // _totalExaminedInPreviousReadResult is now 50 // _totalExaminedInPreviousReadResult is finally 0 after subtracting consumedLength. long examinedLength, consumedLength, totalLength; if (consumed.Equals(examined)) { examinedLength = readResult.Buffer.Slice(readResult.Buffer.Start, examined).Length; consumedLength = examinedLength; } else { consumedLength = readResult.Buffer.Slice(readResult.Buffer.Start, consumed).Length; examinedLength = consumedLength + readResult.Buffer.Slice(consumed, examined).Length; } if (examined.Equals(readResult.Buffer.End)) { totalLength = examinedLength; } else { totalLength = readResult.Buffer.Length; } var newlyExamined = examinedLength - _examinedUnconsumedBytes; if (newlyExamined > 0) { OnDataRead(newlyExamined); _examinedUnconsumedBytes += newlyExamined; } _examinedUnconsumedBytes -= consumedLength; _alreadyTimedBytes = totalLength - consumedLength; return newlyExamined; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.Xml.Serialization; using System.Security; using System.Runtime.CompilerServices; #if !uapaot using ExtensionDataObject = System.Object; #endif namespace System.Runtime.Serialization { #if USE_REFEMIT || uapaot public class XmlObjectSerializerWriteContext : XmlObjectSerializerContext #else internal class XmlObjectSerializerWriteContext : XmlObjectSerializerContext #endif { private ObjectReferenceStack _byValObjectsInScope = new ObjectReferenceStack(); private XmlSerializableWriter _xmlSerializableWriter; private const int depthToCheckCyclicReference = 512; private ObjectToIdCache _serializedObjects; private bool _isGetOnlyCollection; private readonly bool _unsafeTypeForwardingEnabled; protected bool serializeReadOnlyTypes; protected bool preserveObjectReferences; internal static XmlObjectSerializerWriteContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) { return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null) ? new XmlObjectSerializerWriteContextComplex(serializer, rootTypeDataContract, dataContractResolver) : new XmlObjectSerializerWriteContext(serializer, rootTypeDataContract, dataContractResolver); } protected XmlObjectSerializerWriteContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver resolver) : base(serializer, rootTypeDataContract, resolver) { this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes; // Known types restricts the set of types that can be deserialized _unsafeTypeForwardingEnabled = true; } internal XmlObjectSerializerWriteContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { // Known types restricts the set of types that can be deserialized _unsafeTypeForwardingEnabled = true; } #if USE_REFEMIT || uapaot internal ObjectToIdCache SerializedObjects #else protected ObjectToIdCache SerializedObjects #endif { get { if (_serializedObjects == null) _serializedObjects = new ObjectToIdCache(); return _serializedObjects; } } internal override bool IsGetOnlyCollection { get { return _isGetOnlyCollection; } set { _isGetOnlyCollection = value; } } internal bool SerializeReadOnlyTypes { get { return this.serializeReadOnlyTypes; } } internal bool UnsafeTypeForwardingEnabled { get { return _unsafeTypeForwardingEnabled; } } #if USE_REFEMIT public void StoreIsGetOnlyCollection() #else internal void StoreIsGetOnlyCollection() #endif { _isGetOnlyCollection = true; } internal void ResetIsGetOnlyCollection() { _isGetOnlyCollection = false; } #if USE_REFEMIT public void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #else internal void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #endif { if (!OnHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/)) InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); OnEndHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/); } #if USE_REFEMIT public virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #else internal virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) #endif { if (writeXsiType) { Type declaredType = Globals.TypeOfObject; SerializeWithXsiType(xmlWriter, obj, obj.GetType().TypeHandle, null/*type*/, -1, declaredType.TypeHandle, declaredType); } else if (isDeclaredType) { DataContract contract = GetDataContract(declaredTypeID, declaredTypeHandle); SerializeWithoutXsiType(contract, xmlWriter, obj, declaredTypeHandle); } else { RuntimeTypeHandle objTypeHandle = obj.GetType().TypeHandle; if (declaredTypeHandle.GetHashCode() == objTypeHandle.GetHashCode()) // semantically the same as Value == Value; Value is not available in SL { DataContract dataContract = (declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, null /*type*/); SerializeWithoutXsiType(dataContract, xmlWriter, obj, declaredTypeHandle); } else { SerializeWithXsiType(xmlWriter, obj, objTypeHandle, null /*type*/, declaredTypeID, declaredTypeHandle, Type.GetTypeFromHandle(declaredTypeHandle)); } } } internal void SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); scopedKnownTypes.Pop(); } else { WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); } } internal virtual void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) { bool verifyKnownType = false; Type declaredType = rootTypeDataContract.UnderlyingType; if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { if (DataContractResolver != null) { WriteResolvedTypeInfo(xmlWriter, graphType, declaredType); } } else if (!declaredType.IsArray) //Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item { verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract); } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, originalDeclaredTypeHandle, declaredType); } protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { bool verifyKnownType = false; DataContract dataContract; if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { #if !uapaot dataContract = GetDataContractSkipValidation(DataContract.GetId(objectTypeHandle), objectTypeHandle, objectType); if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; dataContract = GetDataContract(declaredTypeHandle, declaredType); #else dataContract = DataContract.GetDataContract(declaredType); if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (this.Mode == SerializationMode.SharedType && dataContract.IsValidContract(this.Mode)) dataContract = dataContract.GetValidContract(this.Mode); else dataContract = GetDataContract(declaredTypeHandle, declaredType); #endif if (!WriteClrTypeInfo(xmlWriter, dataContract) && DataContractResolver != null) { if (objectType == null) { objectType = Type.GetTypeFromHandle(objectTypeHandle); } WriteResolvedTypeInfo(xmlWriter, objectType, declaredType); } } else if (declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item { // A call to OnHandleIsReference is not necessary here -- arrays cannot be IsReference dataContract = GetDataContract(objectTypeHandle, objectType); WriteClrTypeInfo(xmlWriter, dataContract); dataContract = GetDataContract(declaredTypeHandle, declaredType); } else { dataContract = GetDataContract(objectTypeHandle, objectType); if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (!WriteClrTypeInfo(xmlWriter, dataContract)) { DataContract declaredTypeContract = (declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, declaredType); verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract); } } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredTypeHandle, declaredType); } internal bool OnHandleIsReference(XmlWriterDelegator xmlWriter, DataContract contract, object obj) { if (preserveObjectReferences || !contract.IsReference || _isGetOnlyCollection) { return false; } bool isNew = true; int objectId = SerializedObjects.GetId(obj, ref isNew); _byValObjectsInScope.EnsureSetAsIsReference(obj); if (isNew) { xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.IdLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId)); return false; } else { xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId)); return true; } } protected void SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, bool verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } #if !uapaot if (verifyKnownType) { if (!IsKnownType(dataContract, declaredType)) { DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/); if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } } } #endif WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, string clrTypeName, string clrAssemblyName) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, SerializationInfo serInfo) { return false; } #if USE_REFEMIT || uapaot public virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value) #else internal virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value) #endif { xmlWriter.WriteAnyType(value); } #if USE_REFEMIT || uapaot public virtual void WriteString(XmlWriterDelegator xmlWriter, string value) #else internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value) #endif { xmlWriter.WriteString(value); } #if USE_REFEMIT || uapaot public virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteString(value); xmlWriter.WriteEndElementPrimitive(); } } #if USE_REFEMIT || uapaot public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) #else internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) #endif { xmlWriter.WriteBase64(value); } #if USE_REFEMIT || uapaot public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteBase64(value); xmlWriter.WriteEndElementPrimitive(); } } #if USE_REFEMIT || uapaot public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value) #else internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value) #endif { xmlWriter.WriteUri(value); } #if USE_REFEMIT || uapaot public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteUri(value); xmlWriter.WriteEndElementPrimitive(); } } #if USE_REFEMIT || uapaot public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) #else internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) #endif { xmlWriter.WriteQName(value); } #if USE_REFEMIT || uapaot public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) #else internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns); else { if (ns != null && ns.Value != null && ns.Value.Length > 0) xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns); else xmlWriter.WriteStartElement(name, ns); xmlWriter.WriteQName(value); xmlWriter.WriteEndElement(); } } internal void HandleGraphAtTopLevel(XmlWriterDelegator writer, object obj, DataContract contract) { writer.WriteXmlnsAttribute(Globals.XsiPrefix, DictionaryGlobals.SchemaInstanceNamespace); if (contract.IsISerializable) { writer.WriteXmlnsAttribute(Globals.XsdPrefix, DictionaryGlobals.SchemaNamespace); } OnHandleReference(writer, obj, true /*canContainReferences*/); } internal virtual bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (xmlWriter.depth < depthToCheckCyclicReference) return false; if (canContainCyclicReference) { if (_byValObjectsInScope.Contains(obj)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotSerializeObjectWithCycles, DataContract.GetClrTypeFullName(obj.GetType())))); _byValObjectsInScope.Push(obj); } return false; } internal virtual void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (xmlWriter.depth < depthToCheckCyclicReference) return; if (canContainCyclicReference) { _byValObjectsInScope.Pop(obj); } } #if USE_REFEMIT public void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable) #else internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable) #endif { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); WriteNull(xmlWriter); } internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteStartElement(name, ns); WriteNull(xmlWriter, memberType, isMemberTypeSerializable); xmlWriter.WriteEndElement(); } #if USE_REFEMIT public void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array) #else internal void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array) #endif { IncrementCollectionCount(xmlWriter, array.GetLength(0)); } #if USE_REFEMIT public void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection) #else internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection) #endif { IncrementCollectionCount(xmlWriter, collection.Count); } #if USE_REFEMIT public void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection) #else internal void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection) #endif { IncrementCollectionCount(xmlWriter, collection.Count); } private void IncrementCollectionCount(XmlWriterDelegator xmlWriter, int size) { IncrementItemCount(size); WriteArraySize(xmlWriter, size); } internal virtual void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { } #if USE_REFEMIT public static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType) #else internal static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType) #endif { if (obj == null || memberType == null) return false; return obj.GetType().TypeHandle.Equals(memberType.TypeHandle); } #if USE_REFEMIT public static T GetDefaultValue<T>() #else internal static T GetDefaultValue<T>() #endif { return default(T); } #if USE_REFEMIT public static T GetNullableValue<T>(Nullable<T> value) where T : struct #else internal static T GetNullableValue<T>(Nullable<T> value) where T : struct #endif { // value.Value will throw if hasValue is false return value.Value; } #if USE_REFEMIT public static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type) #else internal static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type) #endif { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.RequiredMemberMustBeEmitted, memberName, type.FullName))); } #if USE_REFEMIT public static bool GetHasValue<T>(Nullable<T> value) where T : struct #else internal static bool GetHasValue<T>(Nullable<T> value) where T : struct #endif { return value.HasValue; } internal void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { if (_xmlSerializableWriter == null) _xmlSerializableWriter = new XmlSerializableWriter(); WriteIXmlSerializable(xmlWriter, obj, _xmlSerializableWriter); } internal static void WriteRootIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { WriteIXmlSerializable(xmlWriter, obj, new XmlSerializableWriter()); } private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj, XmlSerializableWriter xmlSerializableWriter) { xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj); IXmlSerializable xmlSerializable = obj as IXmlSerializable; if (xmlSerializable != null) xmlSerializable.WriteXml(xmlSerializableWriter); else { XmlElement xmlElement = obj as XmlElement; if (xmlElement != null) xmlElement.WriteTo(xmlSerializableWriter); else { XmlNode[] xmlNodes = obj as XmlNode[]; if (xmlNodes != null) foreach (XmlNode xmlNode in xmlNodes) xmlNode.WriteTo(xmlSerializableWriter); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownXmlType, DataContract.GetClrTypeFullName(obj.GetType())))); } } xmlSerializableWriter.EndWrite(); } [MethodImpl(MethodImplOptions.NoInlining)] internal void GetObjectData(ISerializable obj, SerializationInfo serInfo, StreamingContext context) { obj.GetObjectData(serInfo, context); } public void WriteISerializable(XmlWriterDelegator xmlWriter, ISerializable obj) { Type objType = obj.GetType(); var serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter /*!UnsafeTypeForwardingEnabled is always false*/); GetObjectData(obj, serInfo, GetStreamingContext()); if (!UnsafeTypeForwardingEnabled && serInfo.AssemblyName == Globals.MscorlibAssemblyName) { // Throw if a malicious type tries to set its assembly name to "0" to get deserialized in mscorlib throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ISerializableAssemblyNameSetToZero, DataContract.GetClrTypeFullName(obj.GetType())))); } WriteSerializationInfo(xmlWriter, objType, serInfo); } internal void WriteSerializationInfo(XmlWriterDelegator xmlWriter, Type objType, SerializationInfo serInfo) { if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName) { if (DataContractResolver != null) { XmlDictionaryString typeName, typeNs; if (ResolveType(serInfo.ObjectType, objType, out typeName, out typeNs)) { xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, typeName, typeNs); } } else { string typeName, typeNs; DataContract.GetDefaultStableName(serInfo.FullTypeName, out typeName, out typeNs); xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, DataContract.GetClrTypeString(typeName), DataContract.GetClrTypeString(typeNs)); } } WriteClrTypeInfo(xmlWriter, objType, serInfo); IncrementItemCount(serInfo.MemberCount); foreach (SerializationEntry serEntry in serInfo) { XmlDictionaryString name = DataContract.GetClrTypeString(DataContract.EncodeLocalName(serEntry.Name)); xmlWriter.WriteStartElement(name, DictionaryGlobals.EmptyString); object obj = serEntry.Value; if (obj == null) { WriteNull(xmlWriter); } else { InternalSerializeReference(xmlWriter, obj, false /*isDeclaredType*/, false /*writeXsiType*/, -1, Globals.TypeOfObject.TypeHandle); } xmlWriter.WriteEndElement(); } } protected virtual void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { dataContract.WriteXmlValue(xmlWriter, obj, this); } protected virtual void WriteNull(XmlWriterDelegator xmlWriter) { XmlObjectSerializer.WriteNull(xmlWriter); } private void WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType) { XmlDictionaryString typeName, typeNamespace; if (ResolveType(objectType, declaredType, out typeName, out typeNamespace)) { WriteTypeInfo(writer, typeName, typeNamespace); } } private bool ResolveType(Type objectType, Type declaredType, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { if (!DataContractResolver.TryResolveType(objectType, declaredType, KnownTypeResolver, out typeName, out typeNamespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedFalse, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } if (typeName == null) { if (typeNamespace == null) { return false; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } } if (typeNamespace == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } return true; } protected virtual bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract) { if (!XmlObjectSerializer.IsContractDeclared(contract, declaredContract)) { if (DataContractResolver == null) { WriteTypeInfo(writer, contract.Name, contract.Namespace); return true; } else { WriteResolvedTypeInfo(writer, contract.OriginalUnderlyingType, declaredContract.OriginalUnderlyingType); return false; } } return false; } protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace) { writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } protected virtual void WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryString dataContractName, XmlDictionaryString dataContractNamespace) { writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject extensionData, int memberIndex) { if (IgnoreExtensionDataObject || extensionData == null) return; IList<ExtensionDataMember> members = extensionData.Members; if (members != null) { for (int i = 0; i < extensionData.Members.Count; i++) { ExtensionDataMember member = extensionData.Members[i]; if (member.MemberIndex == memberIndex) { WriteExtensionDataMember(xmlWriter, member); } } } } private void WriteExtensionDataMember(XmlWriterDelegator xmlWriter, ExtensionDataMember member) { xmlWriter.WriteStartElement(member.Name, member.Namespace); IDataNode dataNode = member.Value; WriteExtensionDataValue(xmlWriter, dataNode); xmlWriter.WriteEndElement(); } internal virtual void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, IDataNode dataNode) { if (dataNode.DataContractName != null) WriteTypeInfo(xmlWriter, dataNode.DataContractName, dataNode.DataContractNamespace); WriteClrTypeInfo(xmlWriter, dataNode.DataType, dataNode.ClrTypeName, dataNode.ClrAssemblyName); } internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode dataNode) { IncrementItemCount(1); if (dataNode == null) { WriteNull(xmlWriter); return; } if (dataNode.PreservesReferences && OnHandleReference(xmlWriter, (dataNode.Value == null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/)) return; Type dataType = dataNode.DataType; if (dataType == Globals.TypeOfClassDataNode) WriteExtensionClassData(xmlWriter, (ClassDataNode)dataNode); else if (dataType == Globals.TypeOfCollectionDataNode) WriteExtensionCollectionData(xmlWriter, (CollectionDataNode)dataNode); else if (dataType == Globals.TypeOfXmlDataNode) WriteExtensionXmlData(xmlWriter, (XmlDataNode)dataNode); else if (dataType == Globals.TypeOfISerializableDataNode) WriteExtensionISerializableData(xmlWriter, (ISerializableDataNode)dataNode); else { WriteExtensionDataTypeInfo(xmlWriter, dataNode); if (dataType == Globals.TypeOfObject) { // NOTE: serialize value in DataNode<object> since it may contain non-primitive // deserialized object (ex. empty class) object o = dataNode.Value; if (o != null) InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, o.GetType().TypeHandle); } else xmlWriter.WriteExtensionData(dataNode); } if (dataNode.PreservesReferences) OnEndHandleReference(xmlWriter, (dataNode.Value == null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/); } internal bool TryWriteDeserializedExtensionData(XmlWriterDelegator xmlWriter, IDataNode dataNode) { object o = dataNode.Value; if (o == null) return false; Type declaredType = (dataNode.DataContractName == null) ? o.GetType() : Globals.TypeOfObject; InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, declaredType.TypeHandle); return true; } private void WriteExtensionClassData(XmlWriterDelegator xmlWriter, ClassDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { WriteExtensionDataTypeInfo(xmlWriter, dataNode); IList<ExtensionDataMember> members = dataNode.Members; if (members != null) { for (int i = 0; i < members.Count; i++) { WriteExtensionDataMember(xmlWriter, members[i]); } } } } private void WriteExtensionCollectionData(XmlWriterDelegator xmlWriter, CollectionDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { WriteExtensionDataTypeInfo(xmlWriter, dataNode); WriteArraySize(xmlWriter, dataNode.Size); IList<IDataNode> items = dataNode.Items; if (items != null) { for (int i = 0; i < items.Count; i++) { xmlWriter.WriteStartElement(dataNode.ItemName, dataNode.ItemNamespace); WriteExtensionDataValue(xmlWriter, items[i]); xmlWriter.WriteEndElement(); } } } } private void WriteExtensionISerializableData(XmlWriterDelegator xmlWriter, ISerializableDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { WriteExtensionDataTypeInfo(xmlWriter, dataNode); if (dataNode.FactoryTypeName != null) xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, dataNode.FactoryTypeName, dataNode.FactoryTypeNamespace); IList<ISerializableDataMember> members = dataNode.Members; if (members != null) { for (int i = 0; i < members.Count; i++) { ISerializableDataMember member = members[i]; xmlWriter.WriteStartElement(member.Name, string.Empty); WriteExtensionDataValue(xmlWriter, member.Value); xmlWriter.WriteEndElement(); } } } } private void WriteExtensionXmlData(XmlWriterDelegator xmlWriter, XmlDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { IList<XmlAttribute> xmlAttributes = dataNode.XmlAttributes; if (xmlAttributes != null) { foreach (XmlAttribute attribute in xmlAttributes) attribute.WriteTo(xmlWriter.Writer); } WriteExtensionDataTypeInfo(xmlWriter, dataNode); IList<XmlNode> xmlChildNodes = dataNode.XmlChildNodes; if (xmlChildNodes != null) { foreach (XmlNode node in xmlChildNodes) node.WriteTo(xmlWriter.Writer); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using NuGet; namespace MakeSharp { public static class HelpersExtensions { /// <summary> /// Equivalent to Console.WriteLine(mystring,args) /// </summary> /// <param name="data"></param> /// <param name="args"></param> public static void ToConsole(this string data, params object[] args) { if (args.Length == 0) { Console.WriteLine(data); } else { Console.WriteLine(data, args); } } /// <summary> /// Writes to console using red colour /// </summary> /// <param name="data"></param> /// <param name="args"></param> public static void WriteError(this string data, params object[] args) { var old = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; if (args.Length == 0) { Console.WriteLine(data); } else { Console.WriteLine(data, args); } Console.ForegroundColor = old; } /// <summary> /// Writes to console using cyan colour /// </summary> /// <param name="data"></param> /// <param name="args"></param> public static void WriteInfo(this string data, params object[] args) { var old = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Cyan; if (args.Length == 0) { Console.WriteLine(data); } else { Console.WriteLine(data, args); } Console.ForegroundColor = old; } /// <summary> /// Creates a directory /// </summary> /// <param name="dirName">Directory path</param> public static void MkDir(this string dirName) { dirName.MustNotBeEmpty(); Directory.CreateDirectory(dirName); } /// <summary> /// Deletes the specified directory /// </summary> /// <param name="dirName">Directory path</param> public static void DeleteDir(this string dirName) { dirName.MustNotBeEmpty(); if (Directory.Exists(dirName)) { Directory.Delete(dirName, true); } } /// <summary> /// Empties the specified directory /// </summary> /// <param name="dirName">Directory path</param> public static void CleanupDir(this string dirName) { dirName.MustNotBeEmpty(); if (Directory.Exists(dirName)) { Directory.Delete(dirName, true); } Directory.CreateDirectory(dirName); } public static DirectoryInfo ToDirectoryInfo(this string path) { return new DirectoryInfo(path); } public static FileInfo ToFileInfo(this string path) { return new FileInfo(path); } /// <summary> /// Runs executable with specified arguments. /// No new window is created and all output goes to console. /// </summary> /// <param name="file">Executable name</param> /// <param name="args">Arguments list</param> /// <returns>Process exit code</returns> public static int Exec(this string file, params string[] args) { using (var p = new Process()) { p.StartInfo.FileName = file; if (args.Length > 0) { p.StartInfo.Arguments = string.Join(" ", args); } p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; "Executing: {0} {1}".ToConsole(file, p.StartInfo.Arguments); p.ErrorDataReceived += p_ErrorDataReceived; int result = -1; try { p.Start(); p.BeginErrorReadLine(); Console.WriteLine(p.StandardOutput.ReadToEnd()); p.WaitForExit(); result = p.ExitCode; } finally { p.ErrorDataReceived -= p_ErrorDataReceived; } return result; } } private static void p_ErrorDataReceived(object sender, DataReceivedEventArgs e) { if (!e.Data.IsNullOrEmpty()) { e.Data.WriteError(); } } /// <summary> /// Loads the specified file as a nuspec file (nuget manifest) /// </summary> /// <param name="filename"></param> /// <returns></returns> public static NuSpecFile AsNuspec(this string filename) { return new NuSpecFile(filename); } /// <summary> /// Treats the file as an assembly and returns its version /// </summary> /// <param name="filename">Path to assembly file</param> /// <returns></returns> public static Version GetAssemblyVersion(this string filename) { var f = new FileInfo(filename); "Getting version from assembly '{0}'".ToConsole(f.FullName); var name = AssemblyName.GetAssemblyName(f.FullName); return name.Version; } /// <summary> /// Creates a semantic version (http://semver.org/) from a Version allowing you to specify pre-release and build strings. /// </summary> /// <see cref="http://semver.org/"/> /// <param name="version"></param> /// <param name="preRelease">beta => 1.0.0-beta</param> /// <param name="build">001 => 1.0.0-beta+001</param> /// <returns></returns> public static CavemanTools.SemanticVersion ToSemanticVersion(this Version version, string preRelease = null, string build = null) { version.MustNotBeNull(); return new CavemanTools.SemanticVersion(version, preRelease, build); } /// <summary> /// Creates nuget package and returns the nupkg file path /// </summary> /// <param name="file"></param> /// <param name="basePath"></param> /// <param name="outputDir"></param> /// <returns></returns> public static string CreateNuget(this string file, string basePath, string outputDir) { "Creating nuget package from '{0}'".ToConsole(file); if (outputDir.IsNullOrEmpty()) { outputDir = Path.GetDirectoryName(file); } if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } string nugetFile = ""; using (var fs = File.Open(file, FileMode.Open)) { var pack = new PackageBuilder(fs, Path.GetFullPath(basePath)); var nugetName = pack.Id + "." + pack.Version.ToString() + ".nupkg"; nugetFile = Path.Combine(outputDir, nugetName); using (var ws = File.Create(nugetFile)) { pack.Save(ws); } } "Package '{0}' was successfuly created".WriteInfo(nugetFile); return nugetFile; } public static void CreateNuget(this string nuspecTemplate,Action<NuSpecFile> cfgNuspec=null,Action<NugetPackConfig> cfgPacker=null) { var file = nuspecTemplate.AsNuspec(); cfgNuspec?.Invoke(file); var packCfg=new NugetPackConfig(); cfgPacker?.Invoke(packCfg); var spec=file.Save(packCfg.OutputDir); var args = new List<string>(); args.AddRange(new[] { "pack", spec, "-BasePath", packCfg.BasePath, "-OutputDirectory", packCfg.OutputDir }); if (packCfg.BuildSymbols) args.Add("-Symbols"); packCfg.NugetPath.Exec(args.ToArray()); var pgk = file.Manifest.Metadata.Id + "." + file.Manifest.Metadata.Version + ".nupkg"; if (packCfg.Publish) { packCfg.NugetPath.Exec("Push",Path.Combine(packCfg.OutputDir,pgk)); } } } public class NugetPackConfig { /// <summary> /// Path to nuget.exe /// </summary> public string NugetPath { get; set; } = "tools/nuget.exe"; /// <summary> /// Base path used to include files from solution into package /// </summary> public string BasePath { get; set; } = "./"; public string OutputDir { get; set; } = "./"; public bool BuildSymbols { get; set; } public bool Publish { get; set; } public string NugetServer { get; set; } } }
using System; using System.Collections.Generic; using FluentSecurity.Configuration; using FluentSecurity.Policy; using NUnit.Framework; namespace FluentSecurity.Specification.Configuration { [TestFixture] [Category("DefaultPolicyAppenderSpec")] public class When_updating_policies { [Test] public void Should_throw_ArgumentNullException_when_policy_to_add_is_null() { // Arrange var policyAppender = new DefaultPolicyAppender(); // Act & Assert Assert.Throws<ArgumentNullException>(() => policyAppender.UpdatePolicies(null, new List<ISecurityPolicy>()) ); } [Test] public void Should_throw_ArgumentNullException_when_policies_is_null() { // Arrange var policyAppender = new DefaultPolicyAppender(); // Act & Assert Assert.Throws<ArgumentNullException>(() => policyAppender.UpdatePolicies(new IgnorePolicy(), null) ); } } [TestFixture] [Category("DefaultPolicyAppenderSpec")] public class When_updating_policies_with_an_IgnorePolicy : with_DefaultPolicyAppender { private DenyAnonymousAccessPolicy _denyAnonymousAccessPolicy; private IgnorePolicy _ignorePolicy; protected override void Context() { // Arrange _denyAnonymousAccessPolicy = new DenyAnonymousAccessPolicy(); _ignorePolicy = new IgnorePolicy(); Policies = new List<ISecurityPolicy> { _denyAnonymousAccessPolicy }; } [Test] public void Should_remove_all_existing_policies() { // Act PolicyAppender.UpdatePolicies(_ignorePolicy, Policies); // Assert Assert.That(Policies.Contains(_denyAnonymousAccessPolicy), Is.False); Assert.That(Policies.Count, Is.EqualTo(1)); } [Test] public void Should_add_ignorepolicy() { // Act PolicyAppender.UpdatePolicies(_ignorePolicy, Policies); // Assert Assert.That(Policies.Contains(_ignorePolicy), Is.True); } } [TestFixture] [Category("DefaultPolicyAppenderSpec")] public class When_updating_policies_with_a_DenyAnonymousAccessPolicy : with_DefaultPolicyAppender { private DenyAuthenticatedAccessPolicy _denyAuthenticatedAccessPolicy; private DenyAnonymousAccessPolicy _denyAnonymousAccessPolicy; protected override void Context() { // Arrange _denyAuthenticatedAccessPolicy = new DenyAuthenticatedAccessPolicy(); _denyAnonymousAccessPolicy = new DenyAnonymousAccessPolicy(); Policies = new List<ISecurityPolicy> { _denyAuthenticatedAccessPolicy }; } [Test] public void Should_remove_all_existing_policies() { // Act PolicyAppender.UpdatePolicies(_denyAnonymousAccessPolicy, Policies); // Assert Assert.That(Policies.Contains(_denyAuthenticatedAccessPolicy), Is.False); Assert.That(Policies.Count, Is.EqualTo(1)); } [Test] public void Should_add_DenyAnonymousAccessPolicy() { // Act PolicyAppender.UpdatePolicies(_denyAnonymousAccessPolicy, Policies); // Assert Assert.That(Policies.Contains(_denyAnonymousAccessPolicy), Is.True); } } [TestFixture] [Category("DefaultPolicyAppenderSpec")] public class When_updating_policies_with_a_DenyAuthenticatedAccessPolicy : with_DefaultPolicyAppender { private DenyAuthenticatedAccessPolicy _denyAuthenticatedAccessPolicy; private DenyAnonymousAccessPolicy _denyAnonymousAccessPolicy; protected override void Context() { // Arrange _denyAuthenticatedAccessPolicy = new DenyAuthenticatedAccessPolicy(); _denyAnonymousAccessPolicy = new DenyAnonymousAccessPolicy(); Policies = new List<ISecurityPolicy> { _denyAnonymousAccessPolicy }; } [Test] public void Should_remove_all_existing_policies() { // Act PolicyAppender.UpdatePolicies(_denyAuthenticatedAccessPolicy, Policies); // Assert Assert.That(Policies.Contains(_denyAnonymousAccessPolicy), Is.False); Assert.That(Policies.Count, Is.EqualTo(1)); } [Test] public void Should_add_DenyAuthenticatedAccessPolicy() { // Act PolicyAppender.UpdatePolicies(_denyAuthenticatedAccessPolicy, Policies); // Assert Assert.That(Policies.Contains(_denyAuthenticatedAccessPolicy), Is.True); } } [TestFixture] [Category("DefaultPolicyAppenderSpec")] public class When_updating_policies_with_a_RequireRolePolicy : with_DefaultPolicyAppender { private RequireRolePolicy _requireRolePolicy; private DenyAnonymousAccessPolicy _denyAnonymousAccessPolicy; protected override void Context() { // Arrange _requireRolePolicy = new RequireRolePolicy("Administrator"); _denyAnonymousAccessPolicy = new DenyAnonymousAccessPolicy(); Policies = new List<ISecurityPolicy> { _denyAnonymousAccessPolicy }; } [Test] public void Should_remove_all_existing_policies() { // Act PolicyAppender.UpdatePolicies(_requireRolePolicy, Policies); // Assert Assert.That(Policies.Contains(_denyAnonymousAccessPolicy), Is.False); Assert.That(Policies.Count, Is.EqualTo(1)); } [Test] public void Should_add_RequireRolePolicy() { // Act PolicyAppender.UpdatePolicies(_requireRolePolicy, Policies); // Assert Assert.That(Policies.Contains(_requireRolePolicy), Is.True); } } [TestFixture] [Category("DefaultPolicyAppenderSpec")] public class When_updating_policies_with_a_RequireAnyRolePolicy : with_DefaultPolicyAppender { private RequireAnyRolePolicy _requireAnyRolePolicy; private DenyAnonymousAccessPolicy _denyAnonymousAccessPolicy; protected override void Context() { // Arrange _requireAnyRolePolicy = new RequireAnyRolePolicy("Administrator"); _denyAnonymousAccessPolicy = new DenyAnonymousAccessPolicy(); Policies = new List<ISecurityPolicy> { _denyAnonymousAccessPolicy }; } [Test] public void Should_remove_all_existing_policies() { // Act PolicyAppender.UpdatePolicies(_requireAnyRolePolicy, Policies); // Assert Assert.That(Policies.Contains(_denyAnonymousAccessPolicy), Is.False); Assert.That(Policies.Count, Is.EqualTo(1)); } [Test] public void Should_add_RequireAnyRolePolicy() { // Act PolicyAppender.UpdatePolicies(_requireAnyRolePolicy, Policies); // Assert Assert.That(Policies.Contains(_requireAnyRolePolicy), Is.True); } } [TestFixture] [Category("DefaultPolicyAppenderSpec")] public class When_updating_policies_with_a_RequireAllRolesPolicy : with_DefaultPolicyAppender { private RequireAllRolesPolicy _requireAllRolesPolicy; private DenyAnonymousAccessPolicy _denyAnonymousAccessPolicy; protected override void Context() { // Arrange _requireAllRolesPolicy = new RequireAllRolesPolicy("Administrator"); _denyAnonymousAccessPolicy = new DenyAnonymousAccessPolicy(); Policies = new List<ISecurityPolicy> { _denyAnonymousAccessPolicy }; } [Test] public void Should_remove_all_existing_policies() { // Act PolicyAppender.UpdatePolicies(_requireAllRolesPolicy, Policies); // Assert Assert.That(Policies.Contains(_denyAnonymousAccessPolicy), Is.False); Assert.That(Policies.Count, Is.EqualTo(1)); } [Test] public void Should_add_RequireAllRolesPolicy() { // Act PolicyAppender.UpdatePolicies(_requireAllRolesPolicy, Policies); // Assert Assert.That(Policies.Contains(_requireAllRolesPolicy), Is.True); } } public abstract class with_DefaultPolicyAppender { protected List<ISecurityPolicy> Policies; protected IPolicyAppender PolicyAppender; [SetUp] public virtual void SetUp() { Policies = new List<ISecurityPolicy>(); PolicyAppender = new DefaultPolicyAppender(); Context(); } protected abstract void Context(); } }
using System; using System.Collections.Specialized; using System.Net; using Newtonsoft.Json; using SteamKit2; namespace SteamTrade.TradeWebAPI { /// <summary> /// This class provides the interface into the Web API for trading on the /// Steam network. /// </summary> public class TradeSession { private const string SteamCommunityDomain = "steamcommunity.com"; private const string SteamTradeUrl = "http://steamcommunity.com/trade/{0}/"; private string sessionIdEsc; private string baseTradeURL; private CookieContainer cookies; private readonly string steamLogin; private readonly string sessionId; private readonly SteamID OtherSID; /// <summary> /// Initializes a new instance of the <see cref="TradeSession"/> class. /// </summary> /// <param name="sessionId">The session id.</param> /// <param name="steamLogin">The current steam login.</param> /// <param name="otherSid">The Steam id of the other trading partner.</param> public TradeSession(string sessionId, string steamLogin, SteamID otherSid) { this.sessionId = sessionId; this.steamLogin = steamLogin; OtherSID = otherSid; Init(); } #region Trade status properties /// <summary> /// Gets the LogPos number of the current trade. /// </summary> /// <remarks>This is not automatically updated by this class.</remarks> internal int LogPos { get; set; } /// <summary> /// Gets the version number of the current trade. This increments on /// every item added or removed from a trade. /// </summary> /// <remarks>This is not automatically updated by this class.</remarks> internal int Version { get; set; } #endregion Trade status properties #region Trade Web API command methods /// <summary> /// Gets the trade status. /// </summary> /// <returns>A deserialized JSON object into <see cref="TradeStatus"/></returns> /// <remarks> /// This is the main polling method for trading and must be done at a /// periodic rate (probably around 1 second). /// </remarks> internal TradeStatus GetStatus() { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("logpos", "" + LogPos); data.Add ("version", "" + Version); string response = Fetch (baseTradeURL + "tradestatus", "POST", data); return JsonConvert.DeserializeObject<TradeStatus> (response); } /// <summary> /// Gets the foriegn inventory. /// </summary> /// <param name="otherId">The other id.</param> /// <returns>A dynamic JSON object.</returns> internal dynamic GetForiegnInventory(SteamID otherId) { return GetForiegnInventory(otherId, 440, 2); } internal dynamic GetForiegnInventory(SteamID otherId, long contextId, int appid) { var data = new NameValueCollection(); data.Add("sessionid", sessionIdEsc); data.Add("steamid", "" + otherId); data.Add("appid", "" + appid); data.Add("contextid", "" + contextId); try { string response = Fetch(baseTradeURL + "foreigninventory", "POST", data); return JsonConvert.DeserializeObject(response); } catch (Exception) { return JsonConvert.DeserializeObject("{\"success\":\"false\"}"); } } /// <summary> /// Sends a message to the user over the trade chat. /// </summary> internal bool SendMessageWebCmd(string msg) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("message", msg); data.Add ("logpos", "" + LogPos); data.Add ("version", "" + Version); string result = Fetch (baseTradeURL + "chat", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Adds a specified itom by its itemid. Since each itemid is /// unique to each item, you'd first have to find the item, or /// use AddItemByDefindex instead. /// </summary> /// <returns> /// Returns false if the item doesn't exist in the Bot's inventory, /// and returns true if it appears the item was added. /// </returns> internal bool AddItemWebCmd(ulong itemid, int slot,int appid,long contextid) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add("appid", "" + appid); data.Add ("contextid", "" + contextid); data.Add ("itemid", "" + itemid); data.Add ("slot", "" + slot); string result = Fetch(baseTradeURL + "additem", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Removes an item by its itemid. Read AddItem about itemids. /// Returns false if the item isn't in the offered items, or /// true if it appears it succeeded. /// </summary> internal bool RemoveItemWebCmd(ulong itemid, int slot, int appid, long contextid) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add("appid", "" + appid); data.Add("contextid", "" + contextid); data.Add ("itemid", "" + itemid); data.Add ("slot", "" + slot); string result = Fetch (baseTradeURL + "removeitem", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Sets the bot to a ready status. /// </summary> internal bool SetReadyWebCmd(bool ready) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("ready", ready ? "true" : "false"); data.Add ("version", "" + Version); string result = Fetch (baseTradeURL + "toggleready", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Accepts the trade from the user. Returns a deserialized /// JSON object. /// </summary> internal bool AcceptTradeWebCmd() { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("version", "" + Version); string response = Fetch (baseTradeURL + "confirm", "POST", data); dynamic json = JsonConvert.DeserializeObject(response); return IsSuccess(json); } /// <summary> /// Cancel the trade. This calls the OnClose handler, as well. /// </summary> internal bool CancelTradeWebCmd () { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); string result = Fetch (baseTradeURL + "cancel", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } private bool IsSuccess(dynamic json) { if(json == null) return false; try { //Sometimes, the response looks like this: {"success":false,"results":{"success":11}} //I believe this is Steam's way of asking the trade window (which is actually a webpage) to refresh, following a large successful update return (json.success == "true" || (json.results != null && json.results.success == "11")); } catch(Exception) { return false; } } #endregion Trade Web API command methods string Fetch (string url, string method, NameValueCollection data = null) { return SteamWeb.Fetch (url, method, data, cookies); } private void Init() { sessionIdEsc = Uri.UnescapeDataString(sessionId); Version = 1; cookies = new CookieContainer(); cookies.Add (new Cookie ("sessionid", sessionId, String.Empty, SteamCommunityDomain)); cookies.Add (new Cookie ("steamLogin", steamLogin, String.Empty, SteamCommunityDomain)); baseTradeURL = String.Format (SteamTradeUrl, OtherSID.ConvertToUInt64()); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Windows.Forms; using L10NSharp; using SIL.Reporting; using SIL.Windows.Forms.Extensions; namespace SIL.Windows.Forms.ImageToolbox.ImageGallery { public partial class ImageGalleryControl : UserControl, IImageToolboxControl { private ImageCollectionManager _imageCollectionManager; private PalasoImage _previousImage; public bool InSomeoneElesesDesignMode; public ImageGalleryControl() { InitializeComponent(); _thumbnailViewer.CaptionMethod = ((s) => string.Empty);//don't show a caption _thumbnailViewer.LoadComplete += ThumbnailViewerOnLoadComplete; _searchResultStats.Text = ""; if (Environment.OSVersion.Platform == PlatformID.Unix) { // For Linux, we can install the package if requested. _downloadInstallerLink.Text = "Install the Art Of Reading package (this may be very slow)".Localize("ImageToolbox.InstallArtOfReading"); _downloadInstallerLink.URL = null; _downloadInstallerLink.LinkClicked += InstallLinkClicked; } else { // Ensure that we can get localized text here. _downloadInstallerLink.Text = "Download Art Of Reading Installer".Localize("ImageToolbox.DownloadArtOfReading"); } _labelSearch.Text = "Image Galleries".Localize("ImageToolbox.ImageGalleries"); SearchLanguage = "en"; // until/unless the owner specifies otherwise explicitly // Get rid of any trace of a border on the toolstrip. toolStrip1.Renderer = new NoBorderToolStripRenderer(); // For some reason, setting these BackColor values in InitializeComponent() doesn't work. // The BackColor gets set back to the standard control background color somewhere... _downloadInstallerLink.BackColor = Color.White; _messageLabel.BackColor = Color.White; _messageLabel.SizeChanged += MessageLabelSizeChanged; } public void Dispose() { _thumbnailViewer.Closing(); //this guy was working away in the background _messageLabel.SizeChanged -= MessageLabelSizeChanged; } /// <summary> /// use if the calling app already has some notion of what the user might be looking for (e.g. the definition in a dictionary program) /// </summary> /// <param name="searchTerm"></param> public void SetIntialSearchTerm(string searchTerm) { _searchTermsBox.Text = searchTerm; } /// <summary> /// Gets or sets the language used in searching for an image by words. /// </summary> public string SearchLanguage { get; set; } void _thumbnailViewer_SelectedIndexChanged(object sender, EventArgs e) { if(ImageChanged!=null && _thumbnailViewer.HasSelection) { ImageChanged.Invoke(this, null); } } private void _thumbnailViewer_DoubleClick(object sender, EventArgs e) { if (ImageChangedAndAccepted != null && _thumbnailViewer.HasSelection) { ImageChangedAndAccepted.Invoke(this, null); } } private void _searchButton_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; _searchButton.Enabled = false; try { _thumbnailViewer.Clear(); if (!string.IsNullOrWhiteSpace(_searchTermsBox.Text)) { bool foundExactMatches; // (avoid enumerating the returned IEnumerable<object> more than once by copying to a List.) var results = _imageCollectionManager.GetMatchingImages(_searchTermsBox.Text, true, out foundExactMatches).ToList(); if (results.Any()) { _messageLabel.Visible = false; _downloadInstallerLink.Visible = false; _thumbnailViewer.LoadItems(results); var fmt = "Found {0} images".Localize("ImageToolbox.MatchingImages", "The {0} will be replaced by the number of matching images"); if (!foundExactMatches) fmt = "Found {0} images with names close to {1}".Localize("ImageToolbox.AlmostMatchingImages", "The {0} will be replaced by the number of images found. The {1} will be replaced with the search string."); _searchResultStats.Text = string.Format(fmt, results.Count, _searchTermsBox.Text); } else { _messageLabel.Visible = true; if (!_searchLanguageMenu.Visible) _downloadInstallerLink.Visible = true; _searchResultStats.Text = "Found no matching images".Localize("ImageToolbox.NoMatchingImages"); } } } catch (Exception) { } _searchButton.Enabled = true; //_okButton.Enabled = false; } private void ThumbnailViewerOnLoadComplete(object sender, EventArgs eventArgs) { Cursor.Current = Cursors.Default; } public string ChosenPath { get { return _thumbnailViewer.SelectedPath; } } public bool HaveImageCollectionOnThisComputer { get { return _imageCollectionManager != null; } } private void OnFormClosing(object sender, FormClosingEventArgs e) { _thumbnailViewer.Closing(); } public void SetImage(PalasoImage image) { _previousImage = image; if(ImageChanged!=null) ImageChanged.Invoke(this,null); } public PalasoImage GetImage() { if(ChosenPath!=null && File.Exists(ChosenPath)) { try { return PalasoImage.FromFile(ChosenPath); } catch (Exception error) { ErrorReport.ReportNonFatalExceptionWithMessage(error, "There was a problem choosing that image."); return _previousImage; } } return _previousImage; } public event EventHandler ImageChanged; /// <summary> /// happens when you double click an item /// </summary> public event EventHandler ImageChangedAndAccepted; private void _searchTermsBox_KeyDown(object sender, KeyEventArgs e) { if(e.KeyCode ==Keys.Enter) { e.SuppressKeyPress = true; _searchButton_Click(sender, null); } else { _searchResultStats.Text = ""; } } private new bool DesignMode { get { return (base.DesignMode || GetService(typeof(IDesignerHost)) != null) || (LicenseManager.UsageMode == LicenseUsageMode.Designtime); } } private void ArtOfReadingChooser_Load(object sender, EventArgs e) { if (DesignMode) return; _imageCollectionManager = ImageCollectionManager.FromStandardLocations(SearchLanguage); _collectionToolStrip.Visible = false; if (_imageCollectionManager == null) { _messageLabel.Visible = true; _messageLabel.Text = "This computer doesn't appear to have any galleries installed yet.".Localize("ImageToolbox.NoGalleries"); _downloadInstallerLink.Visible = true; _searchTermsBox.Enabled = false; _searchButton.Enabled = false; } else { #if DEBUG // _searchTermsBox.Text = @"flower"; #endif SetupSearchLanguageChoice(); _messageLabel.Visible = string.IsNullOrEmpty(_searchTermsBox.Text); // Adjust size to avoid text truncation _messageLabel.Height = 200; SetMessageLabelText(); _thumbnailViewer.SelectedIndexChanged += new EventHandler(_thumbnailViewer_SelectedIndexChanged); if (_imageCollectionManager.Collections.Count() > 1) { _collectionToolStrip.Visible = true; _collectionDropDown.Visible = true; _collectionDropDown.Text = "Galleries".Localize("ImageToolbox.Galleries"); if(ImageToolboxSettings.Default.DisabledImageCollections == null) { ImageToolboxSettings.Default.DisabledImageCollections = new StringCollection(); } foreach (var collection in _imageCollectionManager.Collections) { if(ImageToolboxSettings.Default.DisabledImageCollections.Contains(collection.FolderPath)) { collection.Enabled = false; } var text = Path.GetFileNameWithoutExtension(collection.Name); var item = new ToolStripMenuItem(text); _collectionDropDown.DropDownItems.Add(item); item.CheckOnClick = true; item.CheckState = collection.Enabled ? CheckState.Checked : CheckState.Unchecked; item.CheckedChanged += (o, args) => { if(_collectionDropDown.DropDownItems.Cast<ToolStripMenuItem>().Count(x => x.Checked) == 0) item.Checked = true; // tried to uncheck the last one, don't allow it. else { collection.Enabled = item.Checked; var disabledSettings = ImageToolboxSettings.Default.DisabledImageCollections; if (disabledSettings == null) ImageToolboxSettings.Default.DisabledImageCollections = disabledSettings = new StringCollection(); if (item.Checked && disabledSettings.Contains(collection.FolderPath)) disabledSettings.Remove(collection.FolderPath); if (!item.Checked && !disabledSettings.Contains(collection.FolderPath)) disabledSettings.Add(collection.FolderPath); ImageToolboxSettings.Default.Save(); } }; } } else { // otherwise, just leave them all enabled } } _messageLabel.Font = new Font(SystemFonts.DialogFont.FontFamily, 10); #if DEBUG //if (!HaveImageCollectionOnThisComputer) // return; //when just testing, I just want to see some choices. // _searchTermsBox.Text = @"flower"; //_searchButton_Click(this,null); #endif } private void SetMessageLabelText() { var msg = "In the box above, type what you are searching for, then press ENTER.".Localize("ImageToolbox.EnterSearchTerms"); // Allow for the old index that contained English and Indonesian together. var searchLang = "English + Indonesian"; // If we have the new multilingual index, _searchLanguageMenu will be visible. Its tooltip // contains both the native name of the current search language + its English name in // parentheses if its in a nonRoman script or otherwise thought to be unguessable by a // literate speaker of an European language. (The menu displays only the native name, and // SearchLanguage stores only the ISO code.) if (_searchLanguageMenu.Visible) searchLang = _searchLanguageMenu.ToolTipText; msg += Environment.NewLine + Environment.NewLine + String.Format("The search box is currently set to {0}".Localize("ImageToolbox.SearchLanguage"), searchLang); if (PlatformUtilities.Platform.IsWindows && !_searchLanguageMenu.Visible) { msg += Environment.NewLine + Environment.NewLine + "Did you know that there is a new version of this collection which lets you search in Arabic, Bengali, Chinese, English, French, Indonesian, Hindi, Portuguese, Spanish, Thai, or Swahili? It is free and available for downloading." .Localize("ImageToolbox.NewMultilingual"); _downloadInstallerLink.Visible = true; _downloadInstallerLink.BackColor = Color.White; } // Restore alignment (from center) for messages. (See https://silbloom.myjetbrains.com/youtrack/issue/BL-2753.) _messageLabel.TextAlign = _messageLabel.RightToLeft==RightToLeft.Yes ? HorizontalAlignment.Right : HorizontalAlignment.Left; _messageLabel.Text = msg; } /// <summary> /// Position the download link label properly whenever the size of the main message label changes, /// whether due to changing its text or changing the overall dialog box size. (BL-2853) /// </summary> private void MessageLabelSizeChanged(object sender, EventArgs eventArgs) { if (_searchLanguageMenu.Visible || !PlatformUtilities.Platform.IsWindows || !_downloadInstallerLink.Visible) return; _downloadInstallerLink.Width = _messageLabel.Width; // not sure why this isn't automatic if (_downloadInstallerLink.Location.Y != _messageLabel.Bottom + 5) _downloadInstallerLink.Location = new Point(_downloadInstallerLink.Left, _messageLabel.Bottom + 5); } protected class LanguageChoice { static readonly List<string> idsOfRecognizableLanguages = new List<string> { "en", "fr", "es", "it", "tpi", "pt", "id" }; private readonly CultureInfo _info; public LanguageChoice(CultureInfo ci) { _info = ci; } public string Id { get { return _info.Name == "zh-Hans" ? "zh" : _info.Name; } } public string NativeName { get { return _info.NativeName; } } public override string ToString() { if (_info.NativeName == _info.EnglishName) return _info.NativeName; // English (English) looks rather silly... if (idsOfRecognizableLanguages.Contains(Id)) return _info.NativeName; return String.Format("{0} ({1})", _info.NativeName, _info.EnglishName); } } private void SetupSearchLanguageChoice() { var indexLangs = _imageCollectionManager.IndexLanguageIds; if (indexLangs == null) { _searchLanguageMenu.Visible = false; } else { _searchLanguageMenu.Visible = true; foreach (var id in indexLangs) { var ci = id == "zh" ? new CultureInfo("zh-Hans") : new CultureInfo(id); var choice = new LanguageChoice(ci); var item = _searchLanguageMenu.DropDownItems.Add(choice.ToString()); item.Tag = choice; item.Click += SearchLanguageClick; if (id == SearchLanguage) { _searchLanguageMenu.Text = choice.NativeName; _searchLanguageMenu.ToolTipText = choice.ToString(); } } } // The Mono renderer makes the toolstrip stick out. (This is a Mono bug that // may not be worth spending time on.) Let's not poke the user in the eye // with an empty toolstrip. if (Environment.OSVersion.Platform == PlatformID.Unix) toolStrip1.Visible = _searchLanguageMenu.Visible; } void SearchLanguageClick(object sender, EventArgs e) { var item = sender as ToolStripItem; if (item != null) { var lang = item.Tag as LanguageChoice; if (lang != null && SearchLanguage != lang.Id) { _searchLanguageMenu.Text = lang.NativeName; _searchLanguageMenu.ToolTipText = lang.ToString(); SearchLanguage = lang.Id; _imageCollectionManager.ChangeSearchLanguageAndReloadIndex(lang.Id); SetMessageLabelText(); // Update with new language name. } } } /// <summary> /// To actually focus on the search box, the Mono runtime library appears to /// first need us to focus the search button, wait a bit, and then focus the /// search box. Bizarre, unfortunate, but true. (One of those bugs that we /// couldn't write code to do if we tried!) /// See https://jira.sil.org/browse/BL-964. /// </summary> internal void FocusSearchBox() { _searchButton.GotFocus += _searchButtonGotSetupFocus; _searchButton.Select(); } private System.Windows.Forms.Timer _focusTimer1; private void _searchButtonGotSetupFocus(object sender, EventArgs e) { _searchButton.GotFocus -= _searchButtonGotSetupFocus; _focusTimer1 = new System.Windows.Forms.Timer(this.components); _focusTimer1.Tick += new System.EventHandler(this._focusTimer1_Tick); _focusTimer1.Interval = 100; _focusTimer1.Enabled = true; } private void _focusTimer1_Tick(object sender, EventArgs e) { _focusTimer1.Enabled = false; _focusTimer1.Dispose(); _focusTimer1 = null; _searchTermsBox.TextBox.Focus(); } /// <summary> /// Try to install the artofreading package if possible. Use a GUI program if /// possible, but if not, try the command-line program with a GUI password /// dialog. /// </summary> /// <remarks> /// On Windows, the link label opens a web page to let the user download the /// installer. This is the analogous behavior for Linux, but is potentially /// so slow (300MB download) that we fire off the program without waiting for /// it to finish. /// </remarks> private void InstallLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (Environment.OSVersion.Platform != PlatformID.Unix) return; // Install the artofreading package if at all possible. if (File.Exists("/usr/bin/software-center")) { using (var process = new Process()) { process.StartInfo = new ProcessStartInfo { FileName = "/usr/bin/python", Arguments = "/usr/bin/software-center art-of-reading", UseShellExecute = false, RedirectStandardOutput = false, CreateNoWindow = false }; process.Start(); } } else if (File.Exists("/usr/bin/ssh-askpass")) { using (var process = new Process()) { process.StartInfo = new ProcessStartInfo { FileName = "/usr/bin/sudo", Arguments = "-A /usr/bin/apt-get -y install art-of-reading", UseShellExecute = false, RedirectStandardOutput = false, CreateNoWindow = false }; process.StartInfo.EnvironmentVariables.Add("SUDO_ASKPASS", "/usr/bin/ssh-askpass"); process.Start(); } } } } }
/* 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 Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.IO.IsolatedStorage; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Resources; using System.Xml.Linq; using WPCordovaClassLib.Cordova; using WPCordovaClassLib.Cordova.JSON; using WPCordovaClassLib.CordovaLib; namespace WPCordovaClassLib { public partial class CordovaView : UserControl { /// <summary> /// Indicates whether web control has been loaded and no additional initialization is needed. /// Prevents data clearing during page transitions. /// </summary> private bool IsBrowserInitialized = false; /// <summary> /// Set when the user attaches a back button handler inside the WebBrowser /// </summary> private bool OverrideBackButton = false; /// <summary> /// Sentinel to keep track of page changes as a result of the hardware back button /// Set to false when the back-button is pressed, which calls js window.history.back() /// If the page changes as a result of the back button the event is cancelled. /// </summary> private bool PageDidChange = false; private static string AppRoot = "/app/"; /// <summary> /// Handles native api calls /// </summary> private NativeExecution nativeExecution; protected BrowserMouseHelper bmHelper; private ConfigHandler configHandler; private Dictionary<string, IBrowserDecorator> browserDecorators; public System.Windows.Controls.Grid _LayoutRoot { get { return ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); } } public WebBrowser Browser { get { return CordovaBrowser; } } /* * Setting StartPageUri only has an effect if called before the view is loaded. **/ protected Uri _startPageUri = null; public Uri StartPageUri { get { if (_startPageUri == null) { // default return new Uri(AppRoot + "www/index.html", UriKind.Relative); } else { return _startPageUri; } } set { if (!this.IsBrowserInitialized) { _startPageUri = value; } } } public CordovaView() { InitializeComponent(); if (DesignerProperties.IsInDesignTool) { return; } StartupMode mode = PhoneApplicationService.Current.StartupMode; if (mode == StartupMode.Launch) { PhoneApplicationService service = PhoneApplicationService.Current; service.Activated += new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(AppActivated); service.Launching += new EventHandler<LaunchingEventArgs>(AppLaunching); service.Deactivated += new EventHandler<DeactivatedEventArgs>(AppDeactivated); service.Closing += new EventHandler<ClosingEventArgs>(AppClosing); } else { } configHandler = new ConfigHandler(); configHandler.LoadAppPackageConfig(); if (configHandler.ContentSrc != null) { if (Uri.IsWellFormedUriString(configHandler.ContentSrc, UriKind.Absolute)) { this.StartPageUri = new Uri(configHandler.ContentSrc, UriKind.Absolute); } else { this.StartPageUri = new Uri(AppRoot + "www/" + configHandler.ContentSrc, UriKind.Relative); } } browserDecorators = new Dictionary<string, IBrowserDecorator>(); // initializes native execution logic nativeExecution = new NativeExecution(ref this.CordovaBrowser); bmHelper = new BrowserMouseHelper(ref this.CordovaBrowser); CreateDecorators(); } /* * browserDecorators are a collection of plugin-like classes (IBrowserDecorator) that add some bit of functionality to the browser. * These are somewhat different than plugins in that they are usually not async and patch a browser feature that we would * already expect to have. Essentially these are browser polyfills that are patched from the outside in. * */ void CreateDecorators() { XHRHelper xhrProxy = new XHRHelper(); xhrProxy.Browser = CordovaBrowser; browserDecorators.Add("XHRLOCAL", xhrProxy); OrientationHelper orientHelper = new OrientationHelper(); orientHelper.Browser = CordovaBrowser; browserDecorators.Add("Orientation", orientHelper); DOMStorageHelper storageHelper = new DOMStorageHelper(); storageHelper.Browser = CordovaBrowser; browserDecorators.Add("DOMStorage", storageHelper); ConsoleHelper console = new ConsoleHelper(); console.Browser = CordovaBrowser; browserDecorators.Add("ConsoleLog", console); } void AppClosing(object sender, ClosingEventArgs e) { //Debug.WriteLine("AppClosing"); } void AppDeactivated(object sender, DeactivatedEventArgs e) { Debug.WriteLine("INFO: AppDeactivated"); try { CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('pause');" }); } catch (Exception) { Debug.WriteLine("ERROR: Pause event error"); } } void AppLaunching(object sender, LaunchingEventArgs e) { //Debug.WriteLine("INFO: AppLaunching"); } void AppActivated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e) { Debug.WriteLine("INFO: AppActivated"); try { CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('resume');" }); } catch (Exception) { Debug.WriteLine("ERROR: Resume event error"); } } void GapBrowser_Loaded(object sender, RoutedEventArgs e) { if (DesignerProperties.IsInDesignTool) { return; } // prevents refreshing web control to initial state during pages transitions if (this.IsBrowserInitialized) return; try { // Before we possibly clean the ISO-Store, we need to grab our generated UUID, so we can rewrite it after. string deviceUUID = ""; using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication()) { try { IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Open, FileAccess.Read, appStorage); using (StreamReader reader = new StreamReader(fileStream)) { deviceUUID = reader.ReadLine(); } } catch (Exception /*ex*/) { deviceUUID = Guid.NewGuid().ToString(); Debug.WriteLine("Updating IsolatedStorage for APP:DeviceID :: " + deviceUUID); IsolatedStorageFileStream file = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Create, FileAccess.Write, appStorage); using (StreamWriter writeFile = new StreamWriter(file)) { writeFile.WriteLine(deviceUUID); writeFile.Close(); } } } StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("CordovaSourceDictionary.xml", UriKind.Relative)); if (streamInfo != null) { StreamReader sr = new StreamReader(streamInfo.Stream); //This will Read Keys Collection for the xml file XDocument document = XDocument.Parse(sr.ReadToEnd()); var files = from results in document.Descendants("FilePath") select new { path = (string)results.Attribute("Value") }; StreamResourceInfo fileResourceStreamInfo; using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication()) { foreach (var file in files) { fileResourceStreamInfo = Application.GetResourceStream(new Uri(file.path, UriKind.Relative)); if (fileResourceStreamInfo != null) { using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream)) { byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length); string strBaseDir = AppRoot + file.path.Substring(0, file.path.LastIndexOf(System.IO.Path.DirectorySeparatorChar)); if (!appStorage.DirectoryExists(strBaseDir)) { Debug.WriteLine("INFO: Creating Directory :: " + strBaseDir); appStorage.CreateDirectory(strBaseDir); } // This will truncate/overwrite an existing file, or using (IsolatedStorageFileStream outFile = appStorage.OpenFile(AppRoot + file.path, FileMode.Create)) { Debug.WriteLine("INFO: Writing data for " + AppRoot + file.path + " and length = " + data.Length); using (var writer = new BinaryWriter(outFile)) { writer.Write(data); } } } } else { Debug.WriteLine("ERROR: Failed to write file :: " + file.path + " did you forget to add it to the project?"); } } } } CordovaBrowser.Navigate(StartPageUri); IsBrowserInitialized = true; AttachHardwareButtonHandlers(); } catch (Exception ex) { Debug.WriteLine("ERROR: Exception in GapBrowser_Loaded :: {0}", ex.Message); } } void AttachHardwareButtonHandlers() { PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { page.BackKeyPress += new EventHandler<CancelEventArgs>(page_BackKeyPress); // CB-2347 -jm string fullscreen = configHandler.GetPreference("fullscreen"); bool bFullScreen = false; if (bool.TryParse(fullscreen, out bFullScreen) && bFullScreen) { SystemTray.SetIsVisible(page, false); } } } } void page_BackKeyPress(object sender, CancelEventArgs e) { if (OverrideBackButton) { try { CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('backbutton', {}, true);" }); e.Cancel = true; } catch (Exception ex) { Debug.WriteLine("Exception while invoking backbutton into cordova view: " + ex.Message); } } else { try { PageDidChange = false; Uri uriBefore = this.Browser.Source; // calling js history.back with result in a page change if history was valid. CordovaBrowser.InvokeScript("eval", new string[] { "(function(){window.history.back();})()" }); Uri uriAfter = this.Browser.Source; e.Cancel = PageDidChange || (uriBefore != uriAfter); } catch (Exception) { e.Cancel = false; // exit the app ... ? } } } void GapBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e) { string nativeReady = "(function(){ window.setTimeout(function(){cordova.require('cordova/channel').onNativeReady.fire()},0) })();"; try { CordovaBrowser.InvokeScript("execScript", new string[] { nativeReady }); } catch (Exception) { Debug.WriteLine("Error calling js to fire nativeReady event. Did you include cordova.js in your html script tag?"); } if (this.CordovaBrowser.Opacity < 1) { this.CordovaBrowser.Opacity = 1; RotateIn.Begin(); } } void GapBrowser_Navigating(object sender, NavigatingEventArgs e) { if (!configHandler.URLIsAllowed(e.Uri.ToString())) { e.Cancel = true; return; } this.PageDidChange = true; // Debug.WriteLine("GapBrowser_Navigating to :: " + e.Uri.ToString()); this.nativeExecution.ResetAllCommands(); // TODO: check whitelist / blacklist // NOTE: Navigation can be cancelled by setting : e.Cancel = true; } /* * This method does the work of routing commands * NotifyEventArgs.Value contains a string passed from JS * If the command already exists in our map, we will just attempt to call the method(action) specified, and pass the args along * Otherwise, we create a new instance of the command, add it to the map, and call it ... * This method may also receive JS error messages caught by window.onerror, in any case where the commandStr does not appear to be a valid command * it is simply output to the debugger output, and the method returns. * **/ void GapBrowser_ScriptNotify(object sender, NotifyEventArgs e) { string commandStr = e.Value; string commandName = commandStr.Split('/').FirstOrDefault(); if (browserDecorators.ContainsKey(commandName)) { browserDecorators[commandName].HandleCommand(commandStr); return; } CordovaCommandCall commandCallParams = CordovaCommandCall.Parse(commandStr); if (commandCallParams == null) { // ERROR Debug.WriteLine("ScriptNotify :: " + commandStr); } else if (commandCallParams.Service == "CoreEvents") { switch (commandCallParams.Action.ToLower()) { case "overridebackbutton": string arg0 = JsonHelper.Deserialize<string[]>(commandCallParams.Args)[0]; this.OverrideBackButton = (arg0 != null && arg0.Length > 0 && arg0.ToLower() == "true"); break; } } else { if (configHandler.IsPluginAllowed(commandCallParams.Service)) { nativeExecution.ProcessCommand(commandCallParams); } else { Debug.WriteLine("Error::Plugin not allowed in config.xml. " + commandCallParams.Service); } } } public void LoadPage(string url) { try { Uri newLoc = new Uri(url, UriKind.RelativeOrAbsolute); CordovaBrowser.Navigate(newLoc); } catch (Exception) { } } private void GapBrowser_Unloaded(object sender, RoutedEventArgs e) { } private void GapBrowser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e) { Debug.WriteLine("GapBrowser_NavigationFailed :: " + e.Uri.ToString()); } private void GapBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { Debug.WriteLine("GapBrowser_Navigated :: " + e.Uri.ToString()); foreach (IBrowserDecorator iBD in browserDecorators.Values) { iBD.InjectScript(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.Primitives; using Microsoft.AspNetCore.Internal; using Microsoft.Net.Http.Headers; using System.Linq; namespace Microsoft.AspNetCore.Http { internal class RequestCookieCollection : IRequestCookieCollection { public static readonly RequestCookieCollection Empty = new RequestCookieCollection(); private static readonly string[] EmptyKeys = Array.Empty<string>(); // Pre-box private static readonly IEnumerator<KeyValuePair<string, string>> EmptyIEnumeratorType = default(Enumerator); private static readonly IEnumerator EmptyIEnumerator = default(Enumerator); private AdaptiveCapacityDictionary<string, string> Store { get; set; } public RequestCookieCollection() { Store = new AdaptiveCapacityDictionary<string, string>(StringComparer.OrdinalIgnoreCase); } public RequestCookieCollection(int capacity) { Store = new AdaptiveCapacityDictionary<string, string>(capacity, StringComparer.OrdinalIgnoreCase); } // For tests public RequestCookieCollection(Dictionary<string, string> store) { Store = new AdaptiveCapacityDictionary<string, string>(store); } public string? this[string key] { get { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (Store == null) { return null; } if (TryGetValue(key, out var value)) { return value; } return null; } } public static RequestCookieCollection Parse(StringValues values) => ParseInternal(values, AppContext.TryGetSwitch(ResponseCookies.EnableCookieNameEncoding, out var enabled) && enabled); internal static RequestCookieCollection ParseInternal(StringValues values, bool enableCookieNameEncoding) { if (values.Count == 0) { return Empty; } // Do not set the collection capacity based on StringValues.Count, the Cookie header is supposed to be a single combined value. var collection = new RequestCookieCollection(); var store = collection.Store!; if (CookieHeaderParserShared.TryParseValues(values, store, enableCookieNameEncoding, supportsMultipleValues: true)) { if (store.Count == 0) { return Empty; } return collection; } return Empty; } public int Count { get { if (Store == null) { return 0; } return Store.Count; } } public ICollection<string> Keys { get { if (Store == null) { return EmptyKeys; } return Store.Keys; } } public bool ContainsKey(string key) { if (Store == null) { return false; } return Store.ContainsKey(key); } public bool TryGetValue(string key, [MaybeNullWhen(false)] out string? value) { if (Store == null) { value = null; return false; } return Store.TryGetValue(key, out value); } /// <summary> /// Returns an struct enumerator that iterates through a collection without boxing. /// </summary> /// <returns>An <see cref="Enumerator" /> object that can be used to iterate through the collection.</returns> public Enumerator GetEnumerator() { if (Store == null || Store.Count == 0) { // Non-boxed Enumerator return default; } // Non-boxed Enumerator return new Enumerator(Store.GetEnumerator()); } /// <summary> /// Returns an enumerator that iterates through a collection, boxes in non-empty path. /// </summary> /// <returns>An <see cref="IEnumerator{T}" /> object that can be used to iterate through the collection.</returns> IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator() { if (Store == null || Store.Count == 0) { // Non-boxed Enumerator return EmptyIEnumeratorType; } // Boxed Enumerator return GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection, boxes in non-empty path. /// </summary> /// <returns>An <see cref="IEnumerator" /> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { if (Store == null || Store.Count == 0) { // Non-boxed Enumerator return EmptyIEnumerator; } // Boxed Enumerator return GetEnumerator(); } public struct Enumerator : IEnumerator<KeyValuePair<string, string>> { // Do NOT make this readonly, or MoveNext will not work private AdaptiveCapacityDictionary<string, string>.Enumerator _dictionaryEnumerator; private readonly bool _notEmpty; internal Enumerator(AdaptiveCapacityDictionary<string, string>.Enumerator dictionaryEnumerator) { _dictionaryEnumerator = dictionaryEnumerator; _notEmpty = true; } public bool MoveNext() { if (_notEmpty) { return _dictionaryEnumerator.MoveNext(); } return false; } public KeyValuePair<string, string> Current { get { if (_notEmpty) { var current = _dictionaryEnumerator.Current; return new KeyValuePair<string, string>(current.Key, (string)current.Value!); } return default(KeyValuePair<string, string>); } } object IEnumerator.Current { get { return Current; } } public void Dispose() { } public void Reset() { if (_notEmpty) { ((IEnumerator)_dictionaryEnumerator).Reset(); } } } } }
using System; using System.ComponentModel; using System.IO; using System.Text; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.IO.Pem; using Org.BouncyCastle.X509; using PemReader = Org.BouncyCastle.Utilities.IO.Pem.PemReader; using PemWriter = Org.BouncyCastle.Utilities.IO.Pem.PemWriter; namespace AllAuth.Lib.Crypto { public static class AsymmetricCryptoUtil { public static KeyPair GenerateKeyPair() { return GenerateKeyPair(KeyPair.KeyTypeDefault); } public static KeyPair GenerateKeyPair(KeyPair.KeyTypes type) { AsymmetricCipherKeyPair generatedKeyPair; switch (type) { case KeyPair.KeyTypes.Ecc: generatedKeyPair = GenerateKeyPairEcc(); break; case KeyPair.KeyTypes.Rsa: generatedKeyPair = GenerateKeyPairRsa(); break; default: throw new InvalidEnumArgumentException("Invalid key type"); } var pubKeyPem = ConvertPublicKeyToPem(generatedKeyPair.Public); var privKeyPem = ConvertPrivateKeyToPem(generatedKeyPair.Private); return new KeyPair(type, privKeyPem, pubKeyPem); } private static AsymmetricCipherKeyPair GenerateKeyPairEcc() { var oid = X962NamedCurves.GetOid("prime256v1"); var generator = new ECKeyPairGenerator(); var genParam = new ECKeyGenerationParameters(oid, RandomUtil.SecureRandomBc); generator.Init(genParam); return generator.GenerateKeyPair(); } private static AsymmetricCipherKeyPair GenerateKeyPairRsa() { var generator = GeneratorUtilities.GetKeyPairGenerator("RSA"); var generatorParams = new RsaKeyGenerationParameters( new BigInteger("10001", 16), RandomUtil.SecureRandomBc, 2048, 112); generator.Init(generatorParams); return generator.GenerateKeyPair(); } private static string ConvertPublicKeyToPem(AsymmetricKeyParameter pubKey) { using (var stringWriter = new StringWriter()) { var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey); var pemWriter = new PemWriter(stringWriter); PemObjectGenerator pemObject = new PemObject("PUBLIC KEY", publicKeyInfo.GetEncoded()); pemWriter.WriteObject(pemObject); return stringWriter.ToString(); } } private static string ConvertPrivateKeyToPem(AsymmetricKeyParameter privateKey) { using (var stringWriter = new StringWriter()) { var pkcsgen = new Pkcs8Generator(privateKey); var pemwriter = new PemWriter(stringWriter); pemwriter.WriteObject(pkcsgen.Generate()); return stringWriter.ToString(); } } private static AsymmetricKeyParameter ConvertPemToPublicKey(string pem) { using (var stringReader = new StringReader(pem)) { var pemReader = new PemReader(stringReader); return PublicKeyFactory.CreateKey(pemReader.ReadPemObject().Content); } } internal static AsymmetricKeyParameter ConvertPemToPrivateKey(string pem) { var pemReader = new PemReader(new StringReader(pem)); var key = PrivateKeyFactory.CreateKey(pemReader.ReadPemObject().Content); return key; } public static string CreateSignature(string message, string privateKeyPem) { return Convert.ToBase64String(CreateSignature(Encoding.UTF8.GetBytes(message), privateKeyPem)); } internal static byte[] CreateSignature(byte[] message, string privateKeyPem) { var privateKey = ConvertPemToPrivateKey(privateKeyPem); var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ConvertPemToPrivateKey(privateKeyPem)); ISigner signer; switch (privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Id) { case "1.2.840.10045.2.1": // EC Key signer = SignerUtilities.GetSigner("SHA256withECDSA"); break; case "1.2.840.113549.1.1.1": // RSA key signer = SignerUtilities.GetSigner("SHA256withRSA"); break; default: throw new ArgumentException( "Unsupported key type " + privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Id, nameof(privateKeyPem)); } signer.Init(true, privateKey); var stringToSignInBytes = message; signer.BlockUpdate(stringToSignInBytes, 0, stringToSignInBytes.Length); var signature = signer.GenerateSignature(); return signature; } public static bool VerifySignature(string message, string signature, string publicKeyPem) { return VerifySignature( Encoding.UTF8.GetBytes(message), Convert.FromBase64String(signature), publicKeyPem); } internal static bool VerifySignature(byte[] message, byte[] signature, string publicKeyPem) { var publicKey = ConvertPemToPublicKey(publicKeyPem); var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); ISigner signer; switch (publicKeyInfo.AlgorithmID.Algorithm.Id) { case "1.2.840.10045.2.1": // EC Key signer = SignerUtilities.GetSigner("SHA256withECDSA"); break; case "1.2.840.113549.1.1.1": // RSA Key signer = SignerUtilities.GetSigner("SHA256withRSA"); break; default: throw new ArgumentException( "Unsupported key type " + publicKeyInfo.AlgorithmID.Algorithm.Id, nameof(publicKey)); } signer.Init(false, publicKey); signer.BlockUpdate(message, 0, message.Length); return signer.VerifySignature(signature); } internal static byte[] EncryptDataWithPublicKey(byte[] data, string publicKeyPem) { var recipientPublicKey = ConvertPemToPublicKey(publicKeyPem); var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(recipientPublicKey); switch (publicKeyInfo.AlgorithmID.Algorithm.Id) { // case "1.2.840.10045.2.1": // // EC Key // break; case "1.2.840.113549.1.1.1": // RSA Key return EncryptDataWithPublicKeyRsa(data, (RsaKeyParameters)recipientPublicKey); default: throw new ArgumentException( "Unsupported key type " + publicKeyInfo.AlgorithmID.Algorithm.Id, nameof(publicKeyPem)); } } private static byte[] EncryptDataWithPublicKeyRsa(byte[] encryptedData, RsaKeyParameters publicKey) { var cipher = CipherUtilities.GetCipher("RSA//PKCS1Padding"); cipher.Init(true, publicKey); return cipher.DoFinal(encryptedData); } internal static byte[] DecryptDataWithPrivateKey(byte[] encryptedData, string privateKeyPem) { var privateKey = ConvertPemToPrivateKey(privateKeyPem); var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); switch (privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Id) { // case "1.2.840.10045.2.1": // // EC Key // break; case "1.2.840.113549.1.1.1": // RSA key return DecryptDataWithPrivateKeyRsa(encryptedData, (RsaKeyParameters)privateKey); default: throw new ArgumentException( "Unsupported key type " + privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Id, nameof(privateKeyPem)); } } private static byte[] DecryptDataWithPrivateKeyRsa(byte[] encryptedData, RsaKeyParameters privateKey) { var cipher = CipherUtilities.GetCipher("RSA//PKCS1Padding"); cipher.Init(false, privateKey); return cipher.DoFinal(encryptedData); } } }
// // System.Web.Services.Protocols.HttpWebClientProtocol.cs // // Author: // Tim Coleman (tim@timcoleman.com) // // Copyright (C) Tim Coleman, 2002 // // // 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.ComponentModel; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Web.Services; using System.Collections; namespace System.Web.Services.Protocols { public abstract class HttpWebClientProtocol : WebClientProtocol { #region Fields bool allowAutoRedirect; X509CertificateCollection clientCertificates; CookieContainer cookieContainer; IWebProxy proxy; string userAgent; #if NET_1_1 bool _unsafeAuthenticated; #endif #endregion #region Constructors protected HttpWebClientProtocol () { allowAutoRedirect = false; clientCertificates = null; cookieContainer = null; proxy = null; // FIXME userAgent = String.Format ("Mono Web Services Client Protocol {0}", Environment.Version); } #endregion // Constructors #region Properties [DefaultValue (false)] [WebServicesDescription ("Enable automatic handling of server redirects.")] public bool AllowAutoRedirect { get { return allowAutoRedirect; } set { allowAutoRedirect = value; } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] [WebServicesDescription ("The client certificates that will be sent to the server, if the server requests them.")] public X509CertificateCollection ClientCertificates { get { if (clientCertificates == null) clientCertificates = new X509CertificateCollection (); return clientCertificates; } } [DefaultValue (null)] [WebServicesDescription ("A container for all cookies received from servers in the current session.")] public CookieContainer CookieContainer { get { return cookieContainer; } set { cookieContainer = value; } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public IWebProxy Proxy { get { return proxy; } set { proxy = value; } } [WebServicesDescription ("Sets the user agent http header for the request.")] public string UserAgent { get { return userAgent; } set { userAgent = value; } } #if NET_1_1 public bool UnsafeAuthenticatedConnectionSharing { get { return _unsafeAuthenticated; } set { _unsafeAuthenticated = value; } } #endif #endregion // Properties #region Methods internal virtual void CheckForCookies (HttpWebResponse response) { CookieCollection cookies = response.Cookies; if (cookieContainer == null || cookies.Count == 0) return; CookieCollection coll = cookieContainer.GetCookies (uri); foreach (Cookie c in cookies) { bool add = true; foreach (Cookie prev in coll) { if (c.Equals (prev)) { add = false; break; } } if (add) cookieContainer.Add (c); } } protected override WebRequest GetWebRequest (Uri uri) { WebRequest req = base.GetWebRequest (uri); HttpWebRequest request = req as HttpWebRequest; if (request == null) return req; request.AllowAutoRedirect = allowAutoRedirect; if (clientCertificates != null) request.ClientCertificates.AddRange (clientCertificates); request.CookieContainer = cookieContainer; if (proxy != null) request.Proxy = proxy; request.UserAgent = userAgent; #if NET_1_1 // request.UnsafeAuthenticatedConnectionSharing = _unsafeAuthenticated; #endif return request; } protected override WebResponse GetWebResponse (WebRequest request) { WebResponse response = base.GetWebResponse (request); HttpWebResponse wr = response as HttpWebResponse; if (wr != null) CheckForCookies (wr); return response; } protected override WebResponse GetWebResponse (WebRequest request, IAsyncResult result) { WebResponse response = base.GetWebResponse (request, result); HttpWebResponse wr = response as HttpWebResponse; if (wr != null) CheckForCookies (wr); return response; } #if NET_2_0 [MonoTODO] protected void CancelAsync (object userState) { throw new NotImplementedException (); } [MonoTODO] public static bool GenerateXmlMappings (Type type, ArrayList mapping) { throw new NotImplementedException (); } [MonoTODO] public static Hashtable GenerateXmlMappings (Type[] types, ArrayList mapping) { throw new NotImplementedException (); } #endif #endregion // Methods } #if NET_2_0 internal class InvokeAsyncInfo { public SynchronizationContext Context; public object UserState; public SendOrPostCallback Callback; public InvokeAsyncInfo (SendOrPostCallback callback, object userState) { Callback = callback; UserState = userState; Context = SynchronizationContext.Current; } } #endif }
(>= (f208 (var x3)) (var x3)) (>= (f209 (var x3)) (f208 (var x3))) (>= (f210 (var x42)) (var x42)) (>= (f211 (var x43)) (var x43)) (>= (f1 (var x42) (f212)) (+ (f210 (var x42)) 1)) (>= (+ (f2 (var x42) (f212)) (var x43)) (f211 (var x43))) (>= (f213 (var x3)) (f209 (var x3))) (>= (f214 (var x2)) (var x2)) (>= (f215 (var x1)) (var x1)) (>= (f216 (var x1) (var x2) (var x3) (var x42) (var x43)) (+ (f6 (f212) (f215 (var x1)) (f214 (var x2)) (f216 (var x1) (var x2) (var x3) (var x42) (var x43))) (f213 (var x3)))) (>= (f217 (var x1) (var x2) (var x3) (var x42) (var x43)) (+ (f5 (f212) (f215 (var x1)) (f214 (var x2))) (f216 (var x1) (var x2) (var x3) (var x42) (var x43)))) (>= (f8 (var x1) (var x2)) (f4 (f212) (f215 (var x1)) (f214 (var x2)))) (>= (f7 (var x1) (var x2)) (f3 (f212) (f215 (var x1)) (f214 (var x2)))) (>= (+ (f9 (var x1) (var x2)) (var x3)) (+ (f217 (var x1) (var x2) (var x3) (var x42) (var x43)) 1)) (>= (f218 (var x7)) (var x7)) (>= (f219 (var x7)) (f218 (var x7))) (>= (f220 (var x85)) (var x85)) (>= (f221 (var x86)) (var x86)) (>= (f1 (var x85) (f222 (var x4))) (f1 (f220 (var x85)) (var x4))) (>= (+ (f2 (var x85) (f222 (var x4))) (var x86)) (+ (f2 (f220 (var x85)) (var x4)) (f221 (var x86)))) (>= (f223 (var x7)) (f219 (var x7))) (>= (f224 (var x9)) (var x9)) (>= (f225 (var x5)) (var x5)) (>= (f226 (var x4) (var x5) (var x7) (var x9) (var x85) (var x86)) (+ (f6 (f222 (var x4)) (f225 (var x5)) (f224 (var x9)) (f226 (var x4) (var x5) (var x7) (var x9) (var x85) (var x86))) (f223 (var x7)))) (>= (f227 (var x4) (var x5) (var x9) (var x85) (var x86)) (f4 (f222 (var x4)) (f225 (var x5)) (f224 (var x9)))) (>= (f228 (var x4) (var x5) (var x9) (var x10) (var x85) (var x86) (var x134) (var x135)) (f3 (f222 (var x4)) (f225 (var x5)) (f224 (var x9)))) (>= (f229 (var x4) (var x5) (var x7) (var x9) (var x85) (var x86)) (+ (f5 (f222 (var x4)) (f225 (var x5)) (f224 (var x9))) (f226 (var x4) (var x5) (var x7) (var x9) (var x85) (var x86)))) (>= (f230 (var x4) (var x5) (var x7) (var x9) (var x85) (var x86)) (f229 (var x4) (var x5) (var x7) (var x9) (var x85) (var x86))) (>= (f231 (var x134)) (var x134)) (>= (f232 (var x135)) (var x135)) (>= (f1 (var x134) (f233 (var x4))) (f1 (f231 (var x134)) (var x4))) (>= (+ (f2 (var x134) (f233 (var x4))) (var x135)) (+ (f2 (f231 (var x134)) (var x4)) (f232 (var x135)))) (>= (f234 (var x4) (var x5) (var x7) (var x9) (var x85) (var x86)) (f230 (var x4) (var x5) (var x7) (var x9) (var x85) (var x86))) (>= (f235 (var x10)) (var x10)) (>= (f236 (var x5)) (var x5)) (>= (f237 (var x4) (var x5) (var x7) (var x9) (var x10) (var x85) (var x86) (var x134) (var x135)) (+ (f6 (f233 (var x4)) (f236 (var x5)) (f235 (var x10)) (f237 (var x4) (var x5) (var x7) (var x9) (var x10) (var x85) (var x86) (var x134) (var x135))) (f234 (var x4) (var x5) (var x7) (var x9) (var x85) (var x86)))) (>= (f238 (var x4) (var x5) (var x10) (var x134) (var x135)) (f4 (f233 (var x4)) (f236 (var x5)) (f235 (var x10)))) (>= (f228 (var x4) (var x5) (var x9) (var x10) (var x85) (var x86) (var x134) (var x135)) (f3 (f233 (var x4)) (f236 (var x5)) (f235 (var x10)))) (>= (f239 (var x4) (var x5) (var x7) (var x9) (var x10) (var x85) (var x86) (var x134) (var x135)) (+ (f5 (f233 (var x4)) (f236 (var x5)) (f235 (var x10))) (f237 (var x4) (var x5) (var x7) (var x9) (var x10) (var x85) (var x86) (var x134) (var x135)))) (>= (f240 (var x4) (var x5) (var x7) (var x9) (var x10) (var x85) (var x86) (var x134) (var x135)) (f239 (var x4) (var x5) (var x7) (var x9) (var x10) (var x85) (var x86) (var x134) (var x135))) (>= (f4 (var x4) (var x5) (+ (+ (var x9) (var x10)) 1)) (+ (+ (f227 (var x4) (var x5) (var x9) (var x85) (var x86)) (f238 (var x4) (var x5) (var x10) (var x134) (var x135))) 1)) (>= (f3 (var x4) (var x5) (+ (+ (var x9) (var x10)) 1)) (f228 (var x4) (var x5) (var x9) (var x10) (var x85) (var x86) (var x134) (var x135))) (>= (+ (f5 (var x4) (var x5) (+ (+ (var x9) (var x10)) 1)) (var x7)) (+ (f240 (var x4) (var x5) (var x7) (var x9) (var x10) (var x85) (var x86) (var x134) (var x135)) 1)) (>= (f241 (var x16)) (var x16)) (>= (f242 (var x14)) (var x14)) (>= (f243 (var x16)) (f241 (var x16))) (>= (f244 (var x13) (var x14)) (f1 (f242 (var x14)) (var x13))) (>= (f245 (var x13) (var x14) (var x16)) (+ (f2 (f242 (var x14)) (var x13)) (f243 (var x16)))) (>= (f246 (var x13) (var x14) (var x16)) (f245 (var x13) (var x14) (var x16))) (>= (f4 (var x13) (var x14) 0) 0) (>= (f3 (var x13) (var x14) 0) (f244 (var x13) (var x14))) (>= (+ (f5 (var x13) (var x14) 0) (var x16)) (+ (f246 (var x13) (var x14) (var x16)) 1))
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.ServiceModel; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.Serialization; using System.Text; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.ServiceModel.Security; using System.IdentityModel.Claims; using System.IdentityModel.Policy; public sealed class AddressHeaderCollection : ReadOnlyCollection<AddressHeader> { static AddressHeaderCollection emptyHeaderCollection = new AddressHeaderCollection(); public AddressHeaderCollection() : base(new List<AddressHeader>()) { } public AddressHeaderCollection(IEnumerable<AddressHeader> addressHeaders) : base(new List<AddressHeader>(addressHeaders)) { // avoid allocating an enumerator when possible IList<AddressHeader> collection = addressHeaders as IList<AddressHeader>; if (collection != null) { for (int i = 0; i < collection.Count; i++) { if (collection[i] == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MessageHeaderIsNull0))); } } else { foreach (AddressHeader addressHeader in addressHeaders) { if (addressHeaders == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MessageHeaderIsNull0))); } } } internal static AddressHeaderCollection EmptyHeaderCollection { get { return emptyHeaderCollection; } } int InternalCount { get { if (this == (object)emptyHeaderCollection) return 0; return Count; } } public void AddHeadersTo(Message message) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); for (int i = 0; i < InternalCount; i++) { #pragma warning suppress 56506 // [....], Message.Headers can never be null message.Headers.Add(this[i].ToMessageHeader()); } } public AddressHeader[] FindAll(string name, string ns) { if (name == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name")); if (ns == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns")); List<AddressHeader> results = new List<AddressHeader>(); for (int i = 0; i < Count; i++) { AddressHeader header = this[i]; if (header.Name == name && header.Namespace == ns) { results.Add(header); } } return results.ToArray(); } public AddressHeader FindHeader(string name, string ns) { if (name == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name")); if (ns == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns")); AddressHeader matchingHeader = null; for (int i = 0; i < Count; i++) { AddressHeader header = this[i]; if (header.Name == name && header.Namespace == ns) { if (matchingHeader != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MultipleMessageHeaders, name, ns))); matchingHeader = header; } } return matchingHeader; } internal bool IsEquivalent(AddressHeaderCollection col) { if (InternalCount != col.InternalCount) return false; StringBuilder builder = new StringBuilder(); Dictionary<string, int> myHeaders = new Dictionary<string, int>(); PopulateHeaderDictionary(builder, myHeaders); Dictionary<string, int> otherHeaders = new Dictionary<string, int>(); col.PopulateHeaderDictionary(builder, otherHeaders); if (myHeaders.Count != otherHeaders.Count) return false; foreach (KeyValuePair<string, int> pair in myHeaders) { int count; if (otherHeaders.TryGetValue(pair.Key, out count)) { if (count != pair.Value) return false; } else { return false; } } return true; } internal void PopulateHeaderDictionary(StringBuilder builder, Dictionary<string, int> headers) { string key; for (int i = 0; i < InternalCount; ++i) { builder.Remove(0, builder.Length); key = this[i].GetComparableForm(builder); if (headers.ContainsKey(key)) { headers[key] = headers[key] + 1; } else { headers.Add(key, 1); } } } internal static AddressHeaderCollection ReadServiceParameters(XmlDictionaryReader reader) { return ReadServiceParameters(reader, false); } internal static AddressHeaderCollection ReadServiceParameters(XmlDictionaryReader reader, bool isReferenceProperty) { reader.MoveToContent(); if (reader.IsEmptyElement) { reader.Skip(); return null; } else { reader.ReadStartElement(); List<AddressHeader> headerList = new List<AddressHeader>(); while (reader.IsStartElement()) { headerList.Add(new BufferedAddressHeader(reader, isReferenceProperty)); } reader.ReadEndElement(); return new AddressHeaderCollection(headerList); } } internal bool HasReferenceProperties { get { for (int i = 0; i < InternalCount; i++) if (this[i].IsReferenceProperty) return true; return false; } } internal bool HasNonReferenceProperties { get { for (int i = 0; i < InternalCount; i++) if (!this[i].IsReferenceProperty) return true; return false; } } internal void WriteReferencePropertyContentsTo(XmlDictionaryWriter writer) { for (int i = 0; i < InternalCount; i++) if (this[i].IsReferenceProperty) this[i].WriteAddressHeader(writer); } internal void WriteNonReferencePropertyContentsTo(XmlDictionaryWriter writer) { for (int i = 0; i < InternalCount; i++) if (!this[i].IsReferenceProperty) this[i].WriteAddressHeader(writer); } internal void WriteContentsTo(XmlDictionaryWriter writer) { for (int i = 0; i < InternalCount; i++) this[i].WriteAddressHeader(writer); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { /// <devdoc> /// <para> /// Provides access to local and remote /// processes. Enables you to start and stop system processes. /// </para> /// </devdoc> public partial class Process : IDisposable { private bool _haveProcessId; private int _processId; private bool _haveProcessHandle; private SafeProcessHandle _processHandle; private bool _isRemoteMachine; private string _machineName; private ProcessInfo _processInfo; private ProcessThreadCollection _threads; private ProcessModuleCollection _modules; private bool _haveWorkingSetLimits; private IntPtr _minWorkingSet; private IntPtr _maxWorkingSet; private bool _haveProcessorAffinity; private IntPtr _processorAffinity; private bool _havePriorityClass; private ProcessPriorityClass _priorityClass; private ProcessStartInfo _startInfo; private bool _watchForExit; private bool _watchingForExit; private EventHandler _onExited; private bool _exited; private int _exitCode; private DateTime _exitTime; private bool _haveExitTime; private bool _priorityBoostEnabled; private bool _havePriorityBoostEnabled; private bool _raisedOnExited; private RegisteredWaitHandle _registeredWaitHandle; private WaitHandle _waitHandle; private StreamReader _standardOutput; private StreamWriter _standardInput; private StreamReader _standardError; private bool _disposed; private static object s_createProcessLock = new object(); private StreamReadMode _outputStreamReadMode; private StreamReadMode _errorStreamReadMode; // Support for asynchronously reading streams public event DataReceivedEventHandler OutputDataReceived; public event DataReceivedEventHandler ErrorDataReceived; // Abstract the stream details internal AsyncStreamReader _output; internal AsyncStreamReader _error; internal bool _pendingOutputRead; internal bool _pendingErrorRead; #if FEATURE_TRACESWITCH internal static TraceSwitch _processTracing = #if DEBUG new TraceSwitch("processTracing", "Controls debug output from Process component"); #else null; #endif #endif /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class. /// </para> /// </devdoc> public Process() { // This class once inherited a finalizer. For backward compatibility it has one so that // any derived class that depends on it will see the behaviour expected. Since it is // not used by this class itself, suppress it immediately if this is not an instance // of a derived class it doesn't suffer the GC burden of finalization. if (GetType() == typeof(Process)) { GC.SuppressFinalize(this); } _machineName = "."; _outputStreamReadMode = StreamReadMode.Undefined; _errorStreamReadMode = StreamReadMode.Undefined; } private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo) { GC.SuppressFinalize(this); _processInfo = processInfo; _machineName = machineName; _isRemoteMachine = isRemoteMachine; _processId = processId; _haveProcessId = true; _outputStreamReadMode = StreamReadMode.Undefined; _errorStreamReadMode = StreamReadMode.Undefined; } ~Process() { Dispose(false); } public SafeProcessHandle SafeHandle { get { EnsureState(State.Associated); return OpenProcessHandle(); } } /// <devdoc> /// Returns whether this process component is associated with a real process. /// </devdoc> /// <internalonly/> bool Associated { get { return _haveProcessId || _haveProcessHandle; } } /// <devdoc> /// <para> /// Gets the base priority of /// the associated process. /// </para> /// </devdoc> public int BasePriority { get { EnsureState(State.HaveProcessInfo); return _processInfo.BasePriority; } } /// <devdoc> /// <para> /// Gets /// the /// value that was specified by the associated process when it was terminated. /// </para> /// </devdoc> public int ExitCode { get { EnsureState(State.Exited); return _exitCode; } } /// <devdoc> /// <para> /// Gets a /// value indicating whether the associated process has been terminated. /// </para> /// </devdoc> public bool HasExited { get { if (!_exited) { EnsureState(State.Associated); UpdateHasExited(); if (_exited) { RaiseOnExited(); } } return _exited; } } /// <devdoc> /// <para> /// Gets the time that the associated process exited. /// </para> /// </devdoc> public DateTime ExitTime { get { if (!_haveExitTime) { EnsureState(State.Exited); _exitTime = ExitTimeCore; _haveExitTime = true; } return _exitTime; } } /// <devdoc> /// <para> /// Gets /// the unique identifier for the associated process. /// </para> /// </devdoc> public int Id { get { EnsureState(State.HaveId); return _processId; } } /// <devdoc> /// <para> /// Gets /// the name of the computer on which the associated process is running. /// </para> /// </devdoc> public string MachineName { get { EnsureState(State.Associated); return _machineName; } } /// <devdoc> /// <para> /// Gets or sets the maximum allowable working set for the associated /// process. /// </para> /// </devdoc> public IntPtr MaxWorkingSet { get { EnsureWorkingSetLimits(); return _maxWorkingSet; } set { SetWorkingSetLimits(null, value); } } /// <devdoc> /// <para> /// Gets or sets the minimum allowable working set for the associated /// process. /// </para> /// </devdoc> public IntPtr MinWorkingSet { get { EnsureWorkingSetLimits(); return _minWorkingSet; } set { SetWorkingSetLimits(value, null); } } public ProcessModuleCollection Modules { get { if (_modules == null) { EnsureState(State.HaveId | State.IsLocal); ModuleInfo[] moduleInfos = ProcessManager.GetModuleInfos(_processId); ProcessModule[] newModulesArray = new ProcessModule[moduleInfos.Length]; for (int i = 0; i < moduleInfos.Length; i++) { newModulesArray[i] = new ProcessModule(moduleInfos[i]); } ProcessModuleCollection newModules = new ProcessModuleCollection(newModulesArray); _modules = newModules; } return _modules; } } public long NonpagedSystemMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PoolNonPagedBytes; } } public long PagedMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PageFileBytes; } } public long PagedSystemMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PoolPagedBytes; } } public long PeakPagedMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PageFileBytesPeak; } } public long PeakWorkingSet64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.WorkingSetPeak; } } public long PeakVirtualMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.VirtualBytesPeak; } } /// <devdoc> /// <para> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </para> /// </devdoc> public bool PriorityBoostEnabled { get { if (!_havePriorityBoostEnabled) { _priorityBoostEnabled = PriorityBoostEnabledCore; _havePriorityBoostEnabled = true; } return _priorityBoostEnabled; } set { PriorityBoostEnabledCore = value; _priorityBoostEnabled = value; _havePriorityBoostEnabled = true; } } /// <devdoc> /// <para> /// Gets or sets the overall priority category for the /// associated process. /// </para> /// </devdoc> public ProcessPriorityClass PriorityClass { get { if (!_havePriorityClass) { _priorityClass = PriorityClassCore; _havePriorityClass = true; } return _priorityClass; } set { if (!Enum.IsDefined(typeof(ProcessPriorityClass), value)) { throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, nameof(value), (int)value, typeof(ProcessPriorityClass))); } PriorityClassCore = value; _priorityClass = value; _havePriorityClass = true; } } public long PrivateMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PrivateBytes; } } /// <devdoc> /// <para> /// Gets /// the friendly name of the process. /// </para> /// </devdoc> public string ProcessName { get { EnsureState(State.HaveProcessInfo); return _processInfo.ProcessName; } } /// <devdoc> /// <para> /// Gets /// or sets which processors the threads in this process can be scheduled to run on. /// </para> /// </devdoc> public IntPtr ProcessorAffinity { get { if (!_haveProcessorAffinity) { _processorAffinity = ProcessorAffinityCore; _haveProcessorAffinity = true; } return _processorAffinity; } set { ProcessorAffinityCore = value; _processorAffinity = value; _haveProcessorAffinity = true; } } public int SessionId { get { EnsureState(State.HaveProcessInfo); return _processInfo.SessionId; } } /// <devdoc> /// <para> /// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start'/> method for the <see cref='System.Diagnostics.Process'/> /// . /// </para> /// </devdoc> public ProcessStartInfo StartInfo { get { if (_startInfo == null) { if (Associated) { throw new InvalidOperationException(SR.CantGetProcessStartInfo); } _startInfo = new ProcessStartInfo(); } return _startInfo; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (Associated) { throw new InvalidOperationException(SR.CantSetProcessStartInfo); } _startInfo = value; } } /// <devdoc> /// <para> /// Gets the set of threads that are running in the associated /// process. /// </para> /// </devdoc> public ProcessThreadCollection Threads { get { if (_threads == null) { EnsureState(State.HaveProcessInfo); int count = _processInfo._threadInfoList.Count; ProcessThread[] newThreadsArray = new ProcessThread[count]; for (int i = 0; i < count; i++) { newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]); } ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray); _threads = newThreads; } return _threads; } } public long VirtualMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.VirtualBytes; } } /// <devdoc> /// <para> /// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/> /// event is fired /// when the process terminates. /// </para> /// </devdoc> public bool EnableRaisingEvents { get { return _watchForExit; } set { if (value != _watchForExit) { if (Associated) { if (value) { OpenProcessHandle(); EnsureWatchingForExit(); } else { StopWatchingForExit(); } } _watchForExit = value; } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamWriter StandardInput { get { if (_standardInput == null) { throw new InvalidOperationException(SR.CantGetStandardIn); } return _standardInput; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamReader StandardOutput { get { if (_standardOutput == null) { throw new InvalidOperationException(SR.CantGetStandardOut); } if (_outputStreamReadMode == StreamReadMode.Undefined) { _outputStreamReadMode = StreamReadMode.SyncMode; } else if (_outputStreamReadMode != StreamReadMode.SyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } return _standardOutput; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamReader StandardError { get { if (_standardError == null) { throw new InvalidOperationException(SR.CantGetStandardError); } if (_errorStreamReadMode == StreamReadMode.Undefined) { _errorStreamReadMode = StreamReadMode.SyncMode; } else if (_errorStreamReadMode != StreamReadMode.SyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } return _standardError; } } public long WorkingSet64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.WorkingSet; } } public event EventHandler Exited { add { _onExited += value; } remove { _onExited -= value; } } /// <devdoc> /// Release the temporary handle we used to get process information. /// If we used the process handle stored in the process object (we have all access to the handle,) don't release it. /// </devdoc> /// <internalonly/> private void ReleaseProcessHandle(SafeProcessHandle handle) { if (handle == null) { return; } if (_haveProcessHandle && handle == _processHandle) { return; } #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process)"); #endif handle.Dispose(); } /// <devdoc> /// This is called from the threadpool when a process exits. /// </devdoc> /// <internalonly/> private void CompletionCallback(object context, bool wasSignaled) { StopWatchingForExit(); RaiseOnExited(); } /// <internalonly/> /// <devdoc> /// <para> /// Free any resources associated with this component. /// </para> /// </devdoc> protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { //Dispose managed and unmanaged resources Close(); } _disposed = true; } } /// <devdoc> /// <para> /// Frees any resources associated with this component. /// </para> /// </devdoc> internal void Close() { if (Associated) { if (_haveProcessHandle) { StopWatchingForExit(); #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()"); #endif _processHandle.Dispose(); _processHandle = null; _haveProcessHandle = false; } _haveProcessId = false; _isRemoteMachine = false; _machineName = "."; _raisedOnExited = false; //Don't call close on the Readers and writers //since they might be referenced by somebody else while the //process is still alive but this method called. _standardOutput = null; _standardInput = null; _standardError = null; _output = null; _error = null; CloseCore(); Refresh(); } } /// <devdoc> /// Helper method for checking preconditions when accessing properties. /// </devdoc> /// <internalonly/> private void EnsureState(State state) { if ((state & State.Associated) != (State)0) if (!Associated) throw new InvalidOperationException(SR.NoAssociatedProcess); if ((state & State.HaveId) != (State)0) { if (!_haveProcessId) { if (_haveProcessHandle) { SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle)); } else { EnsureState(State.Associated); throw new InvalidOperationException(SR.ProcessIdRequired); } } } if ((state & State.IsLocal) != (State)0 && _isRemoteMachine) { throw new NotSupportedException(SR.NotSupportedRemote); } if ((state & State.HaveProcessInfo) != (State)0) { if (_processInfo == null) { if ((state & State.HaveId) == (State)0) EnsureState(State.HaveId); _processInfo = ProcessManager.GetProcessInfo(_processId, _machineName); if (_processInfo == null) { throw new InvalidOperationException(SR.NoProcessInfo); } } } if ((state & State.Exited) != (State)0) { if (!HasExited) { throw new InvalidOperationException(SR.WaitTillExit); } if (!_haveProcessHandle) { throw new InvalidOperationException(SR.NoProcessHandle); } } } /// <devdoc> /// Make sure we are watching for a process exit. /// </devdoc> /// <internalonly/> private void EnsureWatchingForExit() { if (!_watchingForExit) { lock (this) { if (!_watchingForExit) { Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle"); Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process"); _watchingForExit = true; try { _waitHandle = new ProcessWaitHandle(_processHandle); _registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(CompletionCallback), null, -1, true); } catch { _watchingForExit = false; throw; } } } } } /// <devdoc> /// Make sure we have obtained the min and max working set limits. /// </devdoc> /// <internalonly/> private void EnsureWorkingSetLimits() { if (!_haveWorkingSetLimits) { GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet); _haveWorkingSetLimits = true; } } /// <devdoc> /// Helper to set minimum or maximum working set limits. /// </devdoc> /// <internalonly/> private void SetWorkingSetLimits(IntPtr? min, IntPtr? max) { SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet); _haveWorkingSetLimits = true; } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and /// the name of a computer in the network. /// </para> /// </devdoc> public static Process GetProcessById(int processId, string machineName) { if (!ProcessManager.IsProcessRunning(processId, machineName)) { throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture))); } return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null); } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> component given the /// identifier of a process on the local computer. /// </para> /// </devdoc> public static Process GetProcessById(int processId) { return GetProcessById(processId, "."); } /// <devdoc> /// <para> /// Creates an array of <see cref='System.Diagnostics.Process'/> components that are /// associated /// with process resources on the /// local computer. These process resources share the specified process name. /// </para> /// </devdoc> public static Process[] GetProcessesByName(string processName) { return GetProcessesByName(processName, "."); } /// <devdoc> /// <para> /// Creates a new <see cref='System.Diagnostics.Process'/> /// component for each process resource on the local computer. /// </para> /// </devdoc> public static Process[] GetProcesses() { return GetProcesses("."); } /// <devdoc> /// <para> /// Creates a new <see cref='System.Diagnostics.Process'/> /// component for each /// process resource on the specified computer. /// </para> /// </devdoc> public static Process[] GetProcesses(string machineName) { bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName); ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName); Process[] processes = new Process[processInfos.Length]; for (int i = 0; i < processInfos.Length; i++) { ProcessInfo processInfo = processInfos[i]; processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo); } #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process.GetProcesses(" + machineName + ")"); #if DEBUG if (_processTracing.TraceVerbose) { Debug.Indent(); for (int i = 0; i < processInfos.Length; i++) { Debug.WriteLine(processes[i].Id + ": " + processes[i].ProcessName); } Debug.Unindent(); } #endif #endif return processes; } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> /// component and associates it with the current active process. /// </para> /// </devdoc> public static Process GetCurrentProcess() { return new Process(".", false, GetCurrentProcessId(), null); } /// <devdoc> /// <para> /// Raises the <see cref='System.Diagnostics.Process.Exited'/> event. /// </para> /// </devdoc> protected void OnExited() { EventHandler exited = _onExited; if (exited != null) { exited(this, EventArgs.Empty); } } /// <devdoc> /// Raise the Exited event, but make sure we don't do it more than once. /// </devdoc> /// <internalonly/> private void RaiseOnExited() { if (!_raisedOnExited) { lock (this) { if (!_raisedOnExited) { _raisedOnExited = true; OnExited(); } } } } /// <devdoc> /// <para> /// Discards any information about the associated process /// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the /// first request for information for each property causes the process component /// to obtain a new value from the associated process. /// </para> /// </devdoc> public void Refresh() { _processInfo = null; _threads = null; _modules = null; _exited = false; _haveWorkingSetLimits = false; _haveProcessorAffinity = false; _havePriorityClass = false; _haveExitTime = false; _havePriorityBoostEnabled = false; RefreshCore(); } /// <summary> /// Opens a long-term handle to the process, with all access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle OpenProcessHandle() { if (!_haveProcessHandle) { //Cannot open a new process handle if the object has been disposed, since finalization has been suppressed. if (_disposed) { throw new ObjectDisposedException(GetType().Name); } SetProcessHandle(GetProcessHandle()); } return _processHandle; } /// <devdoc> /// Helper to associate a process handle with this component. /// </devdoc> /// <internalonly/> private void SetProcessHandle(SafeProcessHandle processHandle) { _processHandle = processHandle; _haveProcessHandle = true; if (_watchForExit) { EnsureWatchingForExit(); } } /// <devdoc> /// Helper to associate a process id with this component. /// </devdoc> /// <internalonly/> private void SetProcessId(int processId) { _processId = processId; _haveProcessId = true; ConfigureAfterProcessIdSet(); } /// <summary>Additional optional configuration hook after a process ID is set.</summary> partial void ConfigureAfterProcessIdSet(); /// <devdoc> /// <para> /// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/> /// component and associates it with the /// <see cref='System.Diagnostics.Process'/> . If a process resource is reused /// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public bool Start() { Close(); ProcessStartInfo startInfo = StartInfo; if (startInfo.FileName.Length == 0) { throw new InvalidOperationException(SR.FileNameMissing); } if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput) { throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed); } if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError) { throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed); } //Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed. if (_disposed) { throw new ObjectDisposedException(GetType().Name); } return StartCore(startInfo); } /// <devdoc> /// <para> /// Starts a process resource by specifying the name of a /// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(string fileName) { return Start(new ProcessStartInfo(fileName)); } /// <devdoc> /// <para> /// Starts a process resource by specifying the name of an /// application and a set of command line arguments. Associates the process resource /// with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(string fileName, string arguments) { return Start(new ProcessStartInfo(fileName, arguments)); } /// <devdoc> /// <para> /// Starts a process resource specified by the process start /// information passed in, for example the file name of the process to start. /// Associates the process resource with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(ProcessStartInfo startInfo) { Process process = new Process(); if (startInfo == null) throw new ArgumentNullException(nameof(startInfo)); process.StartInfo = startInfo; return process.Start() ? process : null; } /// <devdoc> /// Make sure we are not watching for process exit. /// </devdoc> /// <internalonly/> private void StopWatchingForExit() { if (_watchingForExit) { RegisteredWaitHandle rwh = null; WaitHandle wh = null; lock (this) { if (_watchingForExit) { _watchingForExit = false; wh = _waitHandle; _waitHandle = null; rwh = _registeredWaitHandle; _registeredWaitHandle = null; } } if (rwh != null) { rwh.Unregister(null); } if (wh != null) { wh.Dispose(); } } } public override string ToString() { if (Associated) { string processName = ProcessName; if (processName.Length != 0) { return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName); } } return base.ToString(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to wait /// indefinitely for the associated process to exit. /// </para> /// </devdoc> public void WaitForExit() { WaitForExit(Timeout.Infinite); } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for /// the associated process to exit. /// </summary> public bool WaitForExit(int milliseconds) { bool exited = WaitForExitCore(milliseconds); if (exited && _watchForExit) { RaiseOnExited(); } return exited; } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to start /// reading the StandardOutput stream asynchronously. The user can register a callback /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached /// then the remaining information is returned. The user can add an event handler to OutputDataReceived. /// </para> /// </devdoc> public void BeginOutputReadLine() { if (_outputStreamReadMode == StreamReadMode.Undefined) { _outputStreamReadMode = StreamReadMode.AsyncMode; } else if (_outputStreamReadMode != StreamReadMode.AsyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } if (_pendingOutputRead) throw new InvalidOperationException(SR.PendingAsyncOperation); _pendingOutputRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. if (_output == null) { if (_standardOutput == null) { throw new InvalidOperationException(SR.CantGetStandardOut); } Stream s = _standardOutput.BaseStream; _output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding); } _output.BeginReadLine(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to start /// reading the StandardError stream asynchronously. The user can register a callback /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached /// then the remaining information is returned. The user can add an event handler to ErrorDataReceived. /// </para> /// </devdoc> public void BeginErrorReadLine() { if (_errorStreamReadMode == StreamReadMode.Undefined) { _errorStreamReadMode = StreamReadMode.AsyncMode; } else if (_errorStreamReadMode != StreamReadMode.AsyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } if (_pendingErrorRead) { throw new InvalidOperationException(SR.PendingAsyncOperation); } _pendingErrorRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. if (_error == null) { if (_standardError == null) { throw new InvalidOperationException(SR.CantGetStandardError); } Stream s = _standardError.BaseStream; _error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding); } _error.BeginReadLine(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation /// specified by BeginOutputReadLine(). /// </para> /// </devdoc> public void CancelOutputRead() { if (_output != null) { _output.CancelOperation(); } else { throw new InvalidOperationException(SR.NoAsyncOperation); } _pendingOutputRead = false; } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation /// specified by BeginErrorReadLine(). /// </para> /// </devdoc> public void CancelErrorRead() { if (_error != null) { _error.CancelOperation(); } else { throw new InvalidOperationException(SR.NoAsyncOperation); } _pendingErrorRead = false; } internal void OutputReadNotifyUser(String data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler outputDataReceived = OutputDataReceived; if (outputDataReceived != null) { DataReceivedEventArgs e = new DataReceivedEventArgs(data); outputDataReceived(this, e); // Call back to user informing data is available } } internal void ErrorReadNotifyUser(String data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler errorDataReceived = ErrorDataReceived; if (errorDataReceived != null) { DataReceivedEventArgs e = new DataReceivedEventArgs(data); errorDataReceived(this, e); // Call back to user informing data is available. } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// This enum defines the operation mode for redirected process stream. /// We don't support switching between synchronous mode and asynchronous mode. /// </summary> private enum StreamReadMode { Undefined, SyncMode, AsyncMode } /// <summary>A desired internal state.</summary> private enum State { HaveId = 0x1, IsLocal = 0x2, HaveProcessInfo = 0x8, Exited = 0x10, Associated = 0x20, } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq.Expressions; using System.Web; using System.Web.Mvc; using System.Web.Routing; using MvcContrib.Sorting; using MvcContrib.UI.Grid; using MvcContrib.UI.Grid.ActionSyntax; using NUnit.Framework; using Rhino.Mocks; namespace MvcContrib.UnitTests.UI.Grid { [TestFixture] public class GridRendererTester { private List<Person> _people; private GridModel<Person> _model; private IViewEngine _viewEngine; private ViewEngineCollection _engines; private StringWriter _writer; private NameValueCollection _querystring; [SetUp] public void Setup() { _model = new GridModel<Person>(); _people = new List<Person> {new Person {Id = 1, Name = "Jeremy", DateOfBirth = new DateTime(1987, 4, 19)}}; _viewEngine = MockRepository.GenerateMock<IViewEngine>(); _engines = new ViewEngineCollection(new List<IViewEngine> { _viewEngine }); _writer = new StringWriter(); _querystring= new NameValueCollection(); RouteTable.Routes.MapRoute("default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }); } [TearDown] public void Teardown() { RouteTable.Routes.Clear(); } private IGridColumn<Person> ColumnFor(Expression<Func<Person, object>> expression) { return _model.Column.For(expression); } [Test] public void Should_render_empty_table() { string expected = ExpectedEmptyTable("There is no data available.", "grid"); RenderGrid(null).ShouldEqual(expected); } private string ExpectedEmptyTable(string message, string @class) { return "<table class=\""+ @class +"\"><thead><tr><th></th></tr></thead><tbody><tr><td>" + message +"</td></tr></tbody></table>"; } [Test] public void Should_render_empty_table_when_collection_is_empty() { _people.Clear(); string expected = ExpectedEmptyTable("There is no data available.", "grid"); RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_empty_table_with_custom_message() { _people.Clear(); string expected = ExpectedEmptyTable("Test", "grid");// "<table class=\"grid\"><tr><td>Test</td></tr></table>"; _model.Empty("Test"); RenderGrid().ShouldEqual(expected); } [Test] public void Custom_html_attrs() { _people.Clear(); string expected = ExpectedEmptyTable("There is no data available.", "sortable grid");// "<table class=\"sortable grid\"><tr><td>There is no data available.</td></tr></table>"; _model.Attributes(@class => "sortable grid"); RenderGrid().ShouldEqual(expected); } [Test] public void Custom_html_attributes_should_be_encoded() { _people.Clear(); string expected = ExpectedEmptyTable("There is no data available.", "&quot;foo&quot;"); _model.Attributes(@class => "\"foo\""); RenderGrid().ShouldEqual(expected); } [Test] public void Should_render() { ColumnFor(x => x.Name); ColumnFor(x => x.Id); string expected = "<table class=\"grid\"><thead><tr><th>Name</th><th>Id</th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td><td>1</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test, Obsolete] public void Should_render_with_custom_Header() { ColumnFor(x => x.Name).Header("TEST"); ColumnFor(x => x.Id); string expected = "<table class=\"grid\"><thead><tr><th>TEST</th><th>Id</th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td><td>1</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Header_should_be_split_pascal_case() { ColumnFor(x => x.DateOfBirth).Format("{0:dd}"); string expected = "<table class=\"grid\"><thead><tr><th>Date Of Birth</th></tr></thead><tbody><tr class=\"gridrow\"><td>19</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void With_format() { ColumnFor(x => x.DateOfBirth).Format("{0:ddd}"); var dayString = string.Format("{0:ddd}", _people[0].DateOfBirth); dayString = HttpUtility.HtmlEncode(dayString); string expected = "<table class=\"grid\"><thead><tr><th>Date Of Birth</th></tr></thead><tbody><tr class=\"gridrow\"><td>" + dayString + "</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Complicated_column() { ColumnFor(x => x.Id + "-" + x.Name).Named("Test"); string expected = "<table class=\"grid\"><thead><tr><th>Test</th></tr></thead><tbody><tr class=\"gridrow\"><td>1-Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Column_heading_should_be_empty() { ColumnFor(x => x.Id + "-" + x.Name); string expected = "<table class=\"grid\"><thead><tr><th></th></tr></thead><tbody><tr class=\"gridrow\"><td>1-Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void With_cell_condition() { ColumnFor(x => x.Name); ColumnFor(x => x.Id).CellCondition(x => false); string expected = "<table class=\"grid\"><thead><tr><th>Name</th><th>Id</th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td><td></td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void With_col_condition() { ColumnFor(x => x.Name); ColumnFor(x => x.Id).Visible(false); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_custom_row_start() { ColumnFor(x => x.Id); _model.Sections.RowStart(x => "<tr foo=\"bar\">"); string expected = "<table class=\"grid\"><thead><tr><th>Id</th></tr></thead><tbody><tr foo=\"bar\"><td>1</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_custom_row_end() { ColumnFor(x => x.Id); _model.Sections.RowEnd(x => "</tr>TEST"); string expected = "<table class=\"grid\"><thead><tr><th>Id</th></tr></thead><tbody><tr class=\"gridrow\"><td>1</td></tr>TEST</tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Alternating_rows_should_have_correct_css_class() { _people.Add(new Person {Name = "Person 2"}); _people.Add(new Person {Name = "Person 3"}); ColumnFor(x => x.Name); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr><tr class=\"gridrow_alternate\"><td>Person 2</td></tr><tr class=\"gridrow\"><td>Person 3</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_custom_row_start_with_alternate_row() { _people.Add(new Person { Name = "Person 2" }); _people.Add(new Person { Name = "Person 3" }); ColumnFor(x => x.Name); _model.Sections.RowStart(row => "<tr class=\"row " + (row.IsAlternate ? "gridrow_alternate" : "gridrow") + "\">"); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr class=\"row gridrow\"><td>Jeremy</td></tr><tr class=\"row gridrow_alternate\"><td>Person 2</td></tr><tr class=\"row gridrow\"><td>Person 3</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_custom_row_start_with_action() { _people.Add(new Person { Name = "Person 2" }); _people.Add(new Person { Name = "Person 3" }); ColumnFor(x => x.Name); _model.Sections.RowStart(x=> "<tr class=\"gridrow\">"); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr><tr class=\"gridrow\"><td>Person 2</td></tr><tr class=\"gridrow\"><td>Person 3</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_header_attributes() { ColumnFor(x => x.Name).HeaderAttributes(style => "width:100%"); string expected = "<table class=\"grid\"><thead><tr><th style=\"width:100%\">Name</th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_encode_header_attributes() { ColumnFor(x => x.Name).HeaderAttributes(style => "\"foo\""); string expected = "<table class=\"grid\"><thead><tr><th style=\"&quot;foo&quot;\">Name</th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_header_attributes_when_rendering_custom_row_start() { ColumnFor(x => x.Name).HeaderAttributes(style => "width:100%"); _people.Add(new Person { Name = "Person 2" }); _people.Add(new Person { Name = "Person 3" }); _model.Sections.RowStart(row => "<tr class=\"row " + (row.IsAlternate ? "gridrow_alternate" : "gridrow") + "\">"); string expected = "<table class=\"grid\"><thead><tr><th style=\"width:100%\">Name</th></tr></thead><tbody><tr class=\"row gridrow\"><td>Jeremy</td></tr><tr class=\"row gridrow_alternate\"><td>Person 2</td></tr><tr class=\"row gridrow\"><td>Person 3</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test, Obsolete] public void Custom_item_section() { ColumnFor(x => x.Name).Action(s => _writer.Write("<td>Test</td>")); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr class=\"gridrow\"><td>Test</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Custom_column() { _model.Column.Custom(x => "Test").Named("Name"); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr class=\"gridrow\"><td>Test</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test, Obsolete] public void Should_render_with_custom_header_section() { ColumnFor(p => p.Name).HeaderAction(() => _writer.Write("<td>TEST</td>")); ColumnFor(p => p.Id); string expected = "<table class=\"grid\"><thead><tr><td>TEST</td><th>Id</th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td><td>1</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Renders_custom_header() { ColumnFor(x => x.Name).Header(x => "TEST"); ColumnFor(p => p.Id); string expected = "<table class=\"grid\"><thead><tr><th>TEST</th><th>Id</th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td><td>1</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_custom_attributes_in_table_cell() { ColumnFor(x => x.Name).Attributes(foo => "bar"); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr class=\"gridrow\"><td foo=\"bar\">Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_encode_custom_attributes() { ColumnFor(x => x.Name).Attributes(foo => "\"bar\""); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr class=\"gridrow\"><td foo=\"&quot;bar&quot;\">Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_custom_attributes_when_Attributes_called_multiple_times() { ColumnFor(x => x.Name).Attributes(foo => "bar").Attributes(baz => "blah"); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr class=\"gridrow\"><td foo=\"bar\" baz=\"blah\">Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_custom_attributes_in_table_cell_with_logic() { _people.Add(new Person() { Name = "foo"}); ColumnFor(x => x.Name).Attributes(row => new Hash(foo => row.IsAlternate ? "bar" : "baz" )); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr class=\"gridrow\"><td foo=\"baz\">Jeremy</td></tr><tr class=\"gridrow_alternate\"><td foo=\"bar\">foo</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_custom_attributes_for_row() { ColumnFor(x => x.Name); _model.Sections.RowAttributes(x => new Hash(foo => "bar")); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr foo=\"bar\" class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_custom_css_class_for_row() { ColumnFor(x => x.Name); _model.Sections.RowAttributes(x => new Hash(@class => "foo")); string expected = "<table class=\"grid\"><thead><tr><th>Name</th></tr></thead><tbody><tr class=\"foo\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_custom_attributes_for_header_row() { ColumnFor(x => x.Name); _model.Sections.HeaderRowAttributes(new Hash(foo => "bar")); string expected = "<table class=\"grid\"><thead><tr foo=\"bar\"><th>Name</th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_grid_with_sort_links() { ColumnFor(x => x.Name); _model.Sort(new GridSortOptions()); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=Name&amp;Direction=Ascending\">Name</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_grid_with_sort_links_using_prefix() { ColumnFor(x => x.Name); _model.Sort(new GridSortOptions(), "foo"); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?foo.Column=Name&amp;foo.Direction=Ascending\">Name</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_grid_with_sort_direction_ascending() { ColumnFor(x => x.Name); _model.Sort(new GridSortOptions() { Column = "Name" }); string expected = "<table class=\"grid\"><thead><tr><th class=\"sort_asc\"><a href=\"/?Column=Name&amp;Direction=Descending\">Name</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Direction_heading_should_not_override_custom_class() { ColumnFor(x => x.Name).HeaderAttributes(@class => "foo"); _model.Sort(new GridSortOptions() { Column = "Name" }); string expected = "<table class=\"grid\"><thead><tr><th class=\"foo sort_asc\"><a href=\"/?Column=Name&amp;Direction=Descending\">Name</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_grid_with_sort_direction_descending() { ColumnFor(x => x.Name); _model.Sort(new GridSortOptions() { Column = "Name", Direction = SortDirection.Descending }); string expected = "<table class=\"grid\"><thead><tr><th class=\"sort_desc\"><a href=\"/?Column=Name&amp;Direction=Ascending\">Name</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_grid_with_sort_direction_descending_as_the_default() { ColumnFor(x => x.Id); ColumnFor(x => x.Name); ColumnFor(x => x.DateOfBirth).Format("{0:M/d/yyyy}"); _model.Sort(new GridSortOptions() { Direction = SortDirection.Descending }); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=Id&amp;Direction=Descending\">Id</a></th><th><a href=\"/?Column=Name&amp;Direction=Descending\">Name</a></th><th><a href=\"/?Column=DateOfBirth&amp;Direction=Descending\">Date Of Birth</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>1</td><td>Jeremy</td><td>4/19/1987</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_all_sort_links_ascending_when_option_is_ascending_and_no_column_currently_sorted() { ColumnFor(x => x.Id); ColumnFor(x => x.Name); ColumnFor(x => x.DateOfBirth).Format("{0:M/d/yyyy}"); _model.Sort(new GridSortOptions() { Direction = SortDirection.Ascending }); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=Id&amp;Direction=Ascending\">Id</a></th><th><a href=\"/?Column=Name&amp;Direction=Ascending\">Name</a></th><th><a href=\"/?Column=DateOfBirth&amp;Direction=Ascending\">Date Of Birth</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>1</td><td>Jeremy</td><td>4/19/1987</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_initial_direction_descending_when_it_is_not_the_currently_sorted_column() { ColumnFor(x => x.Id); ColumnFor(x => x.Name).SortInitialDirection(SortDirection.Descending); ColumnFor(x => x.DateOfBirth).Format("{0:M/d/yyyy}"); _model.Sort(new GridSortOptions() { Direction = SortDirection.Ascending }); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=Id&amp;Direction=Ascending\">Id</a></th><th><a href=\"/?Column=Name&amp;Direction=Descending\">Name</a></th><th><a href=\"/?Column=DateOfBirth&amp;Direction=Ascending\">Date Of Birth</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>1</td><td>Jeremy</td><td>4/19/1987</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_initial_direction_ascending_when_it_is_not_the_currently_sorted_column() { ColumnFor(x => x.Id); ColumnFor(x => x.Name).SortInitialDirection(SortDirection.Ascending); ColumnFor(x => x.DateOfBirth).Format("{0:M/d/yyyy}"); _model.Sort(new GridSortOptions() { Direction = SortDirection.Descending }); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=Id&amp;Direction=Descending\">Id</a></th><th><a href=\"/?Column=Name&amp;Direction=Ascending\">Name</a></th><th><a href=\"/?Column=DateOfBirth&amp;Direction=Descending\">Date Of Birth</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>1</td><td>Jeremy</td><td>4/19/1987</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_ignore_initial_direction_ascending_when_it_is_the_currently_sorted_column() { ColumnFor(x => x.Id); ColumnFor(x => x.Name).SortInitialDirection(SortDirection.Descending); ColumnFor(x => x.DateOfBirth).Format("{0:M/d/yyyy}"); _model.Sort(new GridSortOptions() { Column = "Name", Direction = SortDirection.Descending }); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=Id&amp;Direction=Descending\">Id</a></th><th class=\"sort_desc\"><a href=\"/?Column=Name&amp;Direction=Ascending\">Name</a></th><th><a href=\"/?Column=DateOfBirth&amp;Direction=Descending\">Date Of Birth</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>1</td><td>Jeremy</td><td>4/19/1987</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Sorting_Maintains_existing_querystring_parameters() { _querystring["foo"] = "bar"; ColumnFor(x => x.Name); _model.Sort(new GridSortOptions()); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=Name&amp;Direction=Ascending&amp;foo=bar\">Name</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Sorting_does_not_maintain_null_querystring_parameters() { _querystring[(string)null] = "foo"; ColumnFor(x => x.Name); _model.Sort(new GridSortOptions()); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=Name&amp;Direction=Ascending\">Name</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_not_render_sort_links_for_columns_tha_are_not_sortable() { ColumnFor(x => x.Id); ColumnFor(x => x.Name).Sortable(false); _model.Sort(new GridSortOptions()); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=Id&amp;Direction=Ascending\">Id</a></th><th>Name</th></tr></thead><tbody><tr class=\"gridrow\"><td>1</td><td>Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Uses_custom_sort_column_name() { ColumnFor(x => x.Id).SortColumnName("foo"); _model.Sort(new GridSortOptions()); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=foo&amp;Direction=Ascending\">Id</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>1</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Uses_custom_sort_column_name_for_composite_expression() { ColumnFor(x => x.Id + x.Name).SortColumnName("foo").Named("bar"); _model.Sort(new GridSortOptions()); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=foo&amp;Direction=Ascending\">bar</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>1Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Falls_back_to_column_name_for_composite_expression() { ColumnFor(x => x.Id + x.Name).Named("bar"); _model.Sort(new GridSortOptions()); string expected = "<table class=\"grid\"><thead><tr><th><a href=\"/?Column=bar&amp;Direction=Ascending\">bar</a></th></tr></thead><tbody><tr class=\"gridrow\"><td>1Jeremy</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_not_automatically_encode_IHtmlString_instances() { ColumnFor(x => new HtmlString("<script></script>")).Named("foo"); string expected = "<table class=\"grid\"><thead><tr><th>foo</th></tr></thead><tbody><tr class=\"gridrow\"><td><script></script></td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Should_render_custom_name_with_DisplayNameAttribute() { ColumnFor(x => x.NameWithAttribute); string expected = "<table class=\"grid\"><thead><tr><th>Name2</th></tr></thead><tbody><tr class=\"gridrow\"><td></td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Infers_format_from_DisplayFormAttribute() { ColumnFor(x => x.DateWithAttribute); string expected = "<table class=\"grid\"><thead><tr><th>Date With Attribute</th></tr></thead><tbody><tr class=\"gridrow\"><td>01</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } [Test] public void Can_render_nested_properties() { _people[0].Address = new Address { Line1 = "Foo" }; ColumnFor(x => x.Address.Line1); string expected = "<table class=\"grid\"><thead><tr><th>Line1</th></tr></thead><tbody><tr class=\"gridrow\"><td>Foo</td></tr></tbody></table>"; RenderGrid().ShouldEqual(expected); } private string RenderGrid() { return RenderGrid(_people); } private string RenderGrid(IEnumerable<Person> dataSource) { var renderer = new HtmlTableGridRenderer<Person>(_engines); var viewContext = MockRepository.GenerateStub<ViewContext>(); viewContext.Writer = _writer; viewContext.View = MockRepository.GenerateStub<IView>(); viewContext.TempData = new TempDataDictionary(); var response = MockRepository.GenerateStub<HttpResponseBase>(); var context = MockRepository.GenerateStub<HttpContextBase>(); var request = MockRepository.GenerateStub<HttpRequestBase>(); viewContext.HttpContext = context; context.Stub(x =>x.Response).Return(response); context.Stub(x => x.Request).Return(request); response.Output = _writer; request.Stub(x => x.ApplicationPath).Return("/"); request.Stub(x => x.QueryString).Return(_querystring); response.Expect(x => x.ApplyAppPathModifier(Arg<string>.Is.Anything)) .Do(new Func<string,string>(x => x)) .Repeat.Any(); renderer.Render(_model, dataSource, _writer, viewContext); return _writer.ToString(); } public static RenderingContext FakeRenderingContext() { var engine = MockRepository.GenerateStub<IViewEngine>(); engine.Stub(x => x.FindPartialView(null, null, true)).IgnoreArguments().Return(new ViewEngineResult(MockRepository.GenerateStub<IView>(), engine)).Repeat.Any(); var context = new RenderingContext( new StringWriter(), new ViewContext() { View = MockRepository.GenerateStub<IView>(), TempData = new TempDataDictionary() }, new ViewEngineCollection(new List<IViewEngine>() { engine })); return context; } } }
// 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.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Threading.Tasks; namespace Microsoft.AspNetCore.SignalR.Hubs { internal static class TypedClientBuilder<T> { private const string ClientModuleName = "Microsoft.AspNetCore.SignalR.Hubs.TypedClientBuilder"; // There is one static instance of _builder per T private static Lazy<Func<IClientProxy, T>> _builder = new Lazy<Func<IClientProxy, T>>(() => GenerateClientBuilder()); [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "This is used internally and by tests.")] public static T Build(IClientProxy proxy) { return _builder.Value(proxy); } [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "forceEvaluation", Justification = "Give me a better way to force the evaluation of Lazy<T>")] public static void Validate() { // The following will throw if T is not a valid type var forceEvaluation = _builder.Value; } private static Func<IClientProxy, T> GenerateClientBuilder() { VerifyInterface(typeof(T)); var assemblyName = new AssemblyName(ClientModuleName); #if NET451 AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); #else AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); #endif ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(ClientModuleName); Type clientType = GenerateInterfaceImplementation(moduleBuilder); return proxy => (T)Activator.CreateInstance(clientType, proxy); } private static Type GenerateInterfaceImplementation(ModuleBuilder moduleBuilder) { TypeBuilder type = moduleBuilder.DefineType( ClientModuleName + "." + typeof(T).Name + "Impl", TypeAttributes.Public, typeof(Object), new[] { typeof(T) }); FieldBuilder proxyField = type.DefineField("_proxy", typeof(IClientProxy), FieldAttributes.Private); BuildConstructor(type, proxyField); foreach (var method in GetAllInterfaceMethods(typeof(T))) { BuildMethod(type, method, proxyField); } return type.CreateTypeInfo().AsType(); } private static IEnumerable<MethodInfo> GetAllInterfaceMethods(Type interfaceType) { foreach (var parent in interfaceType.GetInterfaces()) { foreach (var parentMethod in GetAllInterfaceMethods(parent)) { yield return parentMethod; } } foreach (var method in interfaceType.GetMethods()) { yield return method; } } private static void BuildConstructor(TypeBuilder type, FieldInfo proxyField) { MethodBuilder method = type.DefineMethod(".ctor", System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.HideBySig); ConstructorInfo ctor = typeof(object).GetTypeInfo().DeclaredConstructors.First(c => c.GetParameters().Length == 0); method.SetReturnType(typeof(void)); method.SetParameters(typeof(IClientProxy)); ILGenerator generator = method.GetILGenerator(); // Call object constructor generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Call, ctor); // Assign constructor argument to the proxyField generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Stfld, proxyField); generator.Emit(OpCodes.Ret); } private static void BuildMethod(TypeBuilder type, MethodInfo interfaceMethodInfo, FieldInfo proxyField) { MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot; ParameterInfo[] parameters = interfaceMethodInfo.GetParameters(); Type[] paramTypes = parameters.Select(param => param.ParameterType).ToArray(); MethodBuilder methodBuilder = type.DefineMethod(interfaceMethodInfo.Name, methodAttributes); MethodInfo invokeMethod = typeof(IClientProxy).GetRuntimeMethod("Invoke", new Type[] { typeof(string), typeof(object[]) }); methodBuilder.SetReturnType(interfaceMethodInfo.ReturnType); methodBuilder.SetParameters(paramTypes); ILGenerator generator = methodBuilder.GetILGenerator(); // Declare local variable to store the arguments to IClientProxy.Invoke generator.DeclareLocal(typeof(object[])); // Get IClientProxy generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, proxyField); // The first argument to IClientProxy.Invoke is this method's name generator.Emit(OpCodes.Ldstr, interfaceMethodInfo.Name); // Create an new object array to hold all the parameters to this method generator.Emit(OpCodes.Ldc_I4, parameters.Length); generator.Emit(OpCodes.Newarr, typeof(object)); generator.Emit(OpCodes.Stloc_0); // Store each parameter in the object array for (int i = 0; i < paramTypes.Length; i++) { generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Ldc_I4, i); generator.Emit(OpCodes.Ldarg, i + 1); generator.Emit(OpCodes.Box, paramTypes[i]); generator.Emit(OpCodes.Stelem_Ref); } // Call IProxy.Invoke generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Callvirt, invokeMethod); if (interfaceMethodInfo.ReturnType == typeof(void)) { // void return generator.Emit(OpCodes.Pop); } generator.Emit(OpCodes.Ret); } private static void VerifyInterface(Type interfaceType) { if (!interfaceType.GetTypeInfo().IsInterface) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, Resources.Error_TypeMustBeInterface, interfaceType.Name)); } if (interfaceType.GetProperties().Length != 0) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, Resources.Error_TypeMustNotContainProperties, interfaceType.Name)); } if (interfaceType.GetEvents().Length != 0) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, Resources.Error_TypeMustNotContainEvents, interfaceType.Name)); } foreach (var method in interfaceType.GetMethods()) { VerifyMethod(interfaceType, method); } foreach (var parent in interfaceType.GetInterfaces()) { VerifyInterface(parent); } } private static void VerifyMethod(Type interfaceType, MethodInfo interfaceMethod) { if (interfaceMethod.ReturnType != typeof(void) && interfaceMethod.ReturnType != typeof(Task)) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, Resources.Error_MethodMustReturnVoidOrTask, interfaceType.Name, interfaceMethod.Name)); } foreach (var parameter in interfaceMethod.GetParameters()) { VerifyParameter(interfaceType, interfaceMethod, parameter); } } private static void VerifyParameter(Type interfaceType, MethodInfo interfaceMethod, ParameterInfo parameter) { if (parameter.IsOut) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, Resources.Error_MethodMustNotTakeOutParameter, parameter.Name, interfaceType.Name, interfaceMethod.Name)); } if (parameter.ParameterType.IsByRef) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, Resources.Error_MethodMustNotTakeRefParameter, parameter.Name, interfaceType.Name, interfaceMethod.Name)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Tests; using System.Runtime.CompilerServices; using Xunit; [assembly: Attr(77, name = "AttrSimple"), Int32Attr(77, name = "Int32AttrSimple"), Int64Attr(77, name = "Int64AttrSimple"), StringAttr("hello", name = "StringAttrSimple"), EnumAttr(PublicEnum.Case1, name = "EnumAttrSimple"), TypeAttr(typeof(object), name = "TypeAttrSimple")] [assembly: CompilationRelaxations(8)] [assembly: Debuggable((DebuggableAttribute.DebuggingModes)263)] [assembly: CLSCompliant(false)] namespace System.Reflection.Tests { public class AssemblyTests { [Theory] [InlineData(typeof(Int32Attr))] [InlineData(typeof(Int64Attr))] [InlineData(typeof(StringAttr))] [InlineData(typeof(EnumAttr))] [InlineData(typeof(TypeAttr))] [InlineData(typeof(CompilationRelaxationsAttribute))] [InlineData(typeof(AssemblyTitleAttribute))] [InlineData(typeof(AssemblyDescriptionAttribute))] [InlineData(typeof(AssemblyCompanyAttribute))] [InlineData(typeof(CLSCompliantAttribute))] [InlineData(typeof(DebuggableAttribute))] [InlineData(typeof(Attr))] public void CustomAttributes(Type type) { Assembly assembly = Helpers.ExecutingAssembly; IEnumerable<Type> attributesData = assembly.CustomAttributes.Select(customAttribute => customAttribute.AttributeType); Assert.Contains(type, attributesData); ICustomAttributeProvider attributeProvider = assembly; Assert.Single(attributeProvider.GetCustomAttributes(type, false)); Assert.True(attributeProvider.IsDefined(type, false)); IEnumerable<Type> customAttributes = attributeProvider.GetCustomAttributes(false).Select(attribute => attribute.GetType()); Assert.Contains(type, customAttributes); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(Attr), true)] [InlineData(typeof(Int32Attr), true)] [InlineData(typeof(Int64Attr), true)] [InlineData(typeof(StringAttr), true)] [InlineData(typeof(EnumAttr), true)] [InlineData(typeof(TypeAttr), true)] [InlineData(typeof(ObjectAttr), true)] [InlineData(typeof(NullAttr), true)] public void DefinedTypes(Type type, bool expected) { IEnumerable<Type> customAttrs = Helpers.ExecutingAssembly.DefinedTypes.Select(typeInfo => typeInfo.AsType()); Assert.Equal(expected, customAttrs.Contains(type)); } [Theory] [InlineData("EmbeddedImage.png", true)] [InlineData("NoSuchFile", false)] public void EmbeddedFiles(string resource, bool exists) { string[] resources = Helpers.ExecutingAssembly.GetManifestResourceNames(); Stream resourceStream = Helpers.ExecutingAssembly.GetManifestResourceStream(resource); Assert.Equal(exists, resources.Contains(resource)); Assert.Equal(exists, resourceStream != null); } [Fact] public void EntryPoint_ExecutingAssembly_IsNull() { Assert.Null(Helpers.ExecutingAssembly.EntryPoint); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Helpers.ExecutingAssembly, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals(Assembly assembly1, Assembly assembly2, bool expected) { Assert.Equal(expected, assembly1.Equals(assembly2)); } [Theory] [InlineData(typeof(AssemblyPublicClass), true)] [InlineData(typeof(AssemblyTests), true)] [InlineData(typeof(AssemblyPublicClass.PublicNestedClass), true)] [InlineData(typeof(PublicEnum), true)] [InlineData(typeof(AssemblyGenericPublicClass<>), true)] [InlineData(typeof(AssemblyInternalClass), false)] public void ExportedTypes(Type type, bool expected) { Assembly assembly = Helpers.ExecutingAssembly; Assert.Equal(assembly.GetExportedTypes(), assembly.ExportedTypes); Assert.Equal(expected, assembly.ExportedTypes.Contains(type)); } [Fact] public void GetEntryAssembly() { Assert.NotNull(Assembly.GetEntryAssembly()); Assert.StartsWith("xunit.console.netcore", Assembly.GetEntryAssembly().ToString(), StringComparison.OrdinalIgnoreCase); } public static IEnumerable<object[]> GetHashCode_TestData() { yield return new object[] { LoadSystemRuntimeAssembly() }; yield return new object[] { LoadSystemCollectionsAssembly() }; yield return new object[] { LoadSystemReflectionAssembly() }; yield return new object[] { typeof(AssemblyTests).GetTypeInfo().Assembly }; } [Theory] [MemberData(nameof(GetHashCode_TestData))] public void GetHashCode(Assembly assembly) { int hashCode = assembly.GetHashCode(); Assert.NotEqual(-1, hashCode); Assert.NotEqual(0, hashCode); } [Theory] [InlineData("System.Reflection.Tests.AssemblyPublicClass", true)] [InlineData("System.Reflection.Tests.AssemblyInternalClass", true)] [InlineData("System.Reflection.Tests.PublicEnum", true)] [InlineData("System.Reflection.Tests.PublicStruct", true)] [InlineData("AssemblyPublicClass", false)] [InlineData("NoSuchType", false)] public void GetType(string name, bool exists) { Type type = Helpers.ExecutingAssembly.GetType(name); if (exists) { Assert.Equal(name, type.FullName); } else { Assert.Null(type); } } public static IEnumerable<object[]> IsDynamic_TestData() { yield return new object[] { Helpers.ExecutingAssembly, false }; yield return new object[] { LoadSystemCollectionsAssembly(), false }; } [Theory] [MemberData(nameof(IsDynamic_TestData))] public void IsDynamic(Assembly assembly, bool expected) { Assert.Equal(expected, assembly.IsDynamic); } public static IEnumerable<object[]> Load_TestData() { yield return new object[] { new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName) }; yield return new object[] { new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName) }; yield return new object[] { new AssemblyName(typeof(AssemblyName).GetTypeInfo().Assembly.FullName) }; } [Theory] [MemberData(nameof(Load_TestData))] public void Load(AssemblyName assemblyRef) { Assert.NotNull(Assembly.Load(assemblyRef)); } [Fact] public void Load_Invalid() { Assert.Throws<ArgumentNullException>("assemblyRef", () => Assembly.Load((AssemblyName)null)); // AssemblyRef is null Assert.Throws<FileNotFoundException>(() => Assembly.Load(new AssemblyName("no such assembly"))); // No such assembly } [Fact] public void Location_ExecutingAssembly_IsNotNull() { // This test applies on all platforms including .NET Native. Location must at least be non-null (it can be empty). // System.Reflection.CoreCLR.Tests adds tests that expect more than that. Assert.NotNull(Helpers.ExecutingAssembly.Location); } [Fact] public void CodeBase() { Assert.NotEmpty(Helpers.ExecutingAssembly.CodeBase); } [Fact] public void ImageRuntimeVersion() { Assert.NotEmpty(Helpers.ExecutingAssembly.ImageRuntimeVersion); } public static IEnumerable<object[]> CreateInstance_TestData() { yield return new object[] { Helpers.ExecutingAssembly, typeof(AssemblyPublicClass).FullName, typeof(AssemblyPublicClass) }; yield return new object[] { typeof(int).GetTypeInfo().Assembly, typeof(int).FullName, typeof(int) }; yield return new object[] { typeof(int).GetTypeInfo().Assembly, typeof(Dictionary<int, string>).FullName, typeof(Dictionary<int, string>) }; } [Theory] [MemberData(nameof(CreateInstance_TestData))] public void CreateInstance(Assembly assembly, string typeName, Type expectedType) { Assert.IsType(expectedType, assembly.CreateInstance(typeName)); Assert.IsType(expectedType, assembly.CreateInstance(typeName, false)); Assert.IsType(expectedType, assembly.CreateInstance(typeName, true)); Assert.IsType(expectedType, assembly.CreateInstance(typeName.ToUpper(), true)); Assert.IsType(expectedType, assembly.CreateInstance(typeName.ToLower(), true)); } public static IEnumerable<object[]> CreateInstance_Invalid_TestData() { yield return new object[] { "", typeof(ArgumentException) }; yield return new object[] { null, typeof(ArgumentNullException) }; yield return new object[] { typeof(AssemblyClassWithPrivateCtor).FullName, typeof(MissingMethodException) }; yield return new object[] { typeof(AssemblyClassWithNoDefaultCtor).FullName, typeof(MissingMethodException) }; } [Theory] [MemberData(nameof(CreateInstance_Invalid_TestData))] public void CreateInstance_Invalid(string typeName, Type exceptionType) { Assembly assembly = Helpers.ExecutingAssembly; Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName)); Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName, true)); Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName, false)); } [Fact] public void CreateQualifiedName() { string assemblyName = Helpers.ExecutingAssembly.ToString(); Assert.Equal(typeof(AssemblyTests).FullName + ", " + assemblyName, Assembly.CreateQualifiedName(assemblyName, typeof(AssemblyTests).FullName)); } [Fact] public void GetReferencedAssemblies() { // It is too brittle to depend on the assembly references so we just call the method and check that it does not throw. AssemblyName[] assemblies = Helpers.ExecutingAssembly.GetReferencedAssemblies(); Assert.NotEmpty(assemblies); } public static IEnumerable<object[]> Modules_TestData() { yield return new object[] { LoadSystemCollectionsAssembly() }; yield return new object[] { LoadSystemReflectionAssembly() }; } [Theory] [MemberData(nameof(Modules_TestData))] public void Modules(Assembly assembly) { Assert.NotEmpty(assembly.Modules); foreach (Module module in assembly.Modules) { Assert.NotNull(module); } } public IEnumerable<object[]> ToString_TestData() { yield return new object[] { Helpers.ExecutingAssembly, "System.Reflection.Tests" }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), "PublicKeyToken=" }; } [Theory] public void ToString(Assembly assembly, string expected) { Assert.Contains(expected, assembly.ToString()); Assert.Equal(assembly.ToString(), assembly.FullName); } private static Assembly LoadSystemCollectionsAssembly() { // Force System.collections to be linked statically List<int> li = new List<int>(); li.Add(1); return Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)); } private static Assembly LoadSystemReflectionAssembly() { // Force System.Reflection to be linked statically return Assembly.Load(new AssemblyName(typeof(AssemblyName).GetTypeInfo().Assembly.FullName)); } private static Assembly LoadSystemRuntimeAssembly() { // Load System.Runtime return Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)); ; } } public struct PublicStruct { } public class AssemblyPublicClass { public class PublicNestedClass { } } public class AssemblyGenericPublicClass<T> { } internal class AssemblyInternalClass { } public class AssemblyClassWithPrivateCtor { private AssemblyClassWithPrivateCtor() { } } public class AssemblyClassWithNoDefaultCtor { public AssemblyClassWithNoDefaultCtor(int x) { } } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * 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.Xml; using System.Data; using System.Collections; namespace Reporting.Data { /// <summary> /// Summary description for Class1. /// </summary> public class XmlCommand : IDbCommand { XmlConnection _xc; // connection we're running under string _cmd; // command to execute // parsed constituents of the command string _Url; // url of the xml file string _RowsXPath; // XPath specifying rows selection ArrayList _ColumnsXPath; // XPath for each column string _Type; // type of request DataParameterCollection _Parameters = new DataParameterCollection(); public XmlCommand(XmlConnection conn) { _xc = conn; } internal string Url { get { // Check to see if "Url" or "@Url" is a parameter IDbDataParameter dp= _Parameters["Url"] as IDbDataParameter; if (dp == null) dp= _Parameters["@Url"] as IDbDataParameter; // Then check to see if the Url value is a parameter? if (dp == null) dp = _Parameters[_Url] as IDbDataParameter; if (dp != null) return dp.Value != null? dp.Value.ToString(): _Url; // don't pass null; pass existing value return _Url; // the value must be a constant } set {_Url = value;} } internal string RowsXPath { get { IDbDataParameter dp= _Parameters["RowsXPath"] as IDbDataParameter; if (dp == null) dp= _Parameters["@RowsXPath"] as IDbDataParameter; // Then check to see if the RowsXPath value is a parameter? if (dp == null) dp = _Parameters[_RowsXPath] as IDbDataParameter; if (dp != null) return dp.Value != null? dp.Value.ToString(): _RowsXPath; // don't pass null; pass existing value return _RowsXPath; // the value must be a constant } set {_RowsXPath = value;} } internal ArrayList ColumnsXPath { get {return _ColumnsXPath;} set {_ColumnsXPath = value;} } internal string Type { get {return _Type;} set {_Type = value;} } #region IDbCommand Members public void Cancel() { throw new NotImplementedException("Cancel not implemented"); } public void Prepare() { return; // Prepare is a noop } public System.Data.CommandType CommandType { get { throw new NotImplementedException("CommandType not implemented"); } set { throw new NotImplementedException("CommandType not implemented"); } } public IDataReader ExecuteReader(System.Data.CommandBehavior behavior) { if (!(behavior == CommandBehavior.SingleResult || behavior == CommandBehavior.SchemaOnly)) throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only."); return new XmlDataReader(behavior, _xc, this); } IDataReader System.Data.IDbCommand.ExecuteReader() { return ExecuteReader(System.Data.CommandBehavior.SingleResult); } public object ExecuteScalar() { throw new NotImplementedException("ExecuteScalar not implemented"); } public int ExecuteNonQuery() { throw new NotImplementedException("ExecuteNonQuery not implemented"); } public int CommandTimeout { get { return 0; } set { throw new NotImplementedException("CommandTimeout not implemented"); } } public IDbDataParameter CreateParameter() { return new XmlDataParameter(); } public IDbConnection Connection { get { return this._xc; } set { throw new NotImplementedException("Setting Connection not implemented"); } } public System.Data.UpdateRowSource UpdatedRowSource { get { throw new NotImplementedException("UpdatedRowSource not implemented"); } set { throw new NotImplementedException("UpdatedRowSource not implemented"); } } public string CommandText { get { return this._cmd; } set { // Parse the command string for keyword value pairs separated by ';' string[] args = value.Split(';'); string url=null; string[] colxpaths=null; string rowsxpath=null; string type="both"; // assume we want both attributes and elements foreach(string arg in args) { string[] param = arg.Trim().Split('='); if (param == null || param.Length != 2) continue; string key = param[0].Trim().ToLower(); string val = param[1]; switch (key) { case "url": case "file": url = val; break; case "rowsxpath": rowsxpath = val; break; case "type": { type = val.Trim().ToLower(); if (!(type == "attributes" || type == "elements" || type == "both")) throw new ArgumentException(string.Format("type '{0}' is invalid. Must be 'attributes', 'elements' or 'both'", val)); break; } case "columnsxpath": // column list is separated by ',' colxpaths = val.Trim().Split(','); break; default: throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0])); } } // User must specify both the url and the RowsXPath if (url == null) throw new ArgumentException("CommandText requires a 'Url=' parameter."); if (rowsxpath == null) throw new ArgumentException("CommandText requires a 'RowsXPath=' parameter."); _cmd = value; _Url = url; _Type = type; _RowsXPath = rowsxpath; if (colxpaths != null) _ColumnsXPath = new ArrayList(colxpaths); } } public IDataParameterCollection Parameters { get { return _Parameters; } } public IDbTransaction Transaction { get { throw new NotImplementedException("Transaction not implemented"); } set { throw new NotImplementedException("Transaction not implemented"); } } #endregion #region IDisposable Members public void Dispose() { // nothing to dispose of } #endregion } }
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Moq; using Xunit; using AutoRenter.Api.Controllers; using AutoRenter.Api.Models; using AutoRenter.Api.Services; using AutoRenter.Api.Tests.Helpers; using AutoRenter.Domain.Interfaces; using AutoRenter.Domain.Models; namespace AutoRenter.Api.Tests.Controllers { public class LocationsControllerTests { [Fact] public async void GetAll_WhenFound() { // arrange var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.GetAll()) .ReturnsAsync(() => new Result<IEnumerable<Location>>(ResultCode.Success, TestLocations())); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.GetAll(); var okResult = result as OkObjectResult; var response = okResult.Value as Dictionary<string, object>; // assert Assert.Equal(200, okResult.StatusCode); } [Fact] public async void GetAll_WhenNotFound() { // arrange var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.GetAll()) .ReturnsAsync(() => new Result<IEnumerable<Location>>(ResultCode.NotFound)); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.GetAll(); var notFoundResult = result as NotFoundResult; // assert Assert.NotNull(notFoundResult); } [Fact] public async void GetAll_ReturnsData() { // arrange var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.GetAll()) .ReturnsAsync(() => new Result<IEnumerable<Location>>(ResultCode.Success, TestLocations())); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); dataStructureConverterMoq.Setup(x => x.ConvertAndMap<IEnumerable<LocationModel>, IEnumerable<Location>>(It.IsAny<string>(), It.IsAny<IEnumerable<Location>>())) .Returns(new Dictionary<string, object> { { "locations", TestLocations() } }); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.GetAll(); var okResult = result as OkObjectResult; var response = okResult.Value as Dictionary<string, object>; // assert Assert.NotNull(response.Values); } [Fact] public async void Get_WhenFound() { // arrange var resultCodeConverter = new ResultCodeConverter(); var targetId = IdentifierHelper.LocationId; var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Get(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<Location>(ResultCode.Success, TestLocation())); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Get(targetId); var okResult = result as OkObjectResult; var response = okResult.Value as Dictionary<string, object>; // assert Assert.Equal(200, okResult.StatusCode); } [Fact] public async void Get_WhenNotFound() { // arrange var targetId = Guid.NewGuid(); var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Get(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<Location>(ResultCode.NotFound)); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Get(targetId); var notFoundResult = result as NotFoundResult; // assert Assert.Equal(404, notFoundResult.StatusCode); } [Fact] public async void Get_WithBadId() { // arrange var targetId = Guid.Empty; var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Get(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<Location>(ResultCode.Success, TestLocation())); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Get(targetId); var badRequestResult = result as BadRequestObjectResult; // assert Assert.NotNull(badRequestResult); } [Fact] public async void Get_ReturnsData() { // arrange var targetId = IdentifierHelper.LocationId; var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Get(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<Location>(ResultCode.Success, TestLocation())); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); dataStructureConverterMoq.Setup(x => x.ConvertAndMap<LocationModel, Location>(It.IsAny<string>(), It.IsAny<Location>())) .Returns(new Dictionary<string, object> { { "location", TestLocation() } }); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Get(targetId); var okResult = result as OkObjectResult; var response = okResult.Value as Dictionary<string, object>; // assert Assert.NotNull(response.Values); } [Fact] public async void Post_WhenValid() { // arrange var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Insert(It.IsAny<Location>())) .ReturnsAsync(() => new Result<Guid>(ResultCode.Success, TestLocation().Id)); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Post(TestLocationModel()); var createdAtRouteResult = result as CreatedAtRouteResult; // assert Assert.NotNull(createdAtRouteResult); } [Fact] public async void Post_WhenNotValid() { // arrange var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Insert(It.IsAny<Location>())) .ReturnsAsync(() => new Result<Guid>(ResultCode.BadRequest, TestLocation().Id)); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Post(TestLocationModel()); var badRequestResult = result as BadRequestResult; // assert Assert.NotNull(badRequestResult); } [Fact] public async void Post_WhenConflict() { // arrange var testLocation = TestLocationModel(); var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Insert(It.IsAny<Location>())) .ReturnsAsync(() => new Result<Guid>(ResultCode.Conflict, TestLocation().Id)); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Post(testLocation); var conflictResult = result as StatusCodeResult; // assert Assert.Equal(409, conflictResult.StatusCode); } [Fact] public async void Put_WhenValid() { // arrange var testLocation = TestLocationModel(); var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Update(It.IsAny<Location>())) .ReturnsAsync(() => new Result<Guid>(ResultCode.Success, TestLocation().Id)); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Put(testLocation.Id, testLocation); var okResult = result as OkObjectResult; // assert Assert.NotNull(okResult); } [Fact] public async void Put_WhenNotValid() { // arrange var testLocation = TestLocationModel(); var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Update(It.IsAny<Location>())) .ReturnsAsync(() => new Result<Guid>(ResultCode.BadRequest, TestLocation().Id)); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Put(testLocation.Id, testLocation); var badRequestResult = result as BadRequestResult; // assert Assert.NotNull(badRequestResult); } [Fact] public async void Delete_WhenValid() { // arrange var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Delete(It.IsAny<Guid>())) .ReturnsAsync(() => ResultCode.Success); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Delete(TestLocation().Id); var noContentResult = result as NoContentResult; // assert Assert.NotNull(noContentResult); } [Fact] public async void Delete_WhenNotValid() { // arrange var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Delete(It.IsAny<Guid>())) .ReturnsAsync(() => ResultCode.BadRequest); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Delete(TestLocation().Id); var badRequestResult = result as BadRequestResult; // assert Assert.NotNull(badRequestResult); } [Fact] public async void Delete_WhenNotFound() { // arrange var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.Delete(It.IsAny<Guid>())) .ReturnsAsync(() => ResultCode.NotFound); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.Delete(TestLocation().Id); var notFoundResult = result as NotFoundResult; // assert Assert.NotNull(notFoundResult); } [Fact] public async void GetAllVehicles_WhenFound() { // arrange var locationId = IdentifierHelper.LocationId; var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.GetVehicles(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.Success, TestVehicles())); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); dataStructureConverterMoq.Setup(x => x.ConvertAndMap<IEnumerable<VehicleModel>, IEnumerable<Vehicle>>(It.IsAny<string>(), It.IsAny<IEnumerable<Vehicle>>())) .Returns(new Dictionary<string, object> { { "vehicles", VehicleHelper.GetMany() } }); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.GetAllVehicles(locationId); var okResult = result as OkObjectResult; var response = okResult.Value as Dictionary<string, object>; // assert Assert.Equal(200, okResult.StatusCode); } [Fact] public async void GetAllVehicles_WhenNotFound() { // arrange var locationId = IdentifierHelper.LocationId; var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.GetVehicles(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.NotFound)); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); dataStructureConverterMoq.Setup(x => x.ConvertAndMap<IEnumerable<VehicleModel>, IEnumerable<Vehicle>>(It.IsAny<string>(), It.IsAny<IEnumerable<Vehicle>>())) .Returns(new Dictionary<string, object> { { "vehicles", new List<VehicleModel>() } }); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.GetAllVehicles(locationId); var okResult = result as OkObjectResult; var response = okResult.Value as Dictionary<string, object>; // assert Assert.NotNull(response); } [Fact] public async void GetAllVehicles_WithBadId() { // arrange var targetId = Guid.Empty; var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.GetVehicles(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.Success, TestVehicles())); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.GetAllVehicles(targetId); var badRequestResult = result as BadRequestObjectResult; // assert Assert.NotNull(badRequestResult); } [Fact] private async void GetAllVehicles_ReturnsData() { // arrange var locationId = IdentifierHelper.LocationId; var resultCodeConverter = new ResultCodeConverter(); var locationServiceMoq = new Mock<ILocationService>(); locationServiceMoq.Setup(x => x.GetVehicles(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.Success, TestVehicles())); var dataStructureConverterMoq = new Mock<IDataStructureConverter>(); dataStructureConverterMoq.Setup(x => x.ConvertAndMap<IEnumerable<VehicleModel>, IEnumerable<Vehicle>>(It.IsAny<string>(), It.IsAny<IEnumerable<Vehicle>>())) .Returns(new Dictionary<string, object> { { "vehicles", VehicleModelHelper.GetMany() } }); var sut = new LocationsController(locationServiceMoq.Object, resultCodeConverter, dataStructureConverterMoq.Object) { ControllerContext = DefaultControllerContext() }; // act var result = await sut.GetAllVehicles(locationId); var okResult = result as OkObjectResult; var response = okResult.Value as Dictionary<string, object>; // assert Assert.NotNull(response.Values); } private ControllerContext DefaultControllerContext() { return ControllerContextHelper.GetContext(); } private Location TestLocation() { return LocationHelper.Get(); } private LocationModel TestLocationModel() { return LocationModelHelper.Get(); } private IEnumerable<Location> TestLocations() { return LocationHelper.GetMany(); } private IEnumerable<LocationModel> TestLocationModels() { return LocationModelHelper.GetMany(); } private IEnumerable<Vehicle> TestVehicles() { return VehicleHelper.GetMany(); } private IEnumerable<VehicleModel> TestVehicleModels() { return VehicleModelHelper.GetMany(); } } }
namespace AngleSharp.Dom { /// <summary> /// The treewalker for walking through the DOM tree. /// </summary> sealed class TreeWalker : ITreeWalker { #region Fields private readonly INode _root; private readonly FilterSettings _settings; private readonly NodeFilter _filter; private INode _current; #endregion #region ctor public TreeWalker(INode root, FilterSettings settings, NodeFilter? filter) { _root = root; _settings = settings; _filter = filter ?? (m => FilterResult.Accept); _current = _root; } #endregion #region Properties public INode Root => _root; public FilterSettings Settings => _settings; public NodeFilter Filter => _filter; public INode Current { get => _current; set => _current = value; } #endregion #region Methods public INode? ToNext() { var node = _current; var result = FilterResult.Accept; while (node != null) { while (result != FilterResult.Reject && node.HasChildNodes) { node = node.FirstChild; result = Check(node); if (result == FilterResult.Accept) { _current = node; return node; } } while (node != _root) { var sibling = node!.NextSibling; if (sibling != null) { node = sibling; break; } node = node.Parent; } if (node == _root) { break; } result = Check(node); if (result == FilterResult.Accept) { _current = node; return node; } } return null; } public INode? ToPrevious() { var node = _current; while (node != null && node != _root) { var sibling = node.PreviousSibling; while (sibling != null) { node = sibling; var result = Check(node); while (result != FilterResult.Reject && node.HasChildNodes) { node = node.LastChild; result = Check(node); if (result == FilterResult.Accept) { _current = node; return node; } } } if (node == _root) { break; } var parent = node.Parent; if (parent is null) { break; } if (Check(node) == FilterResult.Accept) { _current = node; return node; } } return null; } public INode? ToParent() { var node = _current; while (node != null && node != _root) { node = node.Parent; if (node != null && Check(node) == FilterResult.Accept) { _current = node; return node; } } return null; } public INode? ToFirst() { var node = _current?.FirstChild; while (node != null) { var result = Check(node); if (result == FilterResult.Accept) { _current = node; return node; } else if (result == FilterResult.Skip) { var child = node.FirstChild; if (child != null) { node = child; continue; } } while (node != null) { var sibling = node.NextSibling; if (sibling != null) { node = sibling; break; } var parent = node.Parent; if (parent is null || parent == _root || parent == _current) { node = null; break; } node = parent; } } return null; } public INode? ToLast() { var node = _current?.LastChild; while (node != null) { var result = Check(node); if (result == FilterResult.Accept) { _current = node; return node; } else if (result == FilterResult.Skip) { var child = node.LastChild; if (child != null) { node = child; continue; } } while (node != null) { var sibling = node.PreviousSibling; if (sibling != null) { node = sibling; break; } var parent = node.Parent; if (parent is null || parent == _root || parent == _current) { node = null; break; } node = parent; } } return null; } public INode? ToPreviousSibling() { var node = _current; if (node != _root) { while (node != null) { var sibling = node.PreviousSibling; while (sibling != null) { node = sibling; var result = Check(node); if (result == FilterResult.Accept) { _current = node; return node; } sibling = node.LastChild; if (result == FilterResult.Reject || sibling is null) { sibling = node.PreviousSibling; } } node = node.Parent; if (node is null || node == _root || Check(node) == FilterResult.Accept) { break; } } } return null; } public INode? ToNextSibling() { var node = _current; if (node != _root) { while (node != null) { var sibling = node.NextSibling; while (sibling != null) { node = sibling; var result = Check(node); if (result == FilterResult.Accept) { _current = node; return node; } sibling = node.FirstChild; if (result == FilterResult.Reject || sibling is null) { sibling = node.NextSibling; } } node = node.Parent; if (node is null || node == _root || Check(node) == FilterResult.Accept) { break; } } } return null; } #endregion #region Helpers private FilterResult Check(INode node) { if (!_settings.Accepts(node)) { return FilterResult.Skip; } return _filter(node); } #endregion } }
using System; using System.Collections; using System.Globalization; using System.Management; using System.Reflection; using System.Runtime; using System.Runtime.InteropServices; namespace System.Management.Instrumentation { public class Instrumentation { private static string processIdentity; private static Hashtable instrumentedAssemblies; internal static string ProcessIdentity { get { lock (typeof(Instrumentation)) { if (Instrumentation.processIdentity == null) { Guid guid = Guid.NewGuid(); Instrumentation.processIdentity = guid.ToString().ToLower(CultureInfo.InvariantCulture); } } return Instrumentation.processIdentity; } } static Instrumentation() { Instrumentation.processIdentity = null; Instrumentation.instrumentedAssemblies = new Hashtable(); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public Instrumentation() { } public static void Fire(object eventData) { IEvent @event = eventData as IEvent; if (@event == null) { Instrumentation.GetFireFunction(eventData.GetType())(eventData); return; } else { @event.Fire(); return; } } [DllImport("kernel32.dll", CharSet=CharSet.Auto)] private static extern int GetCurrentProcessId(); internal static ProvisionFunction GetFireFunction(Type type) { return new ProvisionFunction(Instrumentation.GetInstrumentedAssembly(type.Assembly).Fire); } private static InstrumentedAssembly GetInstrumentedAssembly(Assembly assembly) { InstrumentedAssembly item; lock (Instrumentation.instrumentedAssemblies) { if (!Instrumentation.instrumentedAssemblies.ContainsKey(assembly)) { Instrumentation.Initialize(assembly); } item = (InstrumentedAssembly)Instrumentation.instrumentedAssemblies[assembly]; } return item; } internal static ProvisionFunction GetPublishFunction(Type type) { return new ProvisionFunction(Instrumentation.GetInstrumentedAssembly(type.Assembly).Publish); } internal static ProvisionFunction GetRevokeFunction(Type type) { return new ProvisionFunction(Instrumentation.GetInstrumentedAssembly(type.Assembly).Revoke); } private static void Initialize(Assembly assembly) { lock (Instrumentation.instrumentedAssemblies) { if (!Instrumentation.instrumentedAssemblies.ContainsKey(assembly)) { SchemaNaming schemaNaming = SchemaNaming.GetSchemaNaming(assembly); if (schemaNaming != null) { if (!schemaNaming.IsAssemblyRegistered()) { if (WMICapabilities.IsUserAdmin()) { schemaNaming.DecoupledProviderInstanceName = AssemblyNameUtility.UniqueToAssemblyFullVersion(assembly); schemaNaming.RegisterNonAssemblySpecificSchema(null); schemaNaming.RegisterAssemblySpecificSchema(); } else { throw new Exception(RC.GetString("ASSEMBLY_NOT_REGISTERED")); } } InstrumentedAssembly instrumentedAssembly = new InstrumentedAssembly(assembly, schemaNaming); Instrumentation.instrumentedAssemblies.Add(assembly, instrumentedAssembly); } } } } public static bool IsAssemblyRegistered(Assembly assemblyToRegister) { bool flag; if (null != assemblyToRegister) { lock (Instrumentation.instrumentedAssemblies) { if (!Instrumentation.instrumentedAssemblies.ContainsKey(assemblyToRegister)) { goto Label0; } else { flag = true; } } return flag; } else { throw new ArgumentNullException("assemblyToRegister"); } Label0: SchemaNaming schemaNaming = SchemaNaming.GetSchemaNaming(assemblyToRegister); if (schemaNaming != null) { return schemaNaming.IsAssemblyRegistered(); } else { return false; } } public static void Publish(object instanceData) { Type type = instanceData as Type; Assembly assembly = instanceData as Assembly; IInstance instance = instanceData as IInstance; if (type == null) { if (assembly == null) { if (instance == null) { Instrumentation.GetPublishFunction(instanceData.GetType())(instanceData); return; } else { instance.Published = true; return; } } else { Instrumentation.GetInstrumentedAssembly(assembly); return; } } else { Instrumentation.GetInstrumentedAssembly(type.Assembly); return; } } public static void RegisterAssembly(Assembly assemblyToRegister) { if (null != assemblyToRegister) { Instrumentation.GetInstrumentedAssembly(assemblyToRegister); return; } else { throw new ArgumentNullException("assemblyToRegister"); } } public static void Revoke(object instanceData) { IInstance instance = instanceData as IInstance; if (instance == null) { Instrumentation.GetRevokeFunction(instanceData.GetType())(instanceData); return; } else { instance.Published = false; return; } } public static void SetBatchSize(Type instrumentationClass, int batchSize) { Instrumentation.GetInstrumentedAssembly(instrumentationClass.Assembly).SetBatchSize(instrumentationClass, batchSize); } } }
namespace android.database { [global::MonoJavaBridge.JavaClass()] public partial class MergeCursor : android.database.AbstractCursor { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static MergeCursor() { InitJNI(); } protected MergeCursor(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getShort2761; public override short getShort(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallShortMethod(this.JvmHandle, global::android.database.MergeCursor._getShort2761, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._getShort2761, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getInt2762; public override int getInt(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.MergeCursor._getInt2762, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._getInt2762, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getLong2763; public override long getLong(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.MergeCursor._getLong2763, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._getLong2763, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getFloat2764; public override float getFloat(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.database.MergeCursor._getFloat2764, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._getFloat2764, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDouble2765; public override double getDouble(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallDoubleMethod(this.JvmHandle, global::android.database.MergeCursor._getDouble2765, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._getDouble2765, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _close2766; public override void close() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.MergeCursor._close2766); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._close2766); } internal static global::MonoJavaBridge.MethodId _getString2767; public override global::java.lang.String getString(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.MergeCursor._getString2767, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._getString2767, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _registerContentObserver2768; public override void registerContentObserver(android.database.ContentObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.MergeCursor._registerContentObserver2768, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._registerContentObserver2768, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _unregisterContentObserver2769; public override void unregisterContentObserver(android.database.ContentObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.MergeCursor._unregisterContentObserver2769, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._unregisterContentObserver2769, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getCount2770; public override int getCount() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.MergeCursor._getCount2770); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._getCount2770); } internal static global::MonoJavaBridge.MethodId _getColumnNames2771; public override global::java.lang.String[] getColumnNames() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.MergeCursor._getColumnNames2771)) as java.lang.String[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._getColumnNames2771)) as java.lang.String[]; } internal static global::MonoJavaBridge.MethodId _getBlob2772; public override byte[] getBlob(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.MergeCursor._getBlob2772, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._getBlob2772, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[]; } internal static global::MonoJavaBridge.MethodId _isNull2773; public override bool isNull(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.MergeCursor._isNull2773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._isNull2773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _deactivate2774; public override void deactivate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.MergeCursor._deactivate2774); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._deactivate2774); } internal static global::MonoJavaBridge.MethodId _requery2775; public override bool requery() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.MergeCursor._requery2775); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._requery2775); } internal static global::MonoJavaBridge.MethodId _registerDataSetObserver2776; public override void registerDataSetObserver(android.database.DataSetObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.MergeCursor._registerDataSetObserver2776, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._registerDataSetObserver2776, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _unregisterDataSetObserver2777; public override void unregisterDataSetObserver(android.database.DataSetObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.MergeCursor._unregisterDataSetObserver2777, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._unregisterDataSetObserver2777, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onMove2778; public override bool onMove(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.MergeCursor._onMove2778, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.MergeCursor.staticClass, global::android.database.MergeCursor._onMove2778, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _MergeCursor2779; public MergeCursor(android.database.Cursor[] arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.database.MergeCursor.staticClass, global::android.database.MergeCursor._MergeCursor2779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.database.MergeCursor.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/MergeCursor")); global::android.database.MergeCursor._getShort2761 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "getShort", "(I)S"); global::android.database.MergeCursor._getInt2762 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "getInt", "(I)I"); global::android.database.MergeCursor._getLong2763 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "getLong", "(I)J"); global::android.database.MergeCursor._getFloat2764 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "getFloat", "(I)F"); global::android.database.MergeCursor._getDouble2765 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "getDouble", "(I)D"); global::android.database.MergeCursor._close2766 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "close", "()V"); global::android.database.MergeCursor._getString2767 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "getString", "(I)Ljava/lang/String;"); global::android.database.MergeCursor._registerContentObserver2768 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "registerContentObserver", "(Landroid/database/ContentObserver;)V"); global::android.database.MergeCursor._unregisterContentObserver2769 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "unregisterContentObserver", "(Landroid/database/ContentObserver;)V"); global::android.database.MergeCursor._getCount2770 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "getCount", "()I"); global::android.database.MergeCursor._getColumnNames2771 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "getColumnNames", "()[Ljava/lang/String;"); global::android.database.MergeCursor._getBlob2772 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "getBlob", "(I)[B"); global::android.database.MergeCursor._isNull2773 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "isNull", "(I)Z"); global::android.database.MergeCursor._deactivate2774 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "deactivate", "()V"); global::android.database.MergeCursor._requery2775 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "requery", "()Z"); global::android.database.MergeCursor._registerDataSetObserver2776 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "registerDataSetObserver", "(Landroid/database/DataSetObserver;)V"); global::android.database.MergeCursor._unregisterDataSetObserver2777 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "unregisterDataSetObserver", "(Landroid/database/DataSetObserver;)V"); global::android.database.MergeCursor._onMove2778 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "onMove", "(II)Z"); global::android.database.MergeCursor._MergeCursor2779 = @__env.GetMethodIDNoThrow(global::android.database.MergeCursor.staticClass, "<init>", "([Landroid/database/Cursor;)V"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ExtractInt641() { var test = new ExtractScalarTest__ExtractInt641(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ExtractScalarTest__ExtractInt641 { private struct TestStruct { public Vector128<Int64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(ExtractScalarTest__ExtractInt641 testClass) { var result = Sse41.X64.Extract(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector128<Int64> _clsVar; private Vector128<Int64> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; static ExtractScalarTest__ExtractInt641() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public ExtractScalarTest__ExtractInt641() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.X64.Extract( Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.X64.Extract( Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.X64.Extract( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.X64.Extract( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr); var result = Sse41.X64.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse41.X64.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse41.X64.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ExtractScalarTest__ExtractInt641(); var result = Sse41.X64.Extract(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.X64.Extract(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.X64.Extract(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((result[0] != firstOp[1])) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41.X64)}.{nameof(Sse41.X64.Extract)}<Int64>(Vector128<Int64><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // Copyright (c) Microsoft Corporation. // // 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; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation.Language; using System.Reflection; namespace Microsoft.Windows.PowerShell.ScriptAnalyzer { internal enum SettingsMode { None = 0, Auto, File, Hashtable, Preset }; public class Settings { private string filePath; private List<string> includeRules; private List<string> excludeRules; private List<string> severities; private Dictionary<string, Dictionary<string, object>> ruleArguments; public string FilePath { get { return filePath; } } public IEnumerable<string> IncludeRules { get { return includeRules; } } public IEnumerable<string> ExcludeRules { get { return excludeRules; } } public IEnumerable<string> Severities { get { return severities; } } public Dictionary<string, Dictionary<string, object>> RuleArguments { get { return ruleArguments; } } public Settings(object settings, Func<string, string> presetResolver) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } includeRules = new List<string>(); excludeRules = new List<string>(); severities = new List<string>(); ruleArguments = new Dictionary<string, Dictionary<string, object>>(StringComparer.OrdinalIgnoreCase); var settingsFilePath = settings as string; //it can either be a preset or path to a file or a hashtable if (settingsFilePath != null) { if (presetResolver != null) { var resolvedFilePath = presetResolver(settingsFilePath); if (resolvedFilePath != null) { settingsFilePath = resolvedFilePath; } } if (File.Exists(settingsFilePath)) { filePath = settingsFilePath; parseSettingsFile(settingsFilePath); } else { throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Strings.InvalidPath, settingsFilePath)); } } else { var settingsHashtable = settings as Hashtable; if (settingsHashtable != null) { parseSettingsHashtable(settingsHashtable); } else { throw new ArgumentException(Strings.SettingsInvalidType); } } } public Settings(object settings) : this(settings, null) { } /// <summary> /// Retrieves the Settings directory from the Module directory structure /// </summary> public static string GetShippedSettingsDirectory() { // Find the compatibility files in Settings folder var path = typeof(Helper).GetTypeInfo().Assembly.Location; if (String.IsNullOrWhiteSpace(path)) { return null; } var settingsPath = Path.Combine(Path.GetDirectoryName(path), "Settings"); if (!Directory.Exists(settingsPath)) { // try one level down as the PSScriptAnalyzer module structure is not consistent // CORECLR binaries are in PSScriptAnalyzer/coreclr/, PowerShell v3 binaries are in PSScriptAnalyzer/PSv3/ // and PowerShell v5 binaries are in PSScriptAnalyzer/ settingsPath = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(path)), "Settings"); if (!Directory.Exists(settingsPath)) { return null; } } return settingsPath; } /// <summary> /// Returns the builtin setting presets /// /// Looks for powershell data files (*.psd1) in the PSScriptAnalyzer module settings directory /// and returns the names of the files without extension /// </summary> public static IEnumerable<string> GetSettingPresets() { var settingsPath = GetShippedSettingsDirectory(); if (settingsPath != null) { foreach (var filepath in System.IO.Directory.EnumerateFiles(settingsPath, "*.psd1")) { yield return System.IO.Path.GetFileNameWithoutExtension(filepath); } } } /// <summary> /// Gets the path to the settings file corresponding to the given preset. /// /// If the corresponding preset file is not found, the method returns null. /// </summary> public static string GetSettingPresetFilePath(string settingPreset) { var settingsPath = GetShippedSettingsDirectory(); if (settingsPath != null) { if (GetSettingPresets().Contains(settingPreset, StringComparer.OrdinalIgnoreCase)) { return System.IO.Path.Combine(settingsPath, settingPreset + ".psd1"); } } return null; } /// <summary> /// Recursively convert hashtable to dictionary /// </summary> /// <param name="hashtable"></param> /// <returns>Dictionary that maps string to object</returns> private Dictionary<string, object> GetDictionaryFromHashtable(Hashtable hashtable) { var dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); foreach (var obj in hashtable.Keys) { string key = obj as string; if (key == null) { throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.KeyNotString, key)); } var valueHashtableObj = hashtable[obj]; if (valueHashtableObj == null) { throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.WrongValueHashTable, "", key)); } var valueHashtable = valueHashtableObj as Hashtable; if (valueHashtable == null) { dictionary.Add(key, valueHashtableObj); } else { dictionary.Add(key, GetDictionaryFromHashtable(valueHashtable)); } } return dictionary; } private bool IsStringOrStringArray(object val) { if (val is string) { return true; } var valArr = val as object[]; return val == null ? false : valArr.All(x => x is string); } private List<string> GetData(object val, string key) { // value must be either string or or an array of strings if (val == null) { throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.WrongValueHashTable, "", key)); } List<string> values = new List<string>(); var valueStr = val as string; if (valueStr != null) { values.Add(valueStr); } else { var valueArr = val as object[]; if (valueArr == null) { // check if it is an array of strings valueArr = val as string[]; } if (valueArr != null) { foreach (var item in valueArr) { var itemStr = item as string; if (itemStr != null) { values.Add(itemStr); } else { throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.WrongValueHashTable, val, key)); } } } else { throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.WrongValueHashTable, val, key)); } } return values; } /// <summary> /// Sets the arguments for consumption by rules /// </summary> /// <param name="ruleArgs">A hashtable with rule names as keys</param> private Dictionary<string, Dictionary<string, object>> ConvertToRuleArgumentType(object ruleArguments) { var ruleArgs = ruleArguments as Dictionary<string, object>; if (ruleArgs == null) { throw new ArgumentException(Strings.SettingsInputShouldBeDictionary, nameof(ruleArguments)); } if (ruleArgs.Comparer != StringComparer.OrdinalIgnoreCase) { throw new ArgumentException(Strings.SettingsDictionaryShouldBeCaseInsesitive, nameof(ruleArguments)); } var ruleArgsDict = new Dictionary<string, Dictionary<string, object>>(StringComparer.OrdinalIgnoreCase); foreach (var rule in ruleArgs.Keys) { var argsDict = ruleArgs[rule] as Dictionary<string, object>; if (argsDict == null) { throw new InvalidDataException(Strings.SettingsInputShouldBeDictionary); } ruleArgsDict[rule] = argsDict; } return ruleArgsDict; } private void parseSettingsHashtable(Hashtable settingsHashtable) { HashSet<string> validKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var settings = GetDictionaryFromHashtable(settingsHashtable); foreach (var settingKey in settings.Keys) { var key = settingKey.ToLower(); object val = settings[key]; switch (key) { case "severity": severities = GetData(val, key); break; case "includerules": includeRules = GetData(val, key); break; case "excluderules": excludeRules = GetData(val, key); break; case "rules": try { ruleArguments = ConvertToRuleArgumentType(val); } catch (ArgumentException argumentException) { throw new InvalidDataException( string.Format(CultureInfo.CurrentCulture, Strings.WrongValueHashTable, "", key), argumentException); } break; default: throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.WrongKeyHashTable, key)); } } } private void parseSettingsFile(string settingsFilePath) { Token[] parserTokens = null; ParseError[] parserErrors = null; Ast profileAst = Parser.ParseFile(settingsFilePath, out parserTokens, out parserErrors); IEnumerable<Ast> hashTableAsts = profileAst.FindAll(item => item is HashtableAst, false); // no hashtable, raise warning if (hashTableAsts.Count() == 0) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.InvalidProfile, settingsFilePath)); } HashtableAst hashTableAst = hashTableAsts.First() as HashtableAst; Hashtable hashtable; try { // ideally we should use HashtableAst.SafeGetValue() but since // it is not available on PSv3, we resort to our own narrow implementation. hashtable = GetHashtableFromHashTableAst(hashTableAst); } catch (InvalidOperationException e) { throw new ArgumentException(Strings.InvalidProfile, e); } if (hashtable == null) { throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Strings.InvalidProfile, settingsFilePath)); } parseSettingsHashtable(hashtable); } private Hashtable GetHashtableFromHashTableAst(HashtableAst hashTableAst) { var output = new Hashtable(); foreach (var kvp in hashTableAst.KeyValuePairs) { var keyAst = kvp.Item1 as StringConstantExpressionAst; if (keyAst == null) { // first item (the key) should be a string ThrowInvalidDataException(kvp.Item1); } var key = keyAst.Value; // parse the item2 as array PipelineAst pipeAst = kvp.Item2 as PipelineAst; List<string> rhsList = new List<string>(); if (pipeAst != null) { ExpressionAst pureExp = pipeAst.GetPureExpression(); var constExprAst = pureExp as ConstantExpressionAst; if (constExprAst != null) { var strConstExprAst = constExprAst as StringConstantExpressionAst; if (strConstExprAst != null) { rhsList.Add(strConstExprAst.Value); } else { // it is either an integer or a float output[key] = constExprAst.Value; continue; } } else if (pureExp is HashtableAst) { output[key] = GetHashtableFromHashTableAst((HashtableAst)pureExp); continue; } else if (pureExp is VariableExpressionAst) { var varExprAst = (VariableExpressionAst)pureExp; switch (varExprAst.VariablePath.UserPath.ToLower()) { case "true": output[key] = true; break; case "false": output[key] = false; break; default: ThrowInvalidDataException(varExprAst.Extent); break; } continue; } else { rhsList = GetArrayFromAst(pureExp); } } if (rhsList.Count == 0) { ThrowInvalidDataException(kvp.Item2); } output[key] = rhsList.ToArray(); } return output; } private List<string> GetArrayFromAst(ExpressionAst exprAst) { ArrayLiteralAst arrayLitAst = exprAst as ArrayLiteralAst; var result = new List<string>(); if (arrayLitAst == null && exprAst is ArrayExpressionAst) { ArrayExpressionAst arrayExp = (ArrayExpressionAst)exprAst; return arrayExp == null ? null : GetArrayFromArrayExpressionAst(arrayExp); } if (arrayLitAst == null) { ThrowInvalidDataException(arrayLitAst); } foreach (var element in arrayLitAst.Elements) { var elementValue = element as StringConstantExpressionAst; if (elementValue == null) { ThrowInvalidDataException(element); } result.Add(elementValue.Value); } return result; } private List<string> GetArrayFromArrayExpressionAst(ArrayExpressionAst arrayExp) { var result = new List<string>(); if (arrayExp.SubExpression != null) { StatementAst stateAst = arrayExp.SubExpression.Statements.FirstOrDefault(); if (stateAst != null && stateAst is PipelineAst) { CommandBaseAst cmdBaseAst = (stateAst as PipelineAst).PipelineElements.FirstOrDefault(); if (cmdBaseAst != null && cmdBaseAst is CommandExpressionAst) { CommandExpressionAst cmdExpAst = cmdBaseAst as CommandExpressionAst; if (cmdExpAst.Expression is StringConstantExpressionAst) { return new List<string>() { (cmdExpAst.Expression as StringConstantExpressionAst).Value }; } else { // It should be an ArrayLiteralAst at this point return GetArrayFromAst(cmdExpAst.Expression); } } } } return null; } private void ThrowInvalidDataException(Ast ast) { ThrowInvalidDataException(ast.Extent); } private void ThrowInvalidDataException(IScriptExtent extent) { throw new InvalidDataException(string.Format( CultureInfo.CurrentCulture, Strings.WrongValueFormat, extent.StartLineNumber, extent.StartColumnNumber, extent.File ?? "")); } private static bool IsBuiltinSettingPreset(object settingPreset) { var preset = settingPreset as string; if (preset != null) { return GetSettingPresets().Contains(preset, StringComparer.OrdinalIgnoreCase); } return false; } internal static SettingsMode FindSettingsMode(object settings, string path, out object settingsFound) { var settingsMode = SettingsMode.None; settingsFound = settings; if (settingsFound == null) { if (path != null) { // add a directory separator character because if there is no trailing separator character, it will return the parent var directory = path.TrimEnd(System.IO.Path.DirectorySeparatorChar); if (File.Exists(directory)) { // if given path is a file, get its directory directory = Path.GetDirectoryName(directory); } if (Directory.Exists(directory)) { // if settings are not provided explicitly, look for it in the given path // check if pssasettings.psd1 exists var settingsFilename = "PSScriptAnalyzerSettings.psd1"; var settingsFilePath = Path.Combine(directory, settingsFilename); settingsFound = settingsFilePath; if (File.Exists(settingsFilePath)) { settingsMode = SettingsMode.Auto; } } } } else { var settingsFilePath = settingsFound as String; if (settingsFilePath != null) { if (IsBuiltinSettingPreset(settingsFilePath)) { settingsMode = SettingsMode.Preset; settingsFound = GetSettingPresetFilePath(settingsFilePath); } else { settingsMode = SettingsMode.File; settingsFound = settingsFilePath; } } else { if (settingsFound is Hashtable) { settingsMode = SettingsMode.Hashtable; } } } return settingsMode; } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Xml; using XenAdmin.Controls; using XenAdmin.Core; using XenAPI; using XenAdmin.Actions; using XenAdmin.Dialogs; using XenCenterLib; namespace XenAdmin.Wizards.BugToolWizardFiles { public partial class BugToolPageSelectCapabilities : XenTabPage { #region Private fields private List<Host> _hostList = new List<Host>(); private List<Capability> _capabilities = new List<Capability>(); private Dictionary<Host, List<Capability>> hostCapabilities; private List<GetSystemStatusCapabilities> actions; private ActionProgressDialog dialog; private bool cancelled; #endregion public BugToolPageSelectCapabilities() { InitializeComponent(); this.linkLabel1.Visible = !XenAdmin.Core.HiddenFeatures.LinkLabelHidden; } public override string Text{get { return Messages.BUGTOOL_PAGE_CAPABILITIES_TEXT; }} public override string PageTitle { get { return Messages.BUGTOOL_PAGE_CAPABILITIES_PAGETITLE; } } public override string HelpID { get { return "SelectReportContents"; } } public override bool EnableNext() { return wizardCheckAnyChecked(); } protected override void PageLoadedCore(PageLoadedDirection direction) { if (direction == PageLoadedDirection.Forward) { ClearButton.Enabled = wizardCheckAnyChecked(); SelectButton.Enabled = wizardCheckAnyUnchecked(); } } private bool wizardCheckAnyChecked() { foreach (DataGridViewRow row in dataGridViewItems.Rows) { var capRow = row as CapabilityRow; if (capRow != null && capRow.Capability.Checked) return true; } return false; } private bool wizardCheckAnyUnchecked() { foreach (DataGridViewRow row in dataGridViewItems.Rows) { var capRow = row as CapabilityRow; if (capRow != null && !capRow.Capability.Checked) return true; } return false; } /// <summary> /// /// </summary> /// <param name="HostList"></param> /// <returns>If success of not - false with stop moving to next page</returns> public bool GetCommonCapabilities(List<Host> HostList) { if (!cancelled && Helpers.ListsContentsEqual<Host>(_hostList, HostList)) return true; _hostList = HostList; dataGridViewItems.Rows.Clear(); if (dialog != null && dialog.Visible) dialog.Close(); hostCapabilities = new Dictionary<Host, List<Capability>>(); actions = new List<GetSystemStatusCapabilities>(); cancelled = false; dialog = new ActionProgressDialog(Messages.SERVER_STATUS_REPORT_GET_CAPABILITIES); dialog.ShowCancel = true; dialog.CancelClicked += new EventHandler(dialog_CancelClicked); foreach (Host host in _hostList) { GetSystemStatusCapabilities action = new GetSystemStatusCapabilities(host); actions.Add(action); action.Completed += Common_action_Completed; action.RunAsync(); } if (_hostList.Count > 0) dialog.ShowDialog(this); return !cancelled; } private void dialog_CancelClicked(object sender, EventArgs e) { dialog.Close(); cancelled = true; // Need to unhook events on current actions, to stop them // interfeering when they return in 20mins foreach (GetSystemStatusCapabilities action in actions) action.Completed -= Common_action_Completed; } private void Common_action_Completed(ActionBase sender) { Program.Invoke(this, delegate() { if (cancelled) return; GetSystemStatusCapabilities caps = sender as GetSystemStatusCapabilities; if (caps == null) return; hostCapabilities[caps.Host] = caps.Succeeded ? parseXMLToList(caps) : null; if (hostCapabilities.Count >= _hostList.Count) { dialog.Close(); CombineCapabilitiesLists(); } }); } private List<Capability> parseXMLToList(Actions.GetSystemStatusCapabilities action) { List<Capability> capabilities = new List<Capability>(); XmlDocument doc = new XmlDocument(); doc.LoadXml(action.Result); foreach (XmlNode node in doc.GetElementsByTagName("capability")) { Capability c = new Capability(); foreach (XmlAttribute a in node.Attributes) { string name = a.Name; string value = a.Value; if (name == "content-type") c.ContentType = value == "text/plain" ? ContentType.text_plain : ContentType.application_data; else if (name == "default-checked") c.DefaultChecked = value == "yes" ? true : false; else if (name == "key") c.Key = value; else if (name == "max-size") c.MaxSize = Int64.Parse(value); else if (name == "min-size") c.MinSize = Int64.Parse(value); else if (name == "pii") c.PII = value == "yes" ? PrivateInformationIncluded.yes : value == "no" ? PrivateInformationIncluded.no : value == "maybe" ? PrivateInformationIncluded.maybe : PrivateInformationIncluded.customized; } capabilities.Add(c); } return capabilities; } private void CombineCapabilitiesLists() { List<Capability> combination = null; foreach (List<Capability> capabilities in hostCapabilities.Values) { if (capabilities == null) continue; if (combination == null) { combination = capabilities; continue; } combination = Helpers.ListsCommonItems<Capability>(combination, capabilities); } if (combination == null || combination.Count <= 0) { using (var dlg = new ErrorDialog(Messages.SERVER_STATUS_REPORT_CAPABILITIES_FAILED) {WindowTitle = Messages.SERVER_STATUS_REPORT}) { dlg.ShowDialog(this); } cancelled = true; return; } _capabilities = combination; _capabilities.Add(GetClientCapability()); Sort_capabilities(); buildList(); } private Capability GetClientCapability() { Capability clientCap = new Capability(); clientCap.ContentType = ContentType.text_plain; clientCap.DefaultChecked = true; clientCap.Key = "client-logs"; clientCap.MaxSize = getLogSize(); clientCap.MinSize = clientCap.MaxSize; clientCap.PII = PrivateInformationIncluded.yes; return clientCap; } private void Sort_capabilities() { _capabilities.Sort(new Comparison<Capability>(delegate(Capability obj1, Capability obj2) { int piicompare = obj1.PII.CompareTo(obj2.PII); if (piicompare == 0) return StringUtility.NaturalCompare(obj1.ToString(), obj2.ToString()); else return piicompare; })); } private void OnCheckedCapabilitiesChanged() { string totalSize; CalculateTotalSize(out totalSize); TotalSizeValue.Text = totalSize; ClearButton.Enabled = wizardCheckAnyChecked(); SelectButton.Enabled = wizardCheckAnyUnchecked(); OnPageUpdated(); } private void buildList() { try { dataGridViewItems.SuspendLayout(); dataGridViewItems.Rows.Clear(); var list = new List<DataGridViewRow>(); foreach (Capability c in _capabilities) list.Add(new CapabilityRow(c)); dataGridViewItems.Rows.AddRange(list.ToArray()); } finally { dataGridViewItems.ResumeLayout(); } OnCheckedCapabilitiesChanged(); } private long getLogSize() { String path = Program.GetLogFile(); if (path != null) { // Size of XenCenter.log FileInfo logFileInfo = new FileInfo(path); long total = logFileInfo.Length; // Add size of any XenCenter.log.x DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(path)); Regex regex = new Regex(Regex.Escape(Path.GetFileName(path)) + @"\.\d+"); foreach (FileInfo file in di.GetFiles()) { if (regex.IsMatch(file.Name)) total += file.Length; } return total; } else { return 50 * Util.BINARY_MEGA; } } private void CalculateTotalSize(out string totalSize) { var sizeMinList = new List<long>(); var sizeMaxList = new List<long>(); foreach (var row in dataGridViewItems.Rows) { var capRow = row as CapabilityRow; if (capRow != null && capRow.Capability.Checked) { var c = capRow.Capability; int m = c.Key == "client-logs" ? 1 : _hostList.Count; sizeMinList.Add(c.MinSize * m); sizeMaxList.Add(c.MaxSize * m); } } totalSize = Helpers.StringFromMaxMinSizeList(sizeMinList, sizeMaxList); } public List<Capability> Capabilities { get { return (from DataGridViewRow row in dataGridViewItems.Rows let capRow = row as CapabilityRow where capRow != null && capRow.Capability.Checked select capRow.Capability).ToList(); } } #region Control event handlers private void dataGridViewItems_SortCompare(object sender, DataGridViewSortCompareEventArgs e) { var row1 = dataGridViewItems.Rows[e.RowIndex1] as CapabilityRow; var row2 = dataGridViewItems.Rows[e.RowIndex2] as CapabilityRow; if (row1 != null && row2 != null && e.Column.Index == columnImage.Index) { e.SortResult = row1.Capability.PII.CompareTo(row2.Capability.PII); e.Handled = true; } } private void dataGridViewItems_SelectionChanged(object sender, EventArgs e) { if (dataGridViewItems.SelectedRows.Count > 0) { var row = dataGridViewItems.SelectedRows[0] as CapabilityRow; if (row == null) return; DescriptionValue.Text = row.Capability.Description; SizeValue.Text = row.Capability.EstimatedSize; } } private void dataGridViewItems_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex != columnCheck.Index) return; if (e.RowIndex < 0 || e.RowIndex >= dataGridViewItems.RowCount) return; var row = dataGridViewItems.Rows[e.RowIndex] as CapabilityRow; if (row == null) return; row.Capability.Checked = !row.Capability.Checked; row.Update(); OnCheckedCapabilitiesChanged(); } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { System.Diagnostics.Process.Start(InvisibleMessages.PRIVACY); } catch { using (var dlg = new ErrorDialog(Messages.HOMEPAGE_ERROR_MESSAGE)) dlg.ShowDialog(this); } } private void SelectButton_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridViewItems.Rows) { var capRow = row as CapabilityRow; if (capRow != null && !capRow.Capability.Checked) { capRow.Capability.Checked = true; capRow.Update(); } } OnCheckedCapabilitiesChanged(); } private void ClearButton_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridViewItems.Rows) { var capRow = row as CapabilityRow; if (capRow != null && capRow.Capability.Checked) { capRow.Capability.Checked = false; capRow.Update(); } } OnCheckedCapabilitiesChanged(); } #endregion private class CapabilityRow : DataGridViewRow { public readonly Capability Capability; private readonly DataGridViewCheckBoxCell cellCheck = new DataGridViewCheckBoxCell(); private readonly DataGridViewTextBoxCell cellItem = new DataGridViewTextBoxCell(); private readonly DataGridViewImageCell cellImage = new DataGridViewImageCell(); public CapabilityRow(Capability capability) { Capability = capability; Cells.AddRange(cellCheck, cellItem, cellImage); Update(); } public void Update() { cellCheck.Value = Capability.Checked; cellItem.Value = Capability.Name; switch(Capability.PII) { case PrivateInformationIncluded.maybe: cellImage.Value = Properties.Resources.alert2_16; break; case PrivateInformationIncluded.customized: cellImage.Value = Properties.Resources.alert3_16; break; case PrivateInformationIncluded.no: cellImage.Value = Properties.Resources.alert4_16; break; case PrivateInformationIncluded.yes: default: cellImage.Value = Properties.Resources.alert1_16; break; } cellImage.ToolTipText = Capability.PiiText; } } } public enum ContentType { text_plain, application_data }; public enum PrivateInformationIncluded { yes, maybe, customized, no}; public class Capability : IComparable<Capability>, IEquatable<Capability> { public ContentType ContentType; bool _defaultChecked; public long MaxSize; public long MinSize; public PrivateInformationIncluded PII; private string _key; private string _name; private string _description; public bool Checked; public bool DefaultChecked { get { return _defaultChecked; } set { _defaultChecked = value; Checked = value; } } public string PiiText { get { switch (PII) { case PrivateInformationIncluded.yes: return Messages.PII_YES; case PrivateInformationIncluded.maybe: return Messages.PII_MAYBE; case PrivateInformationIncluded.customized: return Messages.PII_CUSTOMISED; case PrivateInformationIncluded.no: default: return Messages.PII_NO; } } } public string Key { get { return _key; } set { _key = value; _name = FriendlyNameManager.GetFriendlyName(string.Format("Label-host.system_status-{0}", _key)); if (string.IsNullOrEmpty(_name)) _name = _key; _description = FriendlyNameManager.GetFriendlyName(string.Format("Description-host.system_status-{0}", _key)); } } public string Name { get { return _name; } } public string Description { get { return _description; } } public string EstimatedSize { get { return Helpers.StringFromMaxMinSize(MinSize, MaxSize); } } public override string ToString() { return _name; } public int CompareTo(Capability other) { return StringUtility.NaturalCompare(this.Key, other.Key); } public bool Equals(Capability other) { return this.Key.Equals(other.Key); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace TicketingSystem.Server.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.IO; using System.Collections; using Franson.BlueTools; using System.Threading; namespace Chat { public delegate void ParticipantDisconnectedHandler(Participant participant); /// <summary> /// The ChatManager manages the spontanuous networks that occure when devices locate /// eachother. /// </summary> public class ChatManager { public event ParticipantDisconnectedHandler ParticipantDisconnected; /// <summary> /// Raised whenever a message is received from a device. /// </summary> public event MessageReceivedHandler MessageReceived; /// <summary> /// Fired whenever the profile of a device changes. /// </summary> public event ProfileChangedHandler ProfileChanged; /// <summary> /// List of all participants. /// </summary> private ArrayList participants = new ArrayList(); /// <summary> /// The profile of this device. /// </summary> private Profile profile = new Profile(); /// <summary> /// The ChatService that allows devices to connect to this device. /// </summary> private ChatService chatService = new ChatService(); /// <summary> /// The thread in which we're discovering devices. /// </summary> private Thread discoveryThread = null; /// <summary> /// Whether or not the chat service should be enabled. This is only /// used to exit the threads upon exit. /// </summary> private bool opened = true; /// <summary> /// Creates /// </summary> public ChatManager() { // Initialize the profile. We'll name the chat participant "Unnamed" when it // has not been set explicitly by the user. // profile.Name = "Unnamed"; // Fetch the available networks. This will only return one network in BlueTools 1.0, // but always assume several networks might be returned, for compatibility with // future versions. // Network[] networks = Manager.GetManager().Networks; // Go through each network available and advertise the chat service so that is availble // on each network. // foreach(Network network in networks) { network.DeviceDiscoveryStarted += new BlueToolsEventHandler(network_DeviceDiscoveryStarted); // Attach a DeviceDiscovered event delegate to the current network. This will enable // us to handle device discoveries so we can negotiate a connection with the client. // network.DeviceDiscovered += new BlueToolsEventHandler(network_DeviceDiscovered); // Attach a DeviceList event handler to the current network. This will enable us // to handle lost devices. When a device is lost, we will want to disconnect // and remove the device from the list of participants. // network.DeviceLost += new BlueToolsEventHandler(network_DeviceLost); // Advertise the chat service on the server of the current network. // try { network.Server.Advertise(chatService); } catch (Exception exc) { System.Windows.Forms.MessageBox.Show("Could not start chat service: " + exc.Message); } // Enable auto discovery on the network. This will cause the network to continuosly // search for new devices. This is also necessary to get notified about lost devices. // network.AutoDiscovery = true; } // The chat service will negotiate connections with clients. Once a connection has // been negotiated, a participant has connected. This will cause the chat manager // to download the remote device profile. Once this is done, this event will be fired. // chatService.ParticipantConnected += new ParticipantConnectedHandler(chatService_ParticipantConnected); } public bool IsConnected(Address address) { foreach(Participant p in participants) { if(p.Address.HostAddress.Equals(address)) { return true; } } return false; } /// <summary> /// Closes the ChatManager and all connections managed by it. /// </summary> public void Close() { Console.WriteLine("Closing chat manager"); opened = false; while(participants.Count > 0) { Participant participant = (Participant)participants[0]; participants.RemoveAt(0); participant.Close(); } } /// <summary> /// Gets or sets the local profile. Whenever this is set, the new profile will be /// sent to all participants. /// </summary> public Profile Profile { get { return profile; } set { profile = value; SendProfile(); } } /// <summary> /// Returns a list of all participants connected to this device. /// </summary> public Participant[] Participants { get { return (Participant[])participants.ToArray(typeof(Participant)); } } /// <summary> /// Adds a participant to the network. /// </summary> /// <param name="participant">The participant to add.</param> public void AddParticipant(Participant participant) { lock(this) { // This is the only negogation we have. Should be sufficient. // foreach(Participant other in participants) { if(other.Address.Equals(participant.Address)) { participant.Close(); return; } } Console.WriteLine("Adding participant '" + participant.Profile.Name + "'"); participants.Add(participant); participant.MessageReceived += new MessageReceivedHandler(participant_MessageReceived); participant.ProfileChanged += new ProfileChangedHandler(participant_ProfileChanged); participant.Lost += new ParticipantLostHandler(participant_Lost); participant.SendProfile(profile); } } /// <summary> /// Sends the local profile to all participants. /// </summary> public void SendProfile() { foreach(Participant participant in participants) { Console.WriteLine("Sending profile to " + participant.Profile.Name); participant.SendProfile(profile); } } /// <summary> /// Sets a message to all participants. /// </summary> /// <param name="message">The message to send.</param> public void SendMessage(String message) { foreach(Participant participant in participants) { participant.SendMessage(message); } } #region Events private void participant_MessageReceived(Participant participant, String message) { if(MessageReceived != null) { MessageReceived(participant, message); } } private void participant_ProfileChanged(Participant participant) { if(ProfileChanged != null) { ProfileChanged(participant); } } private void chatService_ParticipantConnected(Participant participant) { AddParticipant(participant); } private void network_DeviceDiscovered(object sender, BlueToolsEventArgs eventArgs) { RemoteDevice device = (RemoteDevice)((DiscoveryEventArgs)eventArgs).Discovery; device.ServiceDiscovered += new BlueToolsEventHandler(device_ServiceDiscovered); try { device.DiscoverServicesAsync(ServiceType.RFCOMM); } catch (Exception exc) { System.Windows.Forms.MessageBox.Show(exc.Message); } // Perhaps do this in discovery complete? } private void network_DeviceLost(object sender, BlueToolsEventArgs eventArgs) { RemoteDevice device = (RemoteDevice)((DiscoveryEventArgs)eventArgs).Discovery; device.ServiceDiscovered -= new BlueToolsEventHandler(device_ServiceDiscovered); } private void device_ServiceDiscovered(object sender, BlueToolsEventArgs eventArgs) { Device device = (Device)sender; RemoteService service = (RemoteService)((DiscoveryEventArgs)eventArgs).Discovery; Console.WriteLine("Discovered service " + service.Name + " of device " + device.Name); if(service.Name == "Chat Service") { // Check if we're already connected to the device AddParticipant(new Participant(device.Address, service.Stream)); } } private void participant_Lost(Participant participant) { participants.Remove(participant); participant.MessageReceived -= new MessageReceivedHandler(participant_MessageReceived); participant.ProfileChanged -= new ProfileChangedHandler(participant_ProfileChanged); participant.Lost -= new ParticipantLostHandler(participant_Lost); } #endregion private void network_DeviceDiscoveryStarted(object sender, BlueToolsEventArgs eventArgs) { Console.WriteLine("Looking for devices..."); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** ** ** Purpose: Domains represent an application within the runtime. Objects can ** not be shared between domains and each domain can be configured ** independently. ** ** =============================================================================*/ namespace System { using System; using System.Reflection; using System.Runtime; using System.Runtime.CompilerServices; using System.Security; using System.Security.Policy; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Reflection.Emit; using CultureInfo = System.Globalization.CultureInfo; using System.IO; using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm; using System.Text; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; public class ResolveEventArgs : EventArgs { private String _Name; private Assembly _RequestingAssembly; public String Name { get { return _Name; } } public Assembly RequestingAssembly { get { return _RequestingAssembly; } } public ResolveEventArgs(String name) { _Name = name; } public ResolveEventArgs(String name, Assembly requestingAssembly) { _Name = name; _RequestingAssembly = requestingAssembly; } } public class AssemblyLoadEventArgs : EventArgs { private Assembly _LoadedAssembly; public Assembly LoadedAssembly { get { return _LoadedAssembly; } } public AssemblyLoadEventArgs(Assembly loadedAssembly) { _LoadedAssembly = loadedAssembly; } } [Serializable] public delegate Assembly ResolveEventHandler(Object sender, ResolveEventArgs args); [Serializable] public delegate void AssemblyLoadEventHandler(Object sender, AssemblyLoadEventArgs args); [Serializable] internal delegate void AppDomainInitializer(string[] args); internal class AppDomainInitializerInfo { internal class ItemInfo { public string TargetTypeAssembly; public string TargetTypeName; public string MethodName; } internal ItemInfo[] Info; internal AppDomainInitializerInfo(AppDomainInitializer init) { Info = null; if (init == null) return; List<ItemInfo> itemInfo = new List<ItemInfo>(); List<AppDomainInitializer> nestedDelegates = new List<AppDomainInitializer>(); nestedDelegates.Add(init); int idx = 0; while (nestedDelegates.Count > idx) { AppDomainInitializer curr = nestedDelegates[idx++]; Delegate[] list = curr.GetInvocationList(); for (int i = 0; i < list.Length; i++) { if (!list[i].Method.IsStatic) { if (list[i].Target == null) continue; AppDomainInitializer nested = list[i].Target as AppDomainInitializer; if (nested != null) nestedDelegates.Add(nested); else throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStatic"), list[i].Method.ReflectedType.FullName + "::" + list[i].Method.Name); } else { ItemInfo info = new ItemInfo(); info.TargetTypeAssembly = list[i].Method.ReflectedType.Module.Assembly.FullName; info.TargetTypeName = list[i].Method.ReflectedType.FullName; info.MethodName = list[i].Method.Name; itemInfo.Add(info); } } } Info = itemInfo.ToArray(); } internal AppDomainInitializer Unwrap() { if (Info == null) return null; AppDomainInitializer retVal = null; for (int i = 0; i < Info.Length; i++) { Assembly assembly = Assembly.Load(Info[i].TargetTypeAssembly); AppDomainInitializer newVal = (AppDomainInitializer)Delegate.CreateDelegate(typeof(AppDomainInitializer), assembly.GetType(Info[i].TargetTypeName), Info[i].MethodName); if (retVal == null) retVal = newVal; else retVal += newVal; } return retVal; } } internal sealed class AppDomain { // Domain security information // These fields initialized from the other side only. (NOTE: order // of these fields cannot be changed without changing the layout in // the EE- AppDomainBaseObject in this case) private AppDomainManager _domainManager; private Dictionary<String, Object> _LocalStore; private AppDomainSetup _FusionStore; private Evidence _SecurityIdentity; #pragma warning disable 169 private Object[] _Policies; // Called from the VM. #pragma warning restore 169 public event AssemblyLoadEventHandler AssemblyLoad; private ResolveEventHandler _TypeResolve; public event ResolveEventHandler TypeResolve { add { lock (this) { _TypeResolve += value; } } remove { lock (this) { _TypeResolve -= value; } } } private ResolveEventHandler _ResourceResolve; public event ResolveEventHandler ResourceResolve { add { lock (this) { _ResourceResolve += value; } } remove { lock (this) { _ResourceResolve -= value; } } } private ResolveEventHandler _AssemblyResolve; public event ResolveEventHandler AssemblyResolve { add { lock (this) { _AssemblyResolve += value; } } remove { lock (this) { _AssemblyResolve -= value; } } } private ApplicationTrust _applicationTrust; private EventHandler _processExit; private EventHandler _domainUnload; private UnhandledExceptionEventHandler _unhandledException; // The compat flags are set at domain creation time to indicate that the given breaking // changes (named in the strings) should not be used in this domain. We only use the // keys, the vhe values are ignored. private Dictionary<String, object> _compatFlags; // Delegate that will hold references to FirstChance exception notifications private EventHandler<FirstChanceExceptionEventArgs> _firstChanceException; private IntPtr _pDomain; // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM. private bool _HasSetPolicy; private bool _IsFastFullTrustDomain; // quick check to see if the AppDomain is fully trusted and homogenous private bool _compatFlagsInitialized; internal const String TargetFrameworkNameAppCompatSetting = "TargetFrameworkName"; #if FEATURE_APPX private static APPX_FLAGS s_flags; // // Keep in async with vm\appdomainnative.cpp // [Flags] private enum APPX_FLAGS { APPX_FLAGS_INITIALIZED = 0x01, APPX_FLAGS_APPX_MODEL = 0x02, APPX_FLAGS_APPX_DESIGN_MODE = 0x04, APPX_FLAGS_APPX_NGEN = 0x08, APPX_FLAGS_APPX_MASK = APPX_FLAGS_APPX_MODEL | APPX_FLAGS_APPX_DESIGN_MODE | APPX_FLAGS_APPX_NGEN, APPX_FLAGS_API_CHECK = 0x10, } private static APPX_FLAGS Flags { get { if (s_flags == 0) s_flags = nGetAppXFlags(); Debug.Assert(s_flags != 0); return s_flags; } } internal static bool ProfileAPICheck { get { return (Flags & APPX_FLAGS.APPX_FLAGS_API_CHECK) != 0; } } internal static bool IsAppXNGen { get { return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_NGEN) != 0; } } #endif // FEATURE_APPX [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DisableFusionUpdatesFromADManager(AppDomainHandle domain); #if FEATURE_APPX [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] private static extern APPX_FLAGS nGetAppXFlags(); #endif [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetAppDomainManagerType(AppDomainHandle domain, StringHandleOnStack retAssembly, StringHandleOnStack retType); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void SetAppDomainManagerType(AppDomainHandle domain, string assembly, string type); [SuppressUnmanagedCodeSecurity] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void SetSecurityHomogeneousFlag(AppDomainHandle domain, [MarshalAs(UnmanagedType.Bool)] bool runtimeSuppliedHomogenousGrantSet); /// <summary> /// Get a handle used to make a call into the VM pointing to this domain /// </summary> internal AppDomainHandle GetNativeHandle() { // This should never happen under normal circumstances. However, there ar ways to create an // uninitialized object through remoting, etc. if (_pDomain.IsNull()) { throw new InvalidOperationException(Environment.GetResourceString("Argument_InvalidHandle")); } return new AppDomainHandle(_pDomain); } /// <summary> /// If this AppDomain is configured to have an AppDomain manager then create the instance of it. /// This method is also called from the VM to create the domain manager in the default domain. /// </summary> private void CreateAppDomainManager() { Debug.Assert(_domainManager == null, "_domainManager == null"); AppDomainSetup adSetup = FusionStore; String trustedPlatformAssemblies = (String)(GetData("TRUSTED_PLATFORM_ASSEMBLIES")); if (trustedPlatformAssemblies != null) { String platformResourceRoots = (String)(GetData("PLATFORM_RESOURCE_ROOTS")); if (platformResourceRoots == null) { platformResourceRoots = String.Empty; } String appPaths = (String)(GetData("APP_PATHS")); if (appPaths == null) { appPaths = String.Empty; } String appNiPaths = (String)(GetData("APP_NI_PATHS")); if (appNiPaths == null) { appNiPaths = String.Empty; } String appLocalWinMD = (String)(GetData("APP_LOCAL_WINMETADATA")); if (appLocalWinMD == null) { appLocalWinMD = String.Empty; } SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths, appLocalWinMD); } string domainManagerAssembly; string domainManagerType; GetAppDomainManagerType(out domainManagerAssembly, out domainManagerType); if (domainManagerAssembly != null && domainManagerType != null) { try { _domainManager = CreateInstanceAndUnwrap(domainManagerAssembly, domainManagerType) as AppDomainManager; } catch (FileNotFoundException e) { throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e); } catch (SecurityException e) { throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e); } catch (TypeLoadException e) { throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e); } if (_domainManager == null) { throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager")); } // If this domain was not created by a managed call to CreateDomain, then the AppDomainSetup // will not have the correct values for the AppDomainManager set. FusionStore.AppDomainManagerAssembly = domainManagerAssembly; FusionStore.AppDomainManagerType = domainManagerType; bool notifyFusion = _domainManager.GetType() != typeof(System.AppDomainManager) && !DisableFusionUpdatesFromADManager(); AppDomainSetup FusionStoreOld = null; if (notifyFusion) FusionStoreOld = new AppDomainSetup(FusionStore, true); // Initialize the AppDomainMAnager and register the instance with the native host if requested _domainManager.InitializeNewDomain(FusionStore); if (notifyFusion) SetupFusionStore(_FusionStore, FusionStoreOld); // Notify Fusion about the changes the user implementation of InitializeNewDomain may have made to the FusionStore object. } InitializeCompatibilityFlags(); } /// <summary> /// Initialize the compatibility flags to non-NULL values. /// This method is also called from the VM when the default domain dosen't have a domain manager. /// </summary> private void InitializeCompatibilityFlags() { AppDomainSetup adSetup = FusionStore; // set up shim flags regardless of whether we create a DomainManager in this method. if (adSetup.GetCompatibilityFlags() != null) { _compatFlags = new Dictionary<String, object>(adSetup.GetCompatibilityFlags(), StringComparer.OrdinalIgnoreCase); } // for perf, we don't intialize the _compatFlags dictionary when we don't need to. However, we do need to make a // note that we've run this method, because IsCompatibilityFlagsSet needs to return different values for the // case where the compat flags have been setup. Debug.Assert(!_compatFlagsInitialized); _compatFlagsInitialized = true; CompatibilitySwitches.InitializeSwitches(); } /// <summary> /// Returns the setting of the corresponding compatibility config switch (see CreateAppDomainManager for the impact). /// </summary> internal bool DisableFusionUpdatesFromADManager() { return DisableFusionUpdatesFromADManager(GetNativeHandle()); } /// <summary> /// Returns whether the current AppDomain follows the AppX rules. /// </summary> [Pure] internal static bool IsAppXModel() { #if FEATURE_APPX return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_MODEL) != 0; #else return false; #endif } /// <summary> /// Returns the setting of the AppXDevMode config switch. /// </summary> [Pure] internal static bool IsAppXDesignMode() { #if FEATURE_APPX return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_MASK) == (APPX_FLAGS.APPX_FLAGS_APPX_MODEL | APPX_FLAGS.APPX_FLAGS_APPX_DESIGN_MODE); #else return false; #endif } /// <summary> /// Checks (and throws on failure) if the domain supports Assembly.LoadFrom. /// </summary> [Pure] internal static void CheckLoadFromSupported() { #if FEATURE_APPX if (IsAppXModel()) throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFrom")); #endif } /// <summary> /// Checks (and throws on failure) if the domain supports Assembly.LoadFile. /// </summary> [Pure] internal static void CheckLoadFileSupported() { #if FEATURE_APPX if (IsAppXModel()) throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFile")); #endif } /// <summary> /// Checks (and throws on failure) if the domain supports Assembly.ReflectionOnlyLoad. /// </summary> [Pure] internal static void CheckReflectionOnlyLoadSupported() { #if FEATURE_APPX if (IsAppXModel()) throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.ReflectionOnlyLoad")); #endif } /// <summary> /// Checks (and throws on failure) if the domain supports Assembly.Load(byte[] ...). /// </summary> [Pure] internal static void CheckLoadByteArraySupported() { #if FEATURE_APPX if (IsAppXModel()) throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.Load(byte[], ...)")); #endif } /// <summary> /// Get the name of the assembly and type that act as the AppDomainManager for this domain /// </summary> internal void GetAppDomainManagerType(out string assembly, out string type) { // We can't just use our parameters because we need to ensure that the strings used for hte QCall // are on the stack. string localAssembly = null; string localType = null; GetAppDomainManagerType(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref localAssembly), JitHelpers.GetStringHandleOnStack(ref localType)); assembly = localAssembly; type = localType; } /// <summary> /// Set the assembly and type which act as the AppDomainManager for this domain /// </summary> private void SetAppDomainManagerType(string assembly, string type) { Debug.Assert(assembly != null, "assembly != null"); Debug.Assert(type != null, "type != null"); SetAppDomainManagerType(GetNativeHandle(), assembly, type); } /// <summary> /// Called for every AppDomain (including the default domain) to initialize the security of the AppDomain) /// </summary> private void InitializeDomainSecurity(Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, bool generateDefaultEvidence, IntPtr parentSecurityDescriptor, bool publishAppDomain) { AppDomainSetup adSetup = FusionStore; bool runtimeSuppliedHomogenousGrant = false; ApplicationTrust appTrust = adSetup.ApplicationTrust; if (appTrust != null) { SetupDomainSecurityForHomogeneousDomain(appTrust, runtimeSuppliedHomogenousGrant); } else if (_IsFastFullTrustDomain) { SetSecurityHomogeneousFlag(GetNativeHandle(), runtimeSuppliedHomogenousGrant); } // Get the evidence supplied for the domain. If no evidence was supplied, it means that we want // to use the default evidence creation strategy for this domain Evidence newAppDomainEvidence = (providedSecurityInfo != null ? providedSecurityInfo : creatorsSecurityInfo); if (newAppDomainEvidence == null && generateDefaultEvidence) { newAppDomainEvidence = new Evidence(); } // Set the evidence on the managed side _SecurityIdentity = newAppDomainEvidence; // Set the evidence of the AppDomain in the VM. // Also, now that the initialization is complete, signal that to the security system. // Finish the AppDomain initialization and resolve the policy for the AppDomain evidence. SetupDomainSecurity(newAppDomainEvidence, parentSecurityDescriptor, publishAppDomain); } private void SetupDomainSecurityForHomogeneousDomain(ApplicationTrust appTrust, bool runtimeSuppliedHomogenousGrantSet) { // If the CLR has supplied the homogenous grant set (that is, this domain would have been // heterogenous in v2.0), then we need to strip the ApplicationTrust from the AppDomainSetup of // the current domain. This prevents code which does: // AppDomain.CreateDomain(..., AppDomain.CurrentDomain.SetupInformation); // // From looking like it is trying to create a homogenous domain intentionally, and therefore // having its evidence check bypassed. if (runtimeSuppliedHomogenousGrantSet) { BCLDebug.Assert(_FusionStore.ApplicationTrust != null, "Expected to find runtime supplied ApplicationTrust"); } _applicationTrust = appTrust; // Set the homogeneous bit in the VM's ApplicationSecurityDescriptor. SetSecurityHomogeneousFlag(GetNativeHandle(), runtimeSuppliedHomogenousGrantSet); } public AppDomainManager DomainManager { get { return _domainManager; } } public ObjectHandle CreateInstance(String assemblyName, String typeName) { // jit does not check for that, so we should do it ... if (this == null) throw new NullReferenceException(); if (assemblyName == null) throw new ArgumentNullException(nameof(assemblyName)); Contract.EndContractBlock(); return Activator.CreateInstance(assemblyName, typeName); } public static AppDomain CurrentDomain { get { Contract.Ensures(Contract.Result<AppDomain>() != null); return Thread.GetDomain(); } } public String BaseDirectory { get { return FusionStore.ApplicationBase; } } public override String ToString() { StringBuilder sb = StringBuilderCache.Acquire(); String fn = nGetFriendlyName(); if (fn != null) { sb.Append(Environment.GetResourceString("Loader_Name") + fn); sb.Append(Environment.NewLine); } if (_Policies == null || _Policies.Length == 0) sb.Append(Environment.GetResourceString("Loader_NoContextPolicies") + Environment.NewLine); else { sb.Append(Environment.GetResourceString("Loader_ContextPolicies") + Environment.NewLine); for (int i = 0; i < _Policies.Length; i++) { sb.Append(_Policies[i]); sb.Append(Environment.NewLine); } } return StringBuilderCache.GetStringAndRelease(sb); } // this is true when we've removed the handles etc so really can't do anything [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern bool IsUnloadingForcedFinalize(); // this is true when we've just started going through the finalizers and are forcing objects to finalize // so must be aware that certain infrastructure may have gone away [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern bool IsFinalizingForUnload(); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void PublishAnonymouslyHostedDynamicMethodsAssembly(RuntimeAssembly assemblyHandle); public void SetData(string name, object data) { if (name == null) throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); // SetData should only be used to set values that don't already exist. object currentVal; lock (((ICollection)LocalStore).SyncRoot) { LocalStore.TryGetValue(name, out currentVal); } if (currentVal != null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyOnce")); } lock (((ICollection)LocalStore).SyncRoot) { LocalStore[name] = data; } } [Pure] public Object GetData(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); int key = AppDomainSetup.Locate(name); if (key == -1) { if (name.Equals(AppDomainSetup.LoaderOptimizationKey)) return FusionStore.LoaderOptimization; else { object data; lock (((ICollection)LocalStore).SyncRoot) { LocalStore.TryGetValue(name, out data); } if (data == null) return null; return data; } } else { // Be sure to call these properties, not Value, so // that the appropriate permission demand will be done switch (key) { case (int)AppDomainSetup.LoaderInformation.ApplicationBaseValue: return FusionStore.ApplicationBase; case (int)AppDomainSetup.LoaderInformation.ApplicationNameValue: return FusionStore.ApplicationName; default: Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()"); return null; } } } [Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. http://go.microsoft.com/fwlink/?linkid=14202", false)] [DllImport(Microsoft.Win32.Win32Native.KERNEL32)] public static extern int GetCurrentThreadId(); private AppDomain() { throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor)); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern void nCreateContext(); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void nSetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD); internal void SetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD) { nSetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPath, appNiPaths, appLocalWinMD); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern String nGetFriendlyName(); // support reliability for certain event handlers, if the target // methods also participate in this discipline. If caller passes // an existing MulticastDelegate, then we could use a MDA to indicate // that reliability is not guaranteed. But if it is a single cast // scenario, we can make it work. public event EventHandler ProcessExit { add { if (value != null) { RuntimeHelpers.PrepareContractedDelegate(value); lock (this) _processExit += value; } } remove { lock (this) _processExit -= value; } } public event EventHandler DomainUnload { add { if (value != null) { RuntimeHelpers.PrepareContractedDelegate(value); lock (this) _domainUnload += value; } } remove { lock (this) _domainUnload -= value; } } public event UnhandledExceptionEventHandler UnhandledException { add { if (value != null) { RuntimeHelpers.PrepareContractedDelegate(value); lock (this) _unhandledException += value; } } remove { lock (this) _unhandledException -= value; } } // This is the event managed code can wireup against to be notified // about first chance exceptions. // // To register/unregister the callback, the code must be SecurityCritical. public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException { add { if (value != null) { RuntimeHelpers.PrepareContractedDelegate(value); lock (this) _firstChanceException += value; } } remove { lock (this) _firstChanceException -= value; } } private void OnAssemblyLoadEvent(RuntimeAssembly LoadedAssembly) { AssemblyLoadEventHandler eventHandler = AssemblyLoad; if (eventHandler != null) { AssemblyLoadEventArgs ea = new AssemblyLoadEventArgs(LoadedAssembly); eventHandler(this, ea); } } // This method is called by the VM. private RuntimeAssembly OnResourceResolveEvent(RuntimeAssembly assembly, String resourceName) { ResolveEventHandler eventHandler = _ResourceResolve; if (eventHandler == null) return null; Delegate[] ds = eventHandler.GetInvocationList(); int len = ds.Length; for (int i = 0; i < len; i++) { Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(resourceName, assembly)); RuntimeAssembly ret = GetRuntimeAssembly(asm); if (ret != null) return ret; } return null; } // This method is called by the VM private RuntimeAssembly OnTypeResolveEvent(RuntimeAssembly assembly, String typeName) { ResolveEventHandler eventHandler = _TypeResolve; if (eventHandler == null) return null; Delegate[] ds = eventHandler.GetInvocationList(); int len = ds.Length; for (int i = 0; i < len; i++) { Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(typeName, assembly)); RuntimeAssembly ret = GetRuntimeAssembly(asm); if (ret != null) return ret; } return null; } // This method is called by the VM. private RuntimeAssembly OnAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName) { ResolveEventHandler eventHandler = _AssemblyResolve; if (eventHandler == null) { return null; } Delegate[] ds = eventHandler.GetInvocationList(); int len = ds.Length; for (int i = 0; i < len; i++) { Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(assemblyFullName, assembly)); RuntimeAssembly ret = GetRuntimeAssembly(asm); if (ret != null) return ret; } return null; } #if FEATURE_COMINTEROP // Called by VM - code:CLRPrivTypeCacheWinRT::RaiseDesignerNamespaceResolveEvent private string[] OnDesignerNamespaceResolveEvent(string namespaceName) { return System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.OnDesignerNamespaceResolveEvent(this, namespaceName); } #endif // FEATURE_COMINTEROP internal AppDomainSetup FusionStore { get { Debug.Assert(_FusionStore != null, "Fusion store has not been correctly setup in this domain"); return _FusionStore; } } internal static RuntimeAssembly GetRuntimeAssembly(Assembly asm) { if (asm == null) return null; RuntimeAssembly rtAssembly = asm as RuntimeAssembly; if (rtAssembly != null) return rtAssembly; AssemblyBuilder ab = asm as AssemblyBuilder; if (ab != null) return ab.InternalAssembly; return null; } private Dictionary<String, Object> LocalStore { get { if (_LocalStore != null) return _LocalStore; else { _LocalStore = new Dictionary<String, Object>(); return _LocalStore; } } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void nSetNativeDllSearchDirectories(string paths); private void SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo) { Contract.Requires(info != null); if (info.ApplicationBase == null) { info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized: true); } nCreateContext(); if (info.LoaderOptimization != LoaderOptimization.NotSpecified || (oldInfo != null && info.LoaderOptimization != oldInfo.LoaderOptimization)) UpdateLoaderOptimization(info.LoaderOptimization); // This must be the last action taken _FusionStore = info; } private static void RunInitializer(AppDomainSetup setup) { if (setup.AppDomainInitializer != null) { string[] args = null; if (setup.AppDomainInitializerArguments != null) args = (string[])setup.AppDomainInitializerArguments.Clone(); setup.AppDomainInitializer(args); } } // Used to switch into other AppDomain and call SetupRemoteDomain. // We cannot simply call through the proxy, because if there // are any remoting sinks registered, they can add non-mscorlib // objects to the message (causing an assembly load exception when // we try to deserialize it on the other side) private static object PrepareDataForSetup(String friendlyName, AppDomainSetup setup, Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, IntPtr parentSecurityDescriptor, string sandboxName, string[] propertyNames, string[] propertyValues) { byte[] serializedEvidence = null; bool generateDefaultEvidence = false; AppDomainInitializerInfo initializerInfo = null; if (setup != null && setup.AppDomainInitializer != null) initializerInfo = new AppDomainInitializerInfo(setup.AppDomainInitializer); // will travel x-Ad, drop non-agile data AppDomainSetup newSetup = new AppDomainSetup(setup, false); // Remove the special AppDomainCompatSwitch entries from the set of name value pairs // And add them to the AppDomainSetup // // This is only supported on CoreCLR through ICLRRuntimeHost2.CreateAppDomainWithManager // Desktop code should use System.AppDomain.CreateDomain() or // System.AppDomainManager.CreateDomain() and add the flags to the AppDomainSetup List<String> compatList = new List<String>(); if (propertyNames != null && propertyValues != null) { for (int i = 0; i < propertyNames.Length; i++) { if (String.Compare(propertyNames[i], "AppDomainCompatSwitch", StringComparison.OrdinalIgnoreCase) == 0) { compatList.Add(propertyValues[i]); propertyNames[i] = null; propertyValues[i] = null; } } if (compatList.Count > 0) { newSetup.SetCompatibilitySwitches(compatList); } } return new Object[] { friendlyName, newSetup, parentSecurityDescriptor, generateDefaultEvidence, serializedEvidence, initializerInfo, sandboxName, propertyNames, propertyValues }; } // PrepareDataForSetup private static Object Setup(Object arg) { Contract.Requires(arg != null && arg is Object[]); Contract.Requires(((Object[])arg).Length >= 8); Object[] args = (Object[])arg; String friendlyName = (String)args[0]; AppDomainSetup setup = (AppDomainSetup)args[1]; IntPtr parentSecurityDescriptor = (IntPtr)args[2]; bool generateDefaultEvidence = (bool)args[3]; byte[] serializedEvidence = (byte[])args[4]; AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[5]; string sandboxName = (string)args[6]; string[] propertyNames = (string[])args[7]; // can contain null elements string[] propertyValues = (string[])args[8]; // can contain null elements // extract evidence Evidence providedSecurityInfo = null; Evidence creatorsSecurityInfo = null; AppDomain ad = AppDomain.CurrentDomain; AppDomainSetup newSetup = new AppDomainSetup(setup, false); if (propertyNames != null && propertyValues != null) { for (int i = 0; i < propertyNames.Length; i++) { // We want to set native dll probing directories before any P/Invokes have a // chance to fire. The Path class, for one, has P/Invokes. if (propertyNames[i] == "NATIVE_DLL_SEARCH_DIRECTORIES") { if (propertyValues[i] == null) throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES"); string paths = propertyValues[i]; if (paths.Length == 0) break; nSetNativeDllSearchDirectories(paths); } } for (int i = 0; i < propertyNames.Length; i++) { if (propertyNames[i] == "APPBASE") // make sure in sync with Fusion { if (propertyValues[i] == null) throw new ArgumentNullException("APPBASE"); if (PathInternal.IsPartiallyQualified(propertyValues[i])) throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired")); newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true); } else if (propertyNames[i] == "LOADER_OPTIMIZATION") { if (propertyValues[i] == null) throw new ArgumentNullException("LOADER_OPTIMIZATION"); switch (propertyValues[i]) { case "SingleDomain": newSetup.LoaderOptimization = LoaderOptimization.SingleDomain; break; case "MultiDomain": newSetup.LoaderOptimization = LoaderOptimization.MultiDomain; break; case "MultiDomainHost": newSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost; break; case "NotSpecified": newSetup.LoaderOptimization = LoaderOptimization.NotSpecified; break; default: throw new ArgumentException(Environment.GetResourceString("Argument_UnrecognizedLoaderOptimization"), "LOADER_OPTIMIZATION"); } } else if (propertyNames[i] == "TRUSTED_PLATFORM_ASSEMBLIES" || propertyNames[i] == "PLATFORM_RESOURCE_ROOTS" || propertyNames[i] == "APP_PATHS" || propertyNames[i] == "APP_NI_PATHS") { string values = propertyValues[i]; if (values == null) throw new ArgumentNullException(propertyNames[i]); ad.SetData(propertyNames[i], NormalizeAppPaths(values)); } else if (propertyNames[i] != null) { ad.SetData(propertyNames[i], propertyValues[i]); // just propagate } } } ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup // technically, we don't need this, newSetup refers to the same object as FusionStore // but it's confusing since it isn't immediately obvious whether we have a ref or a copy AppDomainSetup adSetup = ad.FusionStore; adSetup.InternalSetApplicationTrust(sandboxName); // set up the friendly name ad.nSetupFriendlyName(friendlyName); #if FEATURE_COMINTEROP if (setup != null && setup.SandboxInterop) { ad.nSetDisableInterfaceCache(); } #endif // FEATURE_COMINTEROP // set up the AppDomainManager for this domain and initialize security. if (adSetup.AppDomainManagerAssembly != null && adSetup.AppDomainManagerType != null) { ad.SetAppDomainManagerType(adSetup.AppDomainManagerAssembly, adSetup.AppDomainManagerType); } ad.CreateAppDomainManager(); // could modify FusionStore's object ad.InitializeDomainSecurity(providedSecurityInfo, creatorsSecurityInfo, generateDefaultEvidence, parentSecurityDescriptor, true); // can load user code now if (initializerInfo != null) adSetup.AppDomainInitializer = initializerInfo.Unwrap(); RunInitializer(adSetup); return null; } private static string NormalizeAppPaths(string values) { int estimatedLength = values.Length + 1; // +1 for extra separator temporarily added at end StringBuilder sb = StringBuilderCache.Acquire(estimatedLength); for (int pos = 0; pos < values.Length; pos++) { string path; int nextPos = values.IndexOf(Path.PathSeparator, pos); if (nextPos == -1) { path = values.Substring(pos); pos = values.Length - 1; } else { path = values.Substring(pos, nextPos - pos); pos = nextPos; } // Skip empty directories if (path.Length == 0) continue; if (PathInternal.IsPartiallyQualified(path)) throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired")); string appPath = NormalizePath(path, fullCheck: true); sb.Append(appPath); sb.Append(Path.PathSeparator); } // Strip the last separator if (sb.Length > 0) { sb.Remove(sb.Length - 1, 1); } return StringBuilderCache.GetStringAndRelease(sb); } internal static string NormalizePath(string path, bool fullCheck) { return Path.GetFullPath(path); } // This routine is called from unmanaged code to // set the default fusion context. private void SetupDomain(bool allowRedirects, String path, String configFile, String[] propertyNames, String[] propertyValues) { // It is possible that we could have multiple threads initializing // the default domain. We will just take the winner of these two. // (eg. one thread doing a com call and another doing attach for IJW) lock (this) { if (_FusionStore == null) { AppDomainSetup setup = new AppDomainSetup(); // always use internet permission set setup.InternalSetApplicationTrust("Internet"); SetupFusionStore(setup, null); } } } private void SetupDomainSecurity(Evidence appDomainEvidence, IntPtr creatorsSecurityDescriptor, bool publishAppDomain) { Evidence stackEvidence = appDomainEvidence; SetupDomainSecurity(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref stackEvidence), creatorsSecurityDescriptor, publishAppDomain); } [SuppressUnmanagedCodeSecurity] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void SetupDomainSecurity(AppDomainHandle appDomain, ObjectHandleOnStack appDomainEvidence, IntPtr creatorsSecurityDescriptor, [MarshalAs(UnmanagedType.Bool)] bool publishAppDomain); [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern void nSetupFriendlyName(string friendlyName); #if FEATURE_COMINTEROP [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern void nSetDisableInterfaceCache(); #endif // FEATURE_COMINTEROP [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern void UpdateLoaderOptimization(LoaderOptimization optimization); public AppDomainSetup SetupInformation { get { return new AppDomainSetup(FusionStore, true); } } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern String IsStringInterned(String str); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern String GetOrInternString(String str); [SuppressUnmanagedCodeSecurity] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetGrantSet(AppDomainHandle domain, ObjectHandleOnStack retGrantSet); public bool IsFullyTrusted { get { return true; } } public Object CreateInstanceAndUnwrap(String assemblyName, String typeName) { ObjectHandle oh = CreateInstance(assemblyName, typeName); if (oh == null) return null; return oh.Unwrap(); } // CreateInstanceAndUnwrap public Int32 Id { get { return GetId(); } } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern Int32 GetId(); } /// <summary> /// Handle used to marshal an AppDomain to the VM (eg QCall). When marshaled via a QCall, the target /// method in the VM will recieve a QCall::AppDomainHandle parameter. /// </summary> internal struct AppDomainHandle { private IntPtr m_appDomainHandle; // Note: generall an AppDomainHandle should not be directly constructed, instead the // code:System.AppDomain.GetNativeHandle method should be called to get the handle for a specific // AppDomain. internal AppDomainHandle(IntPtr domainHandle) { m_appDomainHandle = domainHandle; } } }
// Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol { using Microsoft.Rest.Azure; using Models; /// <summary> /// JobOperations operations. /// </summary> public partial interface IJobOperations { /// <summary> /// Gets lifetime summary statistics for all of the jobs in the /// specified account. /// </summary> /// <remarks> /// Statistics are aggregated across all jobs that have ever existed /// in the account, from account creation to the last update time of /// the statistics. /// </remarks> /// <param name='jobGetAllJobsLifetimeStatisticsOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<JobStatistics,JobGetAllJobsLifetimeStatisticsHeaders>> GetAllJobsLifetimeStatisticsWithHttpMessagesAsync(JobGetAllJobsLifetimeStatisticsOptions jobGetAllJobsLifetimeStatisticsOptions = default(JobGetAllJobsLifetimeStatisticsOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a job. /// </summary> /// <param name='jobId'> /// The id of the job to delete. /// </param> /// <param name='jobDeleteOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobDeleteHeaders>> DeleteWithHttpMessagesAsync(string jobId, JobDeleteOptions jobDeleteOptions = default(JobDeleteOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets information about the specified job. /// </summary> /// <param name='jobId'> /// The id of the job. /// </param> /// <param name='jobGetOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CloudJob,JobGetHeaders>> GetWithHttpMessagesAsync(string jobId, JobGetOptions jobGetOptions = default(JobGetOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Updates the properties of a job. /// </summary> /// <param name='jobId'> /// The id of the job whose properties you want to update. /// </param> /// <param name='jobPatchParameter'> /// The parameters for the request. /// </param> /// <param name='jobPatchOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobPatchHeaders>> PatchWithHttpMessagesAsync(string jobId, JobPatchParameter jobPatchParameter, JobPatchOptions jobPatchOptions = default(JobPatchOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Updates the properties of a job. /// </summary> /// <param name='jobId'> /// The id of the job whose properties you want to update. /// </param> /// <param name='jobUpdateParameter'> /// The parameters for the request. /// </param> /// <param name='jobUpdateOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobUpdateHeaders>> UpdateWithHttpMessagesAsync(string jobId, JobUpdateParameter jobUpdateParameter, JobUpdateOptions jobUpdateOptions = default(JobUpdateOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Disables the specified job, preventing new tasks from running. /// </summary> /// <param name='jobId'> /// The id of the job to disable. /// </param> /// <param name='disableTasks'> /// What to do with active tasks associated with the job. Possible /// values include: 'requeue', 'terminate', 'wait' /// </param> /// <param name='jobDisableOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobDisableHeaders>> DisableWithHttpMessagesAsync(string jobId, DisableJobOption disableTasks, JobDisableOptions jobDisableOptions = default(JobDisableOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Enables the specified job, allowing new tasks to run. /// </summary> /// <param name='jobId'> /// The id of the job to enable. /// </param> /// <param name='jobEnableOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobEnableHeaders>> EnableWithHttpMessagesAsync(string jobId, JobEnableOptions jobEnableOptions = default(JobEnableOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Terminates the specified job, marking it as completed. /// </summary> /// <param name='jobId'> /// The id of the job to terminate. /// </param> /// <param name='terminateReason'> /// The text you want to appear as the job's TerminateReason. The /// default is 'UserTerminate'. /// </param> /// <param name='jobTerminateOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobTerminateHeaders>> TerminateWithHttpMessagesAsync(string jobId, string terminateReason = default(string), JobTerminateOptions jobTerminateOptions = default(JobTerminateOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Adds a job to the specified account. /// </summary> /// <param name='job'> /// The job to be added. /// </param> /// <param name='jobAddOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobAddHeaders>> AddWithHttpMessagesAsync(JobAddParameter job, JobAddOptions jobAddOptions = default(JobAddOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all of the jobs in the specified account. /// </summary> /// <param name='jobListOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListHeaders>> ListWithHttpMessagesAsync(JobListOptions jobListOptions = default(JobListOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the jobs that have been created under the specified job /// schedule. /// </summary> /// <param name='jobScheduleId'> /// The id of the job schedule from which you want to get a list of /// jobs. /// </param> /// <param name='jobListFromJobScheduleOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListFromJobScheduleHeaders>> ListFromJobScheduleWithHttpMessagesAsync(string jobScheduleId, JobListFromJobScheduleOptions jobListFromJobScheduleOptions = default(JobListFromJobScheduleOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the execution status of the Job Preparation and Job Release /// task for the specified job across the compute nodes where the job /// has run. /// </summary> /// <param name='jobId'> /// The id of the job. /// </param> /// <param name='jobListPreparationAndReleaseTaskStatusOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<JobPreparationAndReleaseTaskExecutionInformation>,JobListPreparationAndReleaseTaskStatusHeaders>> ListPreparationAndReleaseTaskStatusWithHttpMessagesAsync(string jobId, JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions = default(JobListPreparationAndReleaseTaskStatusOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all of the jobs in the specified account. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='jobListNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, JobListNextOptions jobListNextOptions = default(JobListNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the jobs that have been created under the specified job /// schedule. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='jobListFromJobScheduleNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListFromJobScheduleHeaders>> ListFromJobScheduleNextWithHttpMessagesAsync(string nextPageLink, JobListFromJobScheduleNextOptions jobListFromJobScheduleNextOptions = default(JobListFromJobScheduleNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the execution status of the Job Preparation and Job Release /// task for the specified job across the compute nodes where the job /// has run. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='jobListPreparationAndReleaseTaskStatusNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<JobPreparationAndReleaseTaskExecutionInformation>,JobListPreparationAndReleaseTaskStatusHeaders>> ListPreparationAndReleaseTaskStatusNextWithHttpMessagesAsync(string nextPageLink, JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = default(JobListPreparationAndReleaseTaskStatusNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MyHelp.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
//----------------------------------------------------------------------- // <copyright file="BindableBase.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>This class implements INotifyPropertyChanged</summary> //----------------------------------------------------------------------- using System; using System.ComponentModel; namespace Csla.Core { /// <summary> /// This class implements INotifyPropertyChanged /// and INotifyPropertyChanging in a /// serialization-safe manner. /// </summary> [Serializable()] public abstract class BindableBase : MobileObject, INotifyPropertyChanged, INotifyPropertyChanging { /// <summary> /// Creates an instance of the type. /// </summary> protected BindableBase() { } [NonSerialized()] private PropertyChangedEventHandler _nonSerializableChangedHandlers; private PropertyChangedEventHandler _serializableChangedHandlers; /// <summary> /// Implements a serialization-safe PropertyChanged event. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public event PropertyChangedEventHandler PropertyChanged { add { if (ShouldHandlerSerialize(value)) _serializableChangedHandlers = (PropertyChangedEventHandler) System.Delegate.Combine(_serializableChangedHandlers, value); else _nonSerializableChangedHandlers = (PropertyChangedEventHandler) System.Delegate.Combine(_nonSerializableChangedHandlers, value); } remove { if (ShouldHandlerSerialize(value)) _serializableChangedHandlers = (PropertyChangedEventHandler) System.Delegate.Remove(_serializableChangedHandlers, value); else _nonSerializableChangedHandlers = (PropertyChangedEventHandler) System.Delegate.Remove(_nonSerializableChangedHandlers, value); } } /// <summary> /// Override this method to change the default logic for determining /// if the event handler should be serialized /// </summary> /// <param name="value">the event handler to review</param> /// <returns></returns> protected virtual bool ShouldHandlerSerialize(PropertyChangedEventHandler value) { return value.Method.IsPublic && value.Method.DeclaringType != null && (value.Method.DeclaringType.IsSerializable || value.Method.IsStatic); } /// <summary> /// Call this method to raise the PropertyChanged event /// for a specific property. /// </summary> /// <param name="propertyName">Name of the property that /// has changed.</param> /// <remarks> /// This method may be called by properties in the business /// class to indicate the change in a specific property. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnPropertyChanged(string propertyName) { if (_nonSerializableChangedHandlers != null) _nonSerializableChangedHandlers.Invoke(this, new PropertyChangedEventArgs(propertyName)); if (_serializableChangedHandlers != null) _serializableChangedHandlers.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Call this method to raise the PropertyChanged event /// for a MetaData (IsXYZ) property /// </summary> /// <param name="propertyName">Name of the property that /// has changed.</param> /// <remarks> /// This method may be called by properties in the business /// class to indicate the change in a specific property. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnMetaPropertyChanged(string propertyName) { if (_nonSerializableChangedHandlers != null) _nonSerializableChangedHandlers.Invoke(this, new MetaPropertyChangedEventArgs(propertyName)); if (_serializableChangedHandlers != null) _serializableChangedHandlers.Invoke(this, new MetaPropertyChangedEventArgs(propertyName)); } /// <summary> /// Call this method to raise the PropertyChanged event /// for a specific property. /// </summary> /// <param name="propertyInfo">PropertyInfo of the property that /// has changed.</param> /// <remarks> /// This method may be called by properties in the business /// class to indicate the change in a specific property. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnPropertyChanged(IPropertyInfo propertyInfo) { OnPropertyChanged(propertyInfo.Name); } /// <summary> /// Call this method to raise the PropertyChanged event /// for all object properties. /// </summary> /// <remarks> /// This method is for backward compatibility with /// CSLA .NET 1.x. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnIsDirtyChanged() { OnUnknownPropertyChanged(); } /// <summary> /// Call this method to raise the PropertyChanged event /// for all object properties. /// </summary> /// <remarks> /// This method is automatically called by MarkDirty. It /// actually raises PropertyChanged for an empty string, /// which tells data binding to refresh all properties. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnUnknownPropertyChanged() { OnPropertyChanged(string.Empty); } [NonSerialized()] private PropertyChangingEventHandler _nonSerializableChangingHandlers; private PropertyChangingEventHandler _serializableChangingHandlers; /// <summary> /// Implements a serialization-safe PropertyChanging event. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public event PropertyChangingEventHandler PropertyChanging { add { if (ShouldHandlerSerialize(value)) _serializableChangingHandlers = (PropertyChangingEventHandler) System.Delegate.Combine(_serializableChangingHandlers, value); else _nonSerializableChangingHandlers = (PropertyChangingEventHandler) System.Delegate.Combine(_nonSerializableChangingHandlers, value); } remove { if (ShouldHandlerSerialize(value)) _serializableChangingHandlers = (PropertyChangingEventHandler) System.Delegate.Remove(_serializableChangingHandlers, value); else _nonSerializableChangingHandlers = (PropertyChangingEventHandler) System.Delegate.Remove(_nonSerializableChangingHandlers, value); } } /// <summary> /// Call this method to raise the PropertyChanging event /// for all object properties. /// </summary> /// <remarks> /// This method is for backward compatibility with /// CSLA .NET 1.x. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnIsDirtyChanging() { OnUnknownPropertyChanging(); } /// <summary> /// Call this method to raise the PropertyChanging event /// for all object properties. /// </summary> /// <remarks> /// This method is automatically called by MarkDirty. It /// actually raises PropertyChanging for an empty string, /// which tells data binding to refresh all properties. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnUnknownPropertyChanging() { OnPropertyChanging(string.Empty); } /// <summary> /// Call this method to raise the PropertyChanging event /// for a specific property. /// </summary> /// <param name="propertyName">Name of the property that /// has Changing.</param> /// <remarks> /// This method may be called by properties in the business /// class to indicate the change in a specific property. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnPropertyChanging(string propertyName) { if (_nonSerializableChangingHandlers != null) _nonSerializableChangingHandlers.Invoke(this, new PropertyChangingEventArgs(propertyName)); if (_serializableChangingHandlers != null) _serializableChangingHandlers.Invoke(this, new PropertyChangingEventArgs(propertyName)); } /// <summary> /// Call this method to raise the PropertyChanging event /// for a specific property. /// </summary> /// <param name="propertyInfo">PropertyInfo of the property that /// has Changing.</param> /// <remarks> /// This method may be called by properties in the business /// class to indicate the change in a specific property. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnPropertyChanging(IPropertyInfo propertyInfo) { OnPropertyChanging(propertyInfo.Name); } /// <summary> /// Override this method to change the default logic for determining /// if the event handler should be serialized /// </summary> /// <param name="value">the event handler to review</param> /// <returns></returns> protected virtual bool ShouldHandlerSerialize(PropertyChangingEventHandler value) { return value.Method.IsPublic && value.Method.DeclaringType != null && (value.Method.DeclaringType.IsSerializable || value.Method.IsStatic); } } }
using System; using System.Collections.Generic; using Mono.Unix.Native; namespace Manos.IO.Libev { internal class FileStream : FragmentStream<ByteBuffer>, IByteStream { private readonly bool canRead; private readonly bool canWrite; private readonly byte[] readBuffer; private long position; private bool readEnabled, writeEnabled; private FileStream(Context context, IntPtr handle, int blockSize, bool canRead, bool canWrite) : base(context) { Handle = handle; readBuffer = new byte[blockSize]; this.canRead = canRead; this.canWrite = canWrite; } public new Context Context { get { return (Context) base.Context; } } public IntPtr Handle { get; private set; } #region IByteStream Members public override long Position { get { return position; } set { SeekTo(value); } } public override bool CanRead { get { return canRead; } } public override bool CanWrite { get { return canWrite; } } public override bool CanSeek { get { return true; } } public override void SeekBy(long delta) { if (position + delta < 0) throw new ArgumentException("delta"); position += delta; } public override void SeekTo(long position) { if (position < 0) throw new ArgumentException("position"); this.position = position; } public override void Flush() { } public override void Write(IEnumerable<ByteBuffer> data) { base.Write(data); ResumeWriting(); } public void Write(byte[] data) { CheckDisposed(); Write(new ByteBuffer(data)); } public override IDisposable Read(Action<ByteBuffer> onData, Action<Exception> onError, Action onClose) { IDisposable result = base.Read(onData, onError, onClose); ResumeReading(); return result; } public override void ResumeReading() { CheckDisposed(); if (!canRead) throw new InvalidOperationException(); if (!readEnabled) { readEnabled = true; ReadNextBuffer(); } } public override void ResumeWriting() { CheckDisposed(); if (!canWrite) throw new InvalidOperationException(); if (!writeEnabled) { writeEnabled = true; HandleWrite(); } } public override void PauseReading() { CheckDisposed(); readEnabled = false; } public override void PauseWriting() { CheckDisposed(); writeEnabled = false; } #endregion protected override void Dispose(bool disposing) { if (Handle != IntPtr.Zero) { Syscall.close(Handle.ToInt32()); Handle = IntPtr.Zero; } base.Dispose(disposing); } private void ReadNextBuffer() { if (!readEnabled) { return; } Context.Eio.Read(Handle.ToInt32(), readBuffer, position, readBuffer.Length, OnReadDone); } private void OnReadDone(int result, byte[] buffer, int error) { if (result < 0) { PauseReading(); RaiseError(new IOException(string.Format("Error reading from file: {0}", Errors.ErrorToString(error)))); } else if (result > 0) { position += result; var newBuffer = new byte[result]; Buffer.BlockCopy(readBuffer, 0, newBuffer, 0, result); RaiseData(new ByteBuffer(newBuffer)); ReadNextBuffer(); } else { PauseReading(); RaiseEndOfStream(); } } protected override void HandleWrite() { if (writeEnabled) { base.HandleWrite(); } } protected override WriteResult WriteSingleFragment(ByteBuffer buffer) { byte[] bytes = buffer.Bytes; if (buffer.Position > 0) { bytes = new byte[buffer.Length]; Array.Copy(buffer.Bytes, buffer.Position, bytes, 0, buffer.Length); } Context.Eio.Write(Handle.ToInt32(), bytes, position, buffer.Length, OnWriteDone); return WriteResult.Consume; } private void OnWriteDone(int result, int error) { if (result < 0) { RaiseError(new IOException(string.Format("Error writing to file: {0}", Errors.ErrorToString(error)))); } else { position += result; HandleWrite(); } } protected override long FragmentSize(ByteBuffer fragment) { return fragment.Length; } public static FileStream Open(Context context, string fileName, int blockSize, OpenFlags openFlags) { int fd = Syscall.open(fileName, openFlags, FilePermissions.S_IRUSR | FilePermissions.S_IWUSR | FilePermissions.S_IROTH); OpenFlags mask = OpenFlags.O_RDONLY | OpenFlags.O_RDWR | OpenFlags.O_WRONLY; bool canRead = (openFlags & mask) == OpenFlags.O_RDONLY || (openFlags & mask) == OpenFlags.O_RDWR; bool canWrite = (openFlags & mask) == OpenFlags.O_WRONLY || (openFlags & mask) == OpenFlags.O_RDWR; return new FileStream(context, new IntPtr(fd), blockSize, canRead, canWrite); } public static FileStream Create(Context context, string fileName, int blockSize) { return Open(context, fileName, blockSize, OpenFlags.O_RDWR | OpenFlags.O_CREAT | OpenFlags.O_TRUNC); } } }
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf.Logging { using System; using System.Globalization; using Elmah; using Topshelf.Logging; public class ElmahLogLevels { public bool IsDebugEnabled { get; set; } public bool IsInfoEnabled { get; set; } public bool IsWarnEnabled { get; set; } public bool IsErrorEnabled { get; set; } public bool IsFatalEnabled { get; set; } } public enum ElmahLogLevelsEnum { Debug, Info, Warn, Error, Fatal } public class ElmahLogWriter : LogWriter { private readonly ErrorLog _log; private readonly ElmahLogLevels _logLevels; public ElmahLogWriter() : this(ErrorLog.GetDefault(null), null) { } public ElmahLogWriter(ElmahLogLevels logLevels) : this(ErrorLog.GetDefault(null), logLevels) { } public ElmahLogWriter(ErrorLog log, ElmahLogLevels logLevels) { _log = log; _logLevels = logLevels ?? new ElmahLogLevels() { IsDebugEnabled = true, IsErrorEnabled = true, IsFatalEnabled = true, IsInfoEnabled = true, IsWarnEnabled = true }; } private void WriteToElmah(ElmahLogLevelsEnum logLevel, LogWriterOutputProvider messageProvider) { WriteToElmah(logLevel, messageProvider().ToString()); } private void WriteToElmah(ElmahLogLevelsEnum logLevel, string format, params object[] args) { WriteToElmah(logLevel, String.Format(format, args)); } private void WriteToElmah(ElmahLogLevelsEnum logLevel, string message, Exception exception = null) { var error = exception == null ? new Error() : new Error(exception); var type = error.Exception != null ? error.Exception.GetType().FullName : GetLogLevel(logLevel); error.Type = type; error.Message = message; error.Time = DateTime.Now; error.HostName = Environment.MachineName; error.Detail = exception == null ? message : exception.StackTrace; if(IsLogLevelEnabled(logLevel)) _log.Log(error); } private string GetLogLevel(ElmahLogLevelsEnum logLevel) { switch (logLevel) { case ElmahLogLevelsEnum.Debug: return "Debug"; case ElmahLogLevelsEnum.Info: return "Info"; case ElmahLogLevelsEnum.Warn: return "Warn"; case ElmahLogLevelsEnum.Error: return "Error"; case ElmahLogLevelsEnum.Fatal: return "Fatal"; } return "unknown log level"; } public void Debug(object message) { WriteToElmah(ElmahLogLevelsEnum.Debug, message.ToString()); } public void Debug(object message, Exception exception) { WriteToElmah(ElmahLogLevelsEnum.Debug, message.ToString(), exception); } public void Debug(LogWriterOutputProvider messageProvider) { if (!IsDebugEnabled) return; WriteToElmah(ElmahLogLevelsEnum.Debug, messageProvider); } public void DebugFormat(string format, params object[] args) { WriteToElmah(ElmahLogLevelsEnum.Debug, format, args); } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { WriteToElmah(ElmahLogLevelsEnum.Debug, format, args); } public void Info(object message) { WriteToElmah(ElmahLogLevelsEnum.Info, message.ToString()); } public void Info(object message, Exception exception) { WriteToElmah(ElmahLogLevelsEnum.Info, message.ToString(), exception); } public void Info(LogWriterOutputProvider messageProvider) { if (!IsInfoEnabled) return; WriteToElmah(ElmahLogLevelsEnum.Info, messageProvider); } public void InfoFormat(string format, params object[] args) { WriteToElmah(ElmahLogLevelsEnum.Info, format, args); } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { WriteToElmah(ElmahLogLevelsEnum.Info, format, args); } public void Warn(object message) { WriteToElmah(ElmahLogLevelsEnum.Warn, message.ToString()); } public void Warn(object message, Exception exception) { WriteToElmah(ElmahLogLevelsEnum.Warn, message.ToString(), exception); } public void Warn(LogWriterOutputProvider messageProvider) { if (!IsWarnEnabled) return; WriteToElmah(ElmahLogLevelsEnum.Warn, messageProvider); } public void WarnFormat(string format, params object[] args) { WriteToElmah(ElmahLogLevelsEnum.Warn, format, args); } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { WriteToElmah(ElmahLogLevelsEnum.Warn, format, args); } public void Error(object message) { WriteToElmah(ElmahLogLevelsEnum.Error, message.ToString()); } public void Error(object message, Exception exception) { WriteToElmah(ElmahLogLevelsEnum.Error, message.ToString(), exception); } public void Error(LogWriterOutputProvider messageProvider) { if (!IsErrorEnabled) return; WriteToElmah(ElmahLogLevelsEnum.Error, messageProvider); } public void ErrorFormat(string format, params object[] args) { WriteToElmah(ElmahLogLevelsEnum.Error, format, args); } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { WriteToElmah(ElmahLogLevelsEnum.Error, format, args); } public void Fatal(object message) { WriteToElmah(ElmahLogLevelsEnum.Fatal, message.ToString()); } public void Fatal(object message, Exception exception) { WriteToElmah(ElmahLogLevelsEnum.Fatal, message.ToString(), exception); } public void Fatal(LogWriterOutputProvider messageProvider) { if (!IsFatalEnabled) return; WriteToElmah(ElmahLogLevelsEnum.Fatal, messageProvider); } public void FatalFormat(string format, params object[] args) { WriteToElmah(ElmahLogLevelsEnum.Fatal, format, args); } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { WriteToElmah(ElmahLogLevelsEnum.Fatal, format, args); } private bool IsLogLevelEnabled(ElmahLogLevelsEnum logLevel) { switch (logLevel) { case ElmahLogLevelsEnum.Debug: return IsDebugEnabled; case ElmahLogLevelsEnum.Info: return IsInfoEnabled; case ElmahLogLevelsEnum.Warn: return IsWarnEnabled; case ElmahLogLevelsEnum.Error: return IsErrorEnabled; case ElmahLogLevelsEnum.Fatal: return IsFatalEnabled; } return true; } public bool IsDebugEnabled { get { return _logLevels.IsDebugEnabled; } } public bool IsInfoEnabled { get { return _logLevels.IsInfoEnabled; } } public bool IsWarnEnabled { get { return _logLevels.IsWarnEnabled; } } public bool IsErrorEnabled { get { return _logLevels.IsErrorEnabled; } } public bool IsFatalEnabled { get { return _logLevels.IsFatalEnabled; } } public void Log(LoggingLevel level, object obj) { if (level == LoggingLevel.Fatal) Fatal(obj); else if (level == LoggingLevel.Error) Error(obj); else if (level == LoggingLevel.Warn) Warn(obj); else if (level == LoggingLevel.Info) Info(obj); else if (level >= LoggingLevel.Debug) Debug(obj); } public void Log(LoggingLevel level, object obj, Exception exception) { if (level == LoggingLevel.Fatal) Fatal(obj, exception); else if (level == LoggingLevel.Error) Error(obj, exception); else if (level == LoggingLevel.Warn) Warn(obj, exception); else if (level == LoggingLevel.Info) Info(obj, exception); else if (level >= LoggingLevel.Debug) Debug(obj, exception); } public void Log(LoggingLevel level, LogWriterOutputProvider messageProvider) { if (level == LoggingLevel.Fatal) Fatal(messageProvider); else if (level == LoggingLevel.Error) Error(messageProvider); else if (level == LoggingLevel.Warn) Warn(messageProvider); else if (level == LoggingLevel.Info) Info(messageProvider); else if (level >= LoggingLevel.Debug) Debug(messageProvider); } public void LogFormat(LoggingLevel level, string format, params object[] args) { if (level == LoggingLevel.Fatal) FatalFormat(CultureInfo.InvariantCulture, format, args); else if (level == LoggingLevel.Error) ErrorFormat(CultureInfo.InvariantCulture, format, args); else if (level == LoggingLevel.Warn) WarnFormat(CultureInfo.InvariantCulture, format, args); else if (level == LoggingLevel.Info) InfoFormat(CultureInfo.InvariantCulture, format, args); else if (level >= LoggingLevel.Debug) DebugFormat(CultureInfo.InvariantCulture, format, args); } public void LogFormat(LoggingLevel level, IFormatProvider formatProvider, string format, params object[] args) { if (level == LoggingLevel.Fatal) FatalFormat(formatProvider, format, args); else if (level == LoggingLevel.Error) ErrorFormat(formatProvider, format, args); else if (level == LoggingLevel.Warn) WarnFormat(formatProvider, format, args); else if (level == LoggingLevel.Info) InfoFormat(formatProvider, format, args); else if (level >= LoggingLevel.Debug) DebugFormat(formatProvider, format, args); } } }
using System; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Collections.Generic; using Oracle.DataAccess.Client; using DbParallel.DataAccess; using DbParallel.DataAccess.Booster.Oracle; using DbParallel.DataAccess.Booster.SqlServer; namespace DataBooster.DbWebApi.DataAccess { public static partial class DbPackage { #region Initialization static DbPackage() { // DbAccess.DefaultCommandType = CommandType.StoredProcedure; } public static DbAccess CreateConnection() { return new DbAccess(ConfigHelper.DbProviderFactory, ConfigHelper.ConnectionString); } private static string GetProcedure(string sp) { return ConfigHelper.DatabasePackage + sp; } #endregion #region Usage Examples // To turn off following sample code in DEBUG mode, just add NO_SAMPLE into the project properties ... // Project Properties Dialog -> Build -> General -> Conditional Compilation Symbols. #if (DEBUG && !NO_SAMPLE) #region Some samples of using DbAccess class #region A sample of reader action public class SampleClassA { public string PropertyA { get; set; } public int PropertyB { get; set; } public decimal? PropertyC { get; set; } public SampleClassA() // => ... <T> ... where T : class, new() { PropertyA = string.Empty; PropertyB = 0; PropertyC = 0m; } public SampleClassA(string a, int b, decimal? c) { PropertyA = a; PropertyB = b; PropertyC = c; } } internal static List<SampleClassA> LoadSampleObjByAction(this DbAccess dbAccess, string area, int grpId) { const string sp = "GET_SAMPLE_OBJ"; List<SampleClassA> sampleClsList = new List<SampleClassA>(); dbAccess.ExecuteReader(GetProcedure(sp), parameters => { parameters.Add("inArea", area); parameters.Add("inGrp_Id", grpId); }, row => { sampleClsList.Add(new SampleClassA(row.Field<string>("COL_A"), row.Field<int>("COL_B"), row.Field<decimal?>("COL_C"))); }); return sampleClsList; } #endregion #region A sample of specified fields mapping public class SampleClassB { public string PropertyA { get; set; } public int PropertyB { get; set; } public decimal? PropertyC { get; set; } // public SampleClassB() { } // Implicitly or Explicitly } internal static IEnumerable<SampleClassB> LoadSampleObjByMap(this DbAccess dbAccess, string area, int grpId) { const string sp = "GET_SAMPLE_OBJ"; return dbAccess.ExecuteReader<SampleClassB>(GetProcedure(sp), parameters => { parameters.Add("inArea", area); parameters.Add("inGrp_Id", grpId); }, map => { // In order to allow Visual Studio Intellisense to be able to infer the type of map and t correctly // Please make sure that SampleClassB class has a parameterless constructor or default constructor implicitly map.Add("COL_A", t => t.PropertyA); map.Add("COL_B", t => t.PropertyB); map.Add("COL_C", t => t.PropertyC); }); } #endregion #region A sample of auto fields mapping public class SampleClassC { public string Column_Name1 { get; set; } public int Column_Name2 { get; set; } public decimal? Column_Name3 { get; set; } public bool Column_Name4 { get; set; } // public SampleClassC() { } // Implicitly or Explicitly } internal static IEnumerable<SampleClassC> LoadSampleObjAutoMap(this DbAccess dbAccess, string area, int grpId) { const string sp = "GET_SAMPLE_ITEM"; return dbAccess.ExecuteReader<SampleClassC>(GetProcedure(sp), parameters => { parameters.Add("inArea", area); parameters.Add("inGrp_Id", grpId); }); } #endregion #region A sample of Multi-ResultSets with auto/specified fields mapping internal static Tuple<List<SampleClassA>, List<SampleClassB>, List<SampleClassC>> ViewReport(this DbAccess dbAccess, DateTime date, int sessionId) { const string sp = "VIEW_REPORT"; var resultTuple = Tuple.Create(new List<SampleClassA>(), new List<SampleClassB>(), new List<SampleClassC>()); dbAccess.ExecuteMultiReader(GetProcedure(sp), parameters => { parameters.Add("inDate", date); parameters.Add("inSession", sessionId); }, resultSets => { // Specified fields mapping example resultSets.Add(resultTuple.Item1, // Put 1st ResultSet into resultTuple.Item1 colMap => { colMap.Add("COL_A", t => t.PropertyA); colMap.Add("COL_B", t => t.PropertyB); colMap.Add("COL_C", t => t.PropertyC); }); // Full-automatic (case-insensitive) fields mapping examples resultSets.Add(resultTuple.Item2); // Put 2nd ResultSet into resultTuple.Item2 resultSets.Add(resultTuple.Item3); // Put 3rd ResultSet into resultTuple.Item3 } ); return resultTuple; } #endregion #region A sample of output parameter internal static Tuple<string, int, byte> GetSampleSetting(this DbAccess dbAccess, string sampleDomain) { const string sp = "GET_SAMPLE_SETTING"; DbParameter outStartupMode = null; DbParameter outRefreshInterval = null; DbParameter outDegreeOfTaskParallelism = null; dbAccess.ExecuteNonQuery(GetProcedure(sp), parameters => { parameters.Add("inSample_Domain", sampleDomain); outStartupMode = parameters.AddOutput("outStartup_Mode", 32); outRefreshInterval = parameters.AddOutput("outRefresh_Interval", DbType.Int32); outDegreeOfTaskParallelism = parameters.AddOutput("outParallelism_Degree", DbType.Byte); }); return Tuple.Create(outStartupMode.Parameter<string>(), outRefreshInterval.Parameter<int>(), outDegreeOfTaskParallelism.Parameter<byte>()); } #endregion #region A sample of non-return public static void LogSampleError(this DbAccess dbAccess, string strReference, string strMessage) { const string sp = "LOG_SAMPLE_ERROR"; dbAccess.ExecuteNonQuery(GetProcedure(sp), parameters => { parameters.Add("inReference", strReference); parameters.Add("inMessage", strMessage); }); } #endregion #endregion #region A sample of using SqlLauncher class public static SqlLauncher CreateSampleSqlLauncher() { return new SqlLauncher(ConfigHelper.AuxConnectionString, "schema.DestBigTable", /* (Optional) * If the data source and the destination table have the same number of columns, * and the ordinal position of each source column within the data source matches the ordinal position * of the corresponding destination column, the ColumnMappings collection is unnecessary. * However, if the column counts differ, or the ordinal positions are not consistent, * you must use ColumnMappings to make sure that data is copied into the correct columns. * (this remark is excerpted from MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.columnmappings.aspx, * please see also http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopycolumnmappingcollection.aspx) */ columnMappings => { columnMappings.Add(/* 0, */"ProdID"); columnMappings.Add(/* 1, */"ProdName"); columnMappings.Add(/* 2, */"ProdPrice"); } ); } public static void AddSampleSqlRow(this SqlLauncher launcher, int col0, string col1, decimal col2) { launcher.Post(col0, col1, col2); } #endregion #region A sample of using OracleLauncher class public static OracleLauncher CreateSampleOraLauncher(int grpId) { return new OracleLauncher(ConfigHelper.ConnectionString, GetProcedure("WRITE_BULK_DATA"), parameters => { parameters.Add("inGroup_ID", grpId); // Ordinary parameter // All Array Bind Types must be explicitly specified and must match PL/SQL table row types defined in database side parameters.AddAssociativeArray("inItem_IDs", OracleDbType.Int32); parameters.AddAssociativeArray("inItem_Values", OracleDbType.BinaryDouble); }); } public static void AddSampleOraRow(this OracleLauncher launcher, int itemId, double itemValue) { launcher.Post(itemId, itemValue); } // The database side package: // CREATE OR REPLACE PACKAGE SCHEMA.PACKAGE IS // TYPE NUMBER_ARRAY IS TABLE OF NUMBER INDEX BY PLS_INTEGER; // TYPE DOUBLE_ARRAY IS TABLE OF BINARY_DOUBLE INDEX BY PLS_INTEGER; // -- ... // PROCEDURE WRITE_BULK_DATA // ( // inGroup_ID NUMBER, // inItem_IDs NUMBER_ARRAY, // inItem_Values DOUBLE_ARRAY // ); // -- ... // END PACKAGE; // / // CREATE OR REPLACE PACKAGE BODY SCHEMA.PACKAGE IS // -- ... // PROCEDURE WRITE_BULK_DATA // ( // inGroup_ID NUMBER, // inItem_IDs NUMBER_ARRAY, // inItem_Values DOUBLE_ARRAY // ) AS // BEGIN // FORALL i IN inItem_IDs.FIRST .. inItem_IDs.LAST // INSERT /*+ APPEND_VALUES */ INTO SCHEMA.TEST_WRITE_DATA // ( // GROUP_ID, // ITEM_ID, // ITEM_VALUE // ) // VALUES // ( // inGroup_ID, // inItem_IDs(i), // inItem_Values(i) // ); // COMMIT; // END WRITE_BULK_DATA; // -- ... // END PACKAGE; #endregion #endif #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Windows.Media; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; namespace VSConsole.PowerPack.Core { public class WpfConsoleClassifier : ObjectWithFactory<WpfConsoleService>, IClassifier { private readonly OrderedTupleSpans<IClassificationType> _colorSpans = new OrderedTupleSpans<IClassificationType>(); private readonly ComplexCommandSpans _commandLineSpans = new ComplexCommandSpans(); private WeakReference _cacheClassifications; private int _cacheCommandStartPosition; private ITextSnapshot _cacheSnapshot; private EventHandler<ClassificationChangedEventArgs> _classificationChanged; private WpfConsole _console; private ITextFormatClassifier _textFormatClassifier; public WpfConsoleClassifier(WpfConsoleService factory, ITextBuffer textBuffer) : base(factory) { TextBuffer = textBuffer; TextBuffer.Changed += TextBuffer_Changed; } private ITextBuffer TextBuffer { get; set; } private ICommandTokenizer CommandTokenizer { get; set; } private WpfConsole Console { get { if (_console == null) { TextBuffer.Properties.TryGetProperty(typeof (IConsole), out _console); if (_console != null) { CommandTokenizer = Factory.GetCommandTokenizer(_console); if (CommandTokenizer != null) _console.Dispatcher.ExecuteInputLine += Console_ExecuteInputLine; _console.NewColorSpan += Console_NewColorSpan; _console.ConsoleCleared += Console_ConsoleCleared; } } return _console; } } private ITextFormatClassifier TextFormatClassifier { get { if (_textFormatClassifier == null) _textFormatClassifier = Factory.TextFormatClassifierProvider.GetTextFormatClassifier(Console.WpfTextView); return _textFormatClassifier; } } private bool HasConsole { get { return Console != null; } } public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged { add { EventHandler<ClassificationChangedEventArgs> eventHandler = _classificationChanged; EventHandler<ClassificationChangedEventArgs> comparand; do { comparand = eventHandler; eventHandler = Interlocked.CompareExchange(ref _classificationChanged, comparand + value, comparand); } while (eventHandler != comparand); } remove { EventHandler<ClassificationChangedEventArgs> eventHandler = _classificationChanged; EventHandler<ClassificationChangedEventArgs> comparand; do { comparand = eventHandler; eventHandler = Interlocked.CompareExchange(ref _classificationChanged, comparand - value, comparand); } while (eventHandler != comparand); } } public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span) { var list = new List<ClassificationSpan>(); if (HasConsole) { ITextSnapshot snapshot = span.Snapshot; if (CommandTokenizer != null) { bool hasValue = Console.InputLineStart.HasValue; if (hasValue) _commandLineSpans.Add(Console.InputLineExtent, false); try { foreach (var cmdSpans in _commandLineSpans.Overlap(span)) { if (cmdSpans.Count > 0) list.AddRange(GetCommandLineClassifications(snapshot, cmdSpans)); } } finally { if (hasValue) _commandLineSpans.PopLast(); } } foreach (var tuple in _colorSpans.Overlap(span)) list.Add(new ClassificationSpan(new SnapshotSpan(snapshot, tuple.Item1), tuple.Item2)); } return list; } private void TextBuffer_Changed(object sender, TextContentChangedEventArgs e) { if (!HasConsole || !Console.InputLineStart.HasValue) return; SnapshotSpan commandExtent = Console.InputLineExtent; if (!e.Changes.Any(c => c.OldPosition >= commandExtent.Span.Start)) return; if (_commandLineSpans.Count > 0) { int commandStart = _commandLineSpans.FindCommandStart(_commandLineSpans.Count - 1); commandExtent = new SnapshotSpan( new SnapshotPoint(commandExtent.Snapshot, _commandLineSpans[commandStart].Item1.Start), commandExtent.End); } _classificationChanged.Raise(this, new ClassificationChangedEventArgs(commandExtent)); } private void Console_ExecuteInputLine(object sender, EventArgs<Tuple<SnapshotSpan, bool>> e) { SnapshotSpan snapshotSpan = e.Arg.Item1.TranslateTo(Console.WpfTextView.TextSnapshot, SpanTrackingMode.EdgePositive); if (snapshotSpan.IsEmpty) return; _commandLineSpans.Add(snapshotSpan, e.Arg.Item2); } private void Console_NewColorSpan(object sender, EventArgs<Tuple<SnapshotSpan, Color?, Color?>> e) { if (!e.Arg.Item2.HasValue && !e.Arg.Item3.HasValue) return; _colorSpans.Add(Tuple.Create(e.Arg.Item1.Span, TextFormatClassifier.GetClassificationType(e.Arg.Item2, e.Arg.Item3))); _classificationChanged.Raise(this, new ClassificationChangedEventArgs(e.Arg.Item1)); } private void Console_ConsoleCleared(object sender, EventArgs e) { ClearCachedCommandLineClassifications(); _commandLineSpans.Clear(); _colorSpans.Clear(); } private IList<ClassificationSpan> GetCommandLineClassifications(ITextSnapshot snapshot, IList<Span> cmdSpans) { IList<ClassificationSpan> cachedCommandLineClassifications; if (TryGetCachedCommandLineClassifications(snapshot, cmdSpans, out cachedCommandLineClassifications)) return cachedCommandLineClassifications; var list = new List<ClassificationSpan>(); Enumerable.Select(cmdSpans, s => new SnapshotSpan(snapshot, s)); list.AddRange(GetTokenizerClassifications(snapshot, cmdSpans)); SaveCachedCommandLineClassifications(snapshot, cmdSpans, list); return list; } public IList<ClassificationSpan> GetTokenizerClassifications(ITextSnapshot snapshot, IList<Span> spans) { var list = new List<ClassificationSpan>(); string[] lines = spans.Select(span => snapshot.GetText(span)).ToArray(); try { foreach (Token token in CommandTokenizer.Tokenize(lines)) { IClassificationType typeClassification = Factory.GetTokenTypeClassification(token.Type); for (int startLine = token.StartLine; startLine <= token.EndLine; ++startLine) { if (startLine - 1 < spans.Count) { Span span = spans[startLine - 1]; int start = startLine == token.StartLine ? span.Start + (token.StartColumn - 1) : span.Start; int num = startLine == token.EndLine ? span.Start + (token.EndColumn - 1) : span.End; list.Add(new ClassificationSpan(new SnapshotSpan(snapshot, start, num - start), typeClassification)); } } } } catch (Exception ex) { } return list; } private void ClearCachedCommandLineClassifications() { _cacheSnapshot = null; _cacheClassifications = null; } private void SaveCachedCommandLineClassifications(ITextSnapshot snapshot, IList<Span> cmdSpans, IList<ClassificationSpan> spans) { _cacheSnapshot = snapshot; _cacheCommandStartPosition = cmdSpans[0].Start; _cacheClassifications = new WeakReference(spans); } private bool TryGetCachedCommandLineClassifications(ITextSnapshot snapshot, IList<Span> cmdSpans, out IList<ClassificationSpan> cachedCommandLineClassifications) { if (_cacheSnapshot == snapshot && _cacheCommandStartPosition == cmdSpans[0].Start) { var list = _cacheClassifications.Target as IList<ClassificationSpan>; if (list != null) { cachedCommandLineClassifications = list; return true; } ClearCachedCommandLineClassifications(); } cachedCommandLineClassifications = null; return false; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace SL.WebApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
//--------------------------------------------------------------------------- // // File: EditingCoordinator.cs // // Description: // Coordinates editing for InkCanvas // Features: // // History: // 4/29/2003 waynezen: Rewrote for mid-stroke support // 3/15/2003 samgeo: Created // // Copyright (C) 2003 by Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Security; using System.Security.Permissions; using System.Windows.Ink; using System.Windows.Input; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Interop; using System.Windows.Navigation; using System.Windows.Media; using MS.Utility; namespace MS.Internal.Ink { /// <summary> /// Internal class that represents the editing stack of InkCanvas /// Please see the design detain at http://tabletpc/longhorn/Specs/Mid-Stroke%20and%20Pen%20Cursor%20Dev%20Design.mht /// </summary> internal class EditingCoordinator { //------------------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------------------- #region Constructors /// <summary> /// Constructors /// </summary> /// <param name="inkCanvas">InkCanvas instance</param> internal EditingCoordinator(InkCanvas inkCanvas) { if (inkCanvas == null) { throw new ArgumentNullException("inkCanvas"); } _inkCanvas = inkCanvas; // Create a stack for tracking the behavior _activationStack = new Stack<EditingBehavior>(2); // NTRAID#WINDOWS-1104477-2005/02/26-waynezen, // listen to in-air move so that we could get notified when Stylus is inverted. // _inkCanvas.AddHandler(Stylus.StylusInRangeEvent, new StylusEventHandler(OnInkCanvasStylusInAirOrInRangeMove)); _inkCanvas.AddHandler(Stylus.StylusInAirMoveEvent, new StylusEventHandler(OnInkCanvasStylusInAirOrInRangeMove)); _inkCanvas.AddHandler(Stylus.StylusOutOfRangeEvent, new StylusEventHandler(OnInkCanvasStylusOutOfRange)); } #endregion Constructors //------------------------------------------------------------------------------- // // Internal Methods // //------------------------------------------------------------------------------- #region Internal Methods /// <summary> /// Activate a dynamic behavior /// Called from: /// SelectionEditor.OnCanvasMouseMove /// </summary> /// <param name="dynamicBehavior"></param> /// <param name="inputDevice"></param> /// <SecurityNote> /// Critical: Calls critical methods AddStylusPoints and InitializeCapture /// </SecurityNote> [SecurityCritical] internal void ActivateDynamicBehavior(EditingBehavior dynamicBehavior, InputDevice inputDevice) { // Only SelectionEditor should be enable to initiate dynamic behavior Debug.Assert(ActiveEditingBehavior == SelectionEditor, "Only SelectionEditor should be able to initiate dynamic behavior"); DebugCheckDynamicBehavior(dynamicBehavior); // Push the dynamic behavior. PushEditingBehavior(dynamicBehavior); // If this is LassoSelectionBehavior, we should capture the current stylus and feed the cached if ( dynamicBehavior == LassoSelectionBehavior ) { bool fSucceeded = false; // The below code might call out StrokeErasing or StrokeErased event. // The out-side code could throw exception. // We use try/finally block to protect our status. try { //we pass true for userInitiated because we've simply consulted the InputDevice //(and only StylusDevice or MouseDevice) for the current position of the device InitializeCapture(inputDevice, (IStylusEditing)dynamicBehavior, true /*userInitiated*/, false/*Don't reset the RTI*/); fSucceeded = true; } finally { if ( !fSucceeded ) { // Abort the current editing. ActiveEditingBehavior.Commit(false); // Release capture and do clean-up. ReleaseCapture(true); } } } _inkCanvas.RaiseActiveEditingModeChanged(new RoutedEventArgs(InkCanvas.ActiveEditingModeChangedEvent, _inkCanvas)); } /// <summary> /// Deactivate a dynamic behavior /// Called from: /// EditingBehavior.Commit /// </summary> internal void DeactivateDynamicBehavior() { // Make sure we are under correct state: // ActiveEditingBehavior has to be either LassoSelectionBehavior or SelectionEditingBehavior. DebugCheckDynamicBehavior(ActiveEditingBehavior); // Pop the dynamic behavior. PopEditingBehavior(); } /// <summary> /// Update the current active EditingMode /// Called from: /// EditingCoordinator.UpdateInvertedState /// InkCanvas.Initialize() /// </summary> internal void UpdateActiveEditingState() { UpdateEditingState(_stylusIsInverted); } /// <summary> /// Update the EditingMode /// Called from: /// InkCanvas.RaiseEditingModeChanged /// InkCanvas.RaiseEditingModeInvertedChanged /// </summary> /// <param name="inverted">A flage which indicates whether the new mode is for the Inverted state</param> internal void UpdateEditingState(bool inverted) { // If the mode is inactive currently, we should skip the update. if ( inverted != _stylusIsInverted ) { return; } // Get the current behavior and the new behavior. EditingBehavior currentBehavior = ActiveEditingBehavior; EditingBehavior newBehavior = GetBehavior(ActiveEditingMode); // Check whether the user is editing. if ( UserIsEditing ) { // Check if we are in the mid-stroke. if ( IsInMidStroke ) { // We are in mid-stroke now. Debug.Assert(currentBehavior is StylusEditingBehavior, "The current behavoir has to be one of StylusEditingBehaviors"); ( (StylusEditingBehavior)currentBehavior ).SwitchToMode(ActiveEditingMode); } else { if ( currentBehavior == SelectionEditingBehavior ) { // Commit the current moving/resizing behavior currentBehavior.Commit(true); } ChangeEditingBehavior(newBehavior); } } else { // Check if we are in the mid-stroke. if ( IsInMidStroke ) { // We are in mid-stroke now. Debug.Assert(currentBehavior is StylusEditingBehavior, "The current behavoir has to be one of StylusEditingBehaviors"); ( (StylusEditingBehavior)currentBehavior ).SwitchToMode(ActiveEditingMode); } else { // Make sure we are under correct state: // currentBehavior cannot be any of Dynamic Behavior. DebugCheckNonDynamicBehavior(currentBehavior); ChangeEditingBehavior(newBehavior); } } _inkCanvas.UpdateCursor(); } /// <summary> /// Update the PointEraerCursor /// Called from: /// InkCanvas.set_EraserShape /// </summary> internal void UpdatePointEraserCursor() { // We only have to update the point eraser when the active mode is EraseByPoint // In other case, EraseBehavior will update cursor properly in its OnActivate routine. if ( ActiveEditingMode == InkCanvasEditingMode.EraseByPoint ) { InvalidateBehaviorCursor(EraserBehavior); } } /// <summary> /// InvalidateTransform /// Called by: InkCanvas.OnPropertyChanged /// </summary> internal void InvalidateTransform() { // We only have to invalidate transform flags for InkCollectionBehavior and EraserBehavior for now. SetTransformValid(InkCollectionBehavior, false); SetTransformValid(EraserBehavior, false); } /// <summary> /// Invalidate the behavior cursor /// Call from: /// EditingCoordinator.UpdatePointEraserCursor /// EraserBehavior.OnActivate /// InkCollectionBehavior.OnInkCanvasDefaultDrawingAttributesReplaced /// InkCollectionBehavior.OnInkCanvasDefaultDrawingAttributesChanged /// SelectionEditingBehavior.OnActivate /// SelectionEditor.UpdateCursor(InkCanvasSelectionHandle handle) /// </summary> /// <param name="behavior">the behavior which its cursor needs to be updated.</param> internal void InvalidateBehaviorCursor(EditingBehavior behavior) { // Should never be null Debug.Assert(behavior != null); // InvalidateCursor first SetCursorValid(behavior, false); if ( !GetTransformValid(behavior) ) { behavior.UpdateTransform(); SetTransformValid(behavior, true); } // If the behavior is active, we have to update cursor right now. if ( behavior == ActiveEditingBehavior ) { _inkCanvas.UpdateCursor(); } } /// <summary> /// Check whether the cursor of the specified behavior is valid /// </summary> /// <param name="behavior">EditingBehavior</param> /// <returns>True if the cursor doesn't need to be updated</returns> internal bool IsCursorValid(EditingBehavior behavior) { return GetCursorValid(behavior); } /// <summary> /// Check whether the cursor of the specified behavior is valid /// </summary> /// <param name="behavior">EditingBehavior</param> /// <returns>True if the cursor doesn't need to be updated</returns> internal bool IsTransformValid(EditingBehavior behavior) { return GetTransformValid(behavior); } /// <summary> /// Change to another StylusEditing mode or None mode. /// </summary> /// <param name="sourceBehavior"></param> /// <param name="newMode"></param> /// <returns></returns> internal IStylusEditing ChangeStylusEditingMode(StylusEditingBehavior sourceBehavior, InkCanvasEditingMode newMode) { // NOTICE-2006/04/27-WAYNEZEN, // Before the caller invokes the method, the external event could have been fired. // The user code may interrupt the Mid-Stroke by releasing capture or switching to another mode. // So we should check if we still is under mid-stroke and the source behavior still is active. // If not, we just no-op. if ( IsInMidStroke && ( ( // We expect that either InkCollectionBehavior or EraseBehavior is active. sourceBehavior != LassoSelectionBehavior && sourceBehavior == ActiveEditingBehavior ) // Or We expect SelectionEditor is active here since // LassoSelectionBehavior will be deactivated once it gets committed. || ( sourceBehavior == LassoSelectionBehavior && SelectionEditor == ActiveEditingBehavior ) ) ) { Debug.Assert(_activationStack.Count == 1, "The behavior stack has to contain one behavior."); // Pop up the old behavior PopEditingBehavior(); // Get the new behavior EditingBehavior newBehavior = GetBehavior(ActiveEditingMode); if ( newBehavior != null ) { // Push the new behavior PushEditingBehavior(newBehavior); // If the new mode is Select, we should push the LassoSelectionBehavior now. if ( newMode == InkCanvasEditingMode.Select // NOTICE-2006/04/27-WAYNEZEN, // Make sure the newBehavior is SelectionEditor since it could be changed by the user event handling code. && newBehavior == SelectionEditor ) { PushEditingBehavior(LassoSelectionBehavior); } } else { // None-mode now. We stop collecting the packets. ReleaseCapture(true); } _inkCanvas.RaiseActiveEditingModeChanged(new RoutedEventArgs(InkCanvas.ActiveEditingModeChangedEvent, _inkCanvas)); return ActiveEditingBehavior as IStylusEditing; } else { // No-op return null; } } /// <summary> /// Debug Checker /// </summary> /// <param name="behavior"></param> [Conditional("DEBUG")] internal void DebugCheckActiveBehavior(EditingBehavior behavior) { Debug.Assert(behavior == ActiveEditingBehavior); } /// <summary> /// Debug check for the dynamic behavior /// </summary> /// <param name="behavior"></param> [Conditional("DEBUG")] private void DebugCheckDynamicBehavior(EditingBehavior behavior) { Debug.Assert(behavior == LassoSelectionBehavior || behavior == SelectionEditingBehavior, "Only LassoSelectionBehavior or SelectionEditingBehavior is dynamic behavior"); } /// <summary> /// Debug check for the non dynamic behavior /// </summary> /// <param name="behavior"></param> [Conditional("DEBUG")] private void DebugCheckNonDynamicBehavior(EditingBehavior behavior) { Debug.Assert(behavior != LassoSelectionBehavior && behavior != SelectionEditingBehavior, "behavior cannot be LassoSelectionBehavior or SelectionEditingBehavior"); } #endregion Internal Methods //------------------------------------------------------------------------------- // // Internal Properties // //------------------------------------------------------------------------------- #region Internal Properties /// <summary> /// Gets / sets whether move is enabled or note /// </summary> internal bool MoveEnabled { get { return _moveEnabled; } set { _moveEnabled = value; } } /// <summary> /// The property that indicates if the user is interacting with the current InkCanvas /// </summary> internal bool UserIsEditing { get { return _userIsEditing; } set { _userIsEditing = value; } } /// <summary> /// Helper flag that tells if we're between a preview down and an up. /// </summary> internal bool StylusOrMouseIsDown { get { bool stylusDown = false; StylusDevice stylusDevice = Stylus.CurrentStylusDevice; if (stylusDevice != null && _inkCanvas.IsStylusOver && !stylusDevice.InAir) { stylusDown = true; } bool mouseDown = (_inkCanvas.IsMouseOver && Mouse.PrimaryDevice.LeftButton == MouseButtonState.Pressed); if (stylusDown || mouseDown) { return true; } return false; } } /// <summary> /// Returns the StylusDevice to call DynamicRenderer.Reset with. Stylus or Mouse /// must be in a down state. If the down device is a Mouse, null is returned, since /// that is what DynamicRenderer.Reset expects for the Mouse. /// </summary> /// <returns></returns> internal InputDevice GetInputDeviceForReset() { Debug.Assert((_capturedStylus != null && _capturedMouse == null) || (_capturedStylus == null && _capturedMouse != null), "There must be one and at most one device being captured."); if ( _capturedStylus != null && !_capturedStylus.InAir ) { return _capturedStylus; } else if ( _capturedMouse != null && _capturedMouse.LeftButton == MouseButtonState.Pressed ) { return _capturedMouse; } return null; } /// <summary> /// Gets / sets whether resize is enabled or note /// </summary> internal bool ResizeEnabled { get { return _resizeEnabled; } set { _resizeEnabled = value; } } /// <summary> /// Lazy init access to the LassoSelectionBehavior /// </summary> /// <value></value> internal LassoSelectionBehavior LassoSelectionBehavior { get { if ( _lassoSelectionBehavior == null ) { _lassoSelectionBehavior = new LassoSelectionBehavior(this, _inkCanvas); } return _lassoSelectionBehavior; } } /// <summary> /// Lazy init access to the SelectionEditingBehavior /// </summary> /// <value></value> internal SelectionEditingBehavior SelectionEditingBehavior { get { if ( _selectionEditingBehavior == null ) { _selectionEditingBehavior = new SelectionEditingBehavior(this, _inkCanvas); } return _selectionEditingBehavior; } } /// <summary> /// Internal helper prop to indicate the active editing mode /// </summary> internal InkCanvasEditingMode ActiveEditingMode { get { if ( _stylusIsInverted ) { return _inkCanvas.EditingModeInverted; } return _inkCanvas.EditingMode; } } /// <summary> /// Lazy init access to the SelectionEditor /// </summary> /// <value></value> internal SelectionEditor SelectionEditor { get { if ( _selectionEditor == null ) { _selectionEditor = new SelectionEditor(this, _inkCanvas); } return _selectionEditor; } } /// <summary> /// Gets the mid-stroke state /// </summary> internal bool IsInMidStroke { get { return _capturedStylus != null || _capturedMouse != null; } } /// <summary> /// Returns Stylus Inverted state /// </summary> internal bool IsStylusInverted { get { return _stylusIsInverted; } } #endregion Internal Properties //------------------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------------------- #region Private Methods /// <summary> /// Retrieve the behavior instance based on the EditingMode /// </summary> /// <param name="editingMode">EditingMode</param> /// <returns></returns> private EditingBehavior GetBehavior(InkCanvasEditingMode editingMode) { EditingBehavior newBehavior; switch ( editingMode ) { case InkCanvasEditingMode.Ink: case InkCanvasEditingMode.GestureOnly: case InkCanvasEditingMode.InkAndGesture: newBehavior = InkCollectionBehavior; break; case InkCanvasEditingMode.Select: newBehavior = SelectionEditor; break; case InkCanvasEditingMode.EraseByPoint: case InkCanvasEditingMode.EraseByStroke: newBehavior = EraserBehavior; break; default: // Treat as InkCanvasEditingMode.None. Return null value newBehavior = null; break; } return newBehavior; } /// <summary> /// Pushes an EditingBehavior onto our stack, disables any current ones /// </summary> /// <param name="newEditingBehavior">The EditingBehavior to activate</param> private void PushEditingBehavior(EditingBehavior newEditingBehavior) { Debug.Assert(newEditingBehavior != null); EditingBehavior behavior = ActiveEditingBehavior; // Deactivate the previous behavior if ( behavior != null ) { behavior.Deactivate(); } // Activate the new behavior. _activationStack.Push(newEditingBehavior); newEditingBehavior.Activate(); } /// <summary> /// Pops an EditingBehavior onto our stack, disables any current ones /// </summary> private void PopEditingBehavior() { EditingBehavior behavior = ActiveEditingBehavior; if ( behavior != null ) { behavior.Deactivate(); _activationStack.Pop(); behavior = ActiveEditingBehavior; if ( ActiveEditingBehavior != null ) { behavior.Activate(); } } return; } /// <summary> /// Handles in-air stylus movements /// </summary> private void OnInkCanvasStylusInAirOrInRangeMove(object sender, StylusEventArgs args) { // If the current capture is mouse, we should reset the capture. if ( _capturedMouse != null ) { if (ActiveEditingBehavior == InkCollectionBehavior && _inkCanvas.InternalDynamicRenderer != null) { // NTRAID#WINDOWS-1378904-2005/11/17-WAYNEZEN // When InkCanvas loses the current capture, we should stop the RTI since the App thread are no longer collecting ink. // By flipping the Enabled property, the RTI will be reset. _inkCanvas.InternalDynamicRenderer.Enabled = false; _inkCanvas.InternalDynamicRenderer.Enabled = true; } // Call ActiveEditingBehavior.Commit at the end of the routine. The method will cause an external event fired. // So it should be invoked after we set up our states. ActiveEditingBehavior.Commit(true); // Release capture and do clean-up. ReleaseCapture(true); } UpdateInvertedState(args.StylusDevice, args.Inverted); } /// <summary> /// Handle StylusOutofRange event /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnInkCanvasStylusOutOfRange(object sender, StylusEventArgs args) { // Reset the inverted state once OutOfRange has been received. UpdateInvertedState(args.StylusDevice, false); } /// <summary> /// InkCanvas.StylusDown handler /// </summary> /// <param name="sender"></param> /// <param name="args"></param> /// <SecurityNote> /// Critical: /// Calls SecurityCritcal method: InitializeCapture and AddStylusPoints /// Eventually calls SecurityCritical method InkCanvas.RaiseGestureOrStrokeCollected /// /// TreatAsSafe: This method is called by the input system, from security transparent /// code, so it can not be marked critical. We check the eventArgs.UserInitiated /// to verify that the input was user initiated and pass this flag to /// InkCanvas.RaiseGestureOrStrokeCollected and use it to decide if we should /// perform gesture recognition /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal void OnInkCanvasDeviceDown(object sender, InputEventArgs args) { MouseButtonEventArgs mouseButtonEventArgs = args as MouseButtonEventArgs; bool resetDynamicRenderer = false; if ( mouseButtonEventArgs != null ) { // NTRADI:WINDOWSOS#1563896-2006/03/20-WAYNEZEN, // Note we don't mark Handled for the None EditingMode. // Set focus to InkCanvas. if ( _inkCanvas.Focus() && ActiveEditingMode != InkCanvasEditingMode.None ) { mouseButtonEventArgs.Handled = true; } // ISSUE-2005/09/20-WAYNEZEN, // We will reevaluate whether we should allow the right-button down for the modes other than the Ink mode. // Skip collecting for the non-left buttons. if ( mouseButtonEventArgs.ChangedButton != MouseButton.Left ) { return; } // NTRAID-WINDOWS#1607286-2006/04/14-WAYNEZEN, // If the mouse down event is from a Stylus, make sure we have a correct inverted state. if ( mouseButtonEventArgs.StylusDevice != null ) { UpdateInvertedState(mouseButtonEventArgs.StylusDevice, mouseButtonEventArgs.StylusDevice.Inverted); } } else { // NTRAID-WINDOWS#1395155-2005/12/15-WAYNEZEN, // When StylusDown is received, We should check the Invert state again. // If there is any change, the ActiveEditingMode will be updated. // The dynamic renderer will be reset in InkCollectionBehavior.OnActivated since the device is under down state. StylusEventArgs stylusEventArgs = args as StylusEventArgs; UpdateInvertedState(stylusEventArgs.StylusDevice, stylusEventArgs.Inverted); } // If the active behavior is not one of StylusEditingBehavior, don't even bother here. IStylusEditing stylusEditingBehavior = ActiveEditingBehavior as IStylusEditing; // We might receive StylusDown from a different device meanwhile we have already captured one. // Make sure that we are starting from a fresh state. if ( !IsInMidStroke && stylusEditingBehavior != null ) { bool fSucceeded = false; try { InputDevice capturedDevice = null; // Capture the stylus (if mouse event make sure to use stylus if generated by a stylus) if ( mouseButtonEventArgs != null && mouseButtonEventArgs.StylusDevice != null ) { capturedDevice = mouseButtonEventArgs.StylusDevice; resetDynamicRenderer = true; } else { capturedDevice = args.Device; } InitializeCapture(capturedDevice, stylusEditingBehavior, args.UserInitiated, resetDynamicRenderer); // The below code might call out StrokeErasing or StrokeErased event. // The out-side code could throw exception. // We use try/finally block to protect our status. fSucceeded = true; } finally { if ( !fSucceeded ) { // Abort the current editing. ActiveEditingBehavior.Commit(false); // Release capture and do clean-up. ReleaseCapture(IsInMidStroke); } } } } /// <summary> /// InkCanvas.StylusMove handler /// </summary> /// <param name="sender"></param> /// <param name="args"></param> /// <SecurityNote> /// Critical: /// Calls SecurityCritcal method: /// Eventually calls SecurityCritical method InkCanvas.RaiseGestureOrStrokeCollected /// /// TreatAsSafe: This method is called by the input system, from security transparent /// code, so it can not be marked critical. We check the eventArgs.UserInitiated /// to verify that the input was user initiated and pass this flag to /// InkCanvas.RaiseGestureOrStrokeCollected and use it to decide if we should /// perform gesture recognition /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void OnInkCanvasDeviceMove<TEventArgs>(object sender, TEventArgs args) where TEventArgs : InputEventArgs { // Make sure that the stylus is the one we captured previously. if ( IsInputDeviceCaptured(args.Device) ) { IStylusEditing stylusEditingBehavior = ActiveEditingBehavior as IStylusEditing; Debug.Assert(stylusEditingBehavior != null || ActiveEditingBehavior == null, "The ActiveEditingBehavior should be either null (The None mode) or type of IStylusEditing."); if ( stylusEditingBehavior != null ) { StylusPointCollection stylusPoints; if ( _capturedStylus != null ) { stylusPoints = _capturedStylus.GetStylusPoints(_inkCanvas, _commonDescription); } else { // Make sure we ignore stylus generated mouse events. MouseEventArgs mouseEventArgs = args as MouseEventArgs; if ( mouseEventArgs != null && mouseEventArgs.StylusDevice != null ) { return; } stylusPoints = new StylusPointCollection(new Point[] { _capturedMouse.GetPosition(_inkCanvas) }); } bool fSucceeded = false; // The below code might call out StrokeErasing or StrokeErased event. // The out-side code could throw exception. // We use try/finally block to protect our status. try { stylusEditingBehavior.AddStylusPoints(stylusPoints, args.UserInitiated); fSucceeded = true; } finally { if ( !fSucceeded ) { // Abort the current editing. ActiveEditingBehavior.Commit(false); // Release capture and do clean-up. ReleaseCapture(true); } } } } } /// <summary> /// InkCanvas.StylusUp handler /// </summary> /// <param name="sender"></param> /// <param name="args"></param> internal void OnInkCanvasDeviceUp(object sender, InputEventArgs args) { // Make sure that the stylus is the one we captured previously. if ( IsInputDeviceCaptured(args.Device) ) { Debug.Assert(ActiveEditingBehavior == null || ActiveEditingBehavior is IStylusEditing, "The ActiveEditingBehavior should be either null (The None mode) or type of IStylusEditing."); // Make sure we only look at mouse left button events if watching mouse events. if ( _capturedMouse != null ) { MouseButtonEventArgs mouseButtonEventArgs = args as MouseButtonEventArgs; if ( mouseButtonEventArgs != null ) { if ( mouseButtonEventArgs.ChangedButton != MouseButton.Left ) { return; } } } try { // The follow code raises variety editing events. // The out-side code could throw exception in the their handlers. We use try/finally block to protect our status. if ( ActiveEditingBehavior != null ) { // Commit the current editing. ActiveEditingBehavior.Commit(true); } } finally { // Call ReleaseCapture(true) at the end of the routine. The method will cause an external event fired. // So it should be invoked after we set up our states. ReleaseCapture(true); } } } /// <summary> /// InkCanvas.LostStylusCapture handler /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnInkCanvasLostDeviceCapture<TEventArgs>(object sender, TEventArgs args) where TEventArgs : InputEventArgs { // If user is editing, we have to commit the current operation and reset our state. if ( UserIsEditing ) { // Note ReleaseCapture(false) won't raise any external events. It only reset the internal states. ReleaseCapture(false); if ( ActiveEditingBehavior == InkCollectionBehavior && _inkCanvas.InternalDynamicRenderer != null ) { // NTRAID#WINDOWS-1378904-2005/11/17-WAYNEZEN // When InkCanvas loses the current capture, we should stop the RTI since the App thread are no longer collecting ink. // By flipping the Enabled property, the RTI will be reset. _inkCanvas.InternalDynamicRenderer.Enabled = false; _inkCanvas.InternalDynamicRenderer.Enabled = true; } // Call ActiveEditingBehavior.Commit at the end of the routine. The method will cause an external event fired. // So it should be invoked after we set up our states. ActiveEditingBehavior.Commit(true); } } /// <summary> /// Initialize the capture state /// </summary> /// <param name="inputDevice"></param> /// <param name="stylusEditingBehavior"></param> /// <param name="userInitiated"></param> /// <param name="resetDynamicRenderer"></param> /// <SecurityNote> /// Critical: Returns critical data from the inputDevice, StylusPointCollection. /// </SecurityNote> [SecurityCritical] private void InitializeCapture(InputDevice inputDevice, IStylusEditing stylusEditingBehavior, bool userInitiated, bool resetDynamicRenderer) { Debug.Assert(inputDevice != null, "A null device is passed in."); Debug.Assert(stylusEditingBehavior != null, "stylusEditingBehavior cannot be null."); Debug.Assert(!IsInMidStroke, "The previous device hasn't been released yet."); StylusPointCollection stylusPoints; _capturedStylus = inputDevice as StylusDevice; _capturedMouse = inputDevice as MouseDevice; // NOTICE-2005/09/15-WAYNEZEN, // We assume that the StylusDown always happens before the MouseDown. So, we could safely add the listeners of // XXXMove and XXXUp as the below which branchs out the coming mouse or stylus events. if ( _capturedStylus != null ) { StylusPointCollection newPoints = _capturedStylus.GetStylusPoints(_inkCanvas); _commonDescription = StylusPointDescription.GetCommonDescription(_inkCanvas.DefaultStylusPointDescription, newPoints.Description); stylusPoints = newPoints.Reformat(_commonDescription); if ( resetDynamicRenderer ) { // Reset the dynamic renderer for InkCollectionBehavior InkCollectionBehavior inkCollectionBehavior = stylusEditingBehavior as InkCollectionBehavior; if ( inkCollectionBehavior != null ) { inkCollectionBehavior.ResetDynamicRenderer(); } } stylusEditingBehavior.AddStylusPoints(stylusPoints, userInitiated); // If the current down device is stylus, we should only listen to StylusMove, StylusUp and LostStylusCapture // events. _inkCanvas.CaptureStylus(); if ( _inkCanvas.IsStylusCaptured && ActiveEditingMode != InkCanvasEditingMode.None ) { _inkCanvas.AddHandler(Stylus.StylusMoveEvent, new StylusEventHandler(OnInkCanvasDeviceMove<StylusEventArgs>)); _inkCanvas.AddHandler(UIElement.LostStylusCaptureEvent, new StylusEventHandler(OnInkCanvasLostDeviceCapture<StylusEventArgs>)); } else { _capturedStylus = null; } } else { Debug.Assert(!resetDynamicRenderer, "The dynamic renderer shouldn't be reset for Mouse"); _commonDescription = null; Point[] points = new Point[] { _capturedMouse.GetPosition(_inkCanvas) }; stylusPoints = new StylusPointCollection(points); stylusEditingBehavior.AddStylusPoints(stylusPoints, userInitiated); // NTRAID:WINDOWSOS#1536974-2006/03/02-WAYNEZEN, // CaptureMouse triggers MouseDevice.Synchronize which sends a simulated MouseMove event. // So we have to call CaptureMouse after at the end of the initialization. // Otherwise, the MouseMove handlers will be executed in the middle of the initialization. _inkCanvas.CaptureMouse(); // The user code could change mode or call release capture when the simulated Move event is received. // So we have to check the capture still is on and the mode is correct before hooking up our handlers. // If the current down device is mouse, we should only listen to MouseMove, MouseUp and LostMouseCapture // events. if ( _inkCanvas.IsMouseCaptured && ActiveEditingMode != InkCanvasEditingMode.None ) { _inkCanvas.AddHandler(Mouse.MouseMoveEvent, new MouseEventHandler(OnInkCanvasDeviceMove<MouseEventArgs>)); _inkCanvas.AddHandler(UIElement.LostMouseCaptureEvent, new MouseEventHandler(OnInkCanvasLostDeviceCapture<MouseEventArgs>)); } else { _capturedMouse = null; } } } /// <summary> /// Clean up the capture state /// </summary> /// <param name="releaseDevice"></param> private void ReleaseCapture(bool releaseDevice) { Debug.Assert(IsInMidStroke || !releaseDevice, "The captured device has been release unexpectly."); if ( _capturedStylus != null ) { // The Stylus was captured. Remove the stylus listeners. _commonDescription = null; _inkCanvas.RemoveHandler(Stylus.StylusMoveEvent, new StylusEventHandler(OnInkCanvasDeviceMove<StylusEventArgs>)); _inkCanvas.RemoveHandler(UIElement.LostStylusCaptureEvent, new StylusEventHandler(OnInkCanvasLostDeviceCapture<StylusEventArgs>)); _capturedStylus = null; if ( releaseDevice ) { // Call ReleaseStylusCapture at the end of the routine. The method will cause an external event fired. // So it should be invoked after we set up our states. _inkCanvas.ReleaseStylusCapture(); } } else if ( _capturedMouse != null ) { // The Mouse was captured. Remove the mouse listeners. _inkCanvas.RemoveHandler(Mouse.MouseMoveEvent, new MouseEventHandler(OnInkCanvasDeviceMove<MouseEventArgs>)); _inkCanvas.RemoveHandler(UIElement.LostMouseCaptureEvent, new MouseEventHandler(OnInkCanvasLostDeviceCapture<MouseEventArgs>)); _capturedMouse = null; if ( releaseDevice ) { // Call ReleaseMouseCapture at the end of the routine. The method will cause an external event fired. // So it should be invoked after we set up our states. _inkCanvas.ReleaseMouseCapture(); } } } /// <summary> /// Retrieve whether a specified device is captured by us. /// </summary> /// <param name="inputDevice"></param> /// <returns></returns> private bool IsInputDeviceCaptured(InputDevice inputDevice) { Debug.Assert(_capturedStylus == null || _capturedMouse == null, "InkCanvas cannot capture both stylus and mouse at the same time."); return (inputDevice == _capturedStylus && ((StylusDevice)inputDevice).Captured == _inkCanvas) || (inputDevice == _capturedMouse && ( (MouseDevice)inputDevice).Captured == _inkCanvas); } /// <summary> /// Return the cursor of the active behavior /// </summary> /// <returns></returns> internal Cursor GetActiveBehaviorCursor() { EditingBehavior behavior = ActiveEditingBehavior; if ( behavior == null ) { // Return the default Arrow cursor for the None mode. return Cursors.Arrow; } // Retrieve the cursor. Cursor cursor = behavior.Cursor; // Clean up the dirty flag when it's done. if ( !GetCursorValid(behavior) ) { SetCursorValid(behavior, true); } return cursor; } /// <summary> /// A private method which returns the valid flag of behaviors' cursor. /// </summary> /// <param name="behavior"></param> /// <returns></returns> private bool GetCursorValid(EditingBehavior behavior) { BehaviorValidFlag flag = GetBehaviorCursorFlag(behavior); return GetBitFlag(flag); } /// <summary> /// A private method which sets/resets the valid flag of behaviors' cursor /// </summary> /// <param name="behavior"></param> /// <param name="isValid"></param> private void SetCursorValid(EditingBehavior behavior, bool isValid) { BehaviorValidFlag flag = GetBehaviorCursorFlag(behavior); SetBitFlag(flag, isValid); } /// <summary> /// A private method which returns the valid flag of behaviors' cursor. /// </summary> /// <param name="behavior"></param> /// <returns></returns> private bool GetTransformValid(EditingBehavior behavior) { BehaviorValidFlag flag = GetBehaviorTransformFlag(behavior); return GetBitFlag(flag); } /// <summary> /// A private method which sets/resets the valid flag of behaviors' cursor /// </summary> /// <param name="behavior"></param> /// <param name="isValid"></param> private void SetTransformValid(EditingBehavior behavior, bool isValid) { BehaviorValidFlag flag = GetBehaviorTransformFlag(behavior); SetBitFlag(flag, isValid); } /// <summary> /// GetBitFlag /// </summary> /// <param name="flag"></param> /// <returns></returns> private bool GetBitFlag(BehaviorValidFlag flag) { return (_behaviorValidFlag & flag) != 0; } /// <summary> /// SetBitFlag /// </summary> /// <param name="flag"></param> /// <param name="value"></param> private void SetBitFlag(BehaviorValidFlag flag, bool value) { if ( value ) { _behaviorValidFlag |= flag; } else { _behaviorValidFlag &= (~flag); } } /// <summary> /// A helper returns behavior cursor flag from a behavior instance /// </summary> /// <param name="behavior"></param> /// <returns></returns> private BehaviorValidFlag GetBehaviorCursorFlag(EditingBehavior behavior) { BehaviorValidFlag flag = 0; if ( behavior == InkCollectionBehavior ) { flag = BehaviorValidFlag.InkCollectionBehaviorCursorValid; } else if ( behavior == EraserBehavior ) { flag = BehaviorValidFlag.EraserBehaviorCursorValid; } else if ( behavior == LassoSelectionBehavior ) { flag = BehaviorValidFlag.LassoSelectionBehaviorCursorValid; } else if ( behavior == SelectionEditingBehavior ) { flag = BehaviorValidFlag.SelectionEditingBehaviorCursorValid; } else if ( behavior == SelectionEditor ) { flag = BehaviorValidFlag.SelectionEditorCursorValid; } else { Debug.Assert(false, "Unknown behavior"); } return flag; } /// <summary> /// A helper returns behavior transform flag from a behavior instance /// </summary> /// <param name="behavior"></param> /// <returns></returns> private BehaviorValidFlag GetBehaviorTransformFlag(EditingBehavior behavior) { BehaviorValidFlag flag = 0; if ( behavior == InkCollectionBehavior ) { flag = BehaviorValidFlag.InkCollectionBehaviorTransformValid; } else if ( behavior == EraserBehavior ) { flag = BehaviorValidFlag.EraserBehaviorTransformValid; } else if ( behavior == LassoSelectionBehavior ) { flag = BehaviorValidFlag.LassoSelectionBehaviorTransformValid; } else if ( behavior == SelectionEditingBehavior ) { flag = BehaviorValidFlag.SelectionEditingBehaviorTransformValid; } else if ( behavior == SelectionEditor ) { flag = BehaviorValidFlag.SelectionEditorTransformValid; } else { Debug.Assert(false, "Unknown behavior"); } return flag; } private void ChangeEditingBehavior(EditingBehavior newBehavior) { Debug.Assert(!IsInMidStroke, "ChangeEditingBehavior cannot be called in a mid-stroke"); Debug.Assert(_activationStack.Count <= 1, "The behavior stack has to contain at most one behavior when user is not editing."); try { _inkCanvas.ClearSelection(true); } finally { if ( ActiveEditingBehavior != null ) { // Pop the old behavior. PopEditingBehavior(); } // Push the new behavior if ( newBehavior != null ) { PushEditingBehavior(newBehavior); } _inkCanvas.RaiseActiveEditingModeChanged(new RoutedEventArgs(InkCanvas.ActiveEditingModeChangedEvent, _inkCanvas)); } } /// <summary> /// Update the Inverted state /// </summary> /// <param name="stylusDevice"></param> /// <param name="stylusIsInverted"></param> /// <returns>true if the behavior is updated</returns> private bool UpdateInvertedState(StylusDevice stylusDevice, bool stylusIsInverted) { if ( !IsInMidStroke || ( IsInMidStroke && IsInputDeviceCaptured(stylusDevice) )) { if ( stylusIsInverted != _stylusIsInverted ) { _stylusIsInverted = stylusIsInverted; // // this can change editing state // UpdateActiveEditingState(); return true; } } return false; } #endregion Private Methods //------------------------------------------------------------------------------- // // Private Properties // //------------------------------------------------------------------------------- #region Private Properties /// <summary> /// Gets the top level active EditingBehavior /// </summary> /// <value></value> private EditingBehavior ActiveEditingBehavior { get { EditingBehavior EditingBehavior = null; if ( _activationStack.Count > 0 ) { EditingBehavior = _activationStack.Peek(); } return EditingBehavior; } } /// <summary> /// Lazy init access to the InkCollectionBehavior /// </summary> /// <value></value> internal InkCollectionBehavior InkCollectionBehavior { get { if ( _inkCollectionBehavior == null ) { _inkCollectionBehavior = new InkCollectionBehavior(this, _inkCanvas); } return _inkCollectionBehavior; } } /// <summary> /// Lazy init access to the EraserBehavior /// </summary> /// <value></value> private EraserBehavior EraserBehavior { get { if ( _eraserBehavior == null ) { _eraserBehavior = new EraserBehavior(this, _inkCanvas); } return _eraserBehavior; } } #endregion Private Properties //------------------------------------------------------------------------------- // // Private Enum // //------------------------------------------------------------------------------- #region Private Enum /// <summary> /// Enum values which represent the cursor valid flag for each EditingBehavior. /// </summary> [Flags] private enum BehaviorValidFlag { InkCollectionBehaviorCursorValid = 0x00000001, EraserBehaviorCursorValid = 0x00000002, LassoSelectionBehaviorCursorValid = 0x00000004, SelectionEditingBehaviorCursorValid = 0x00000008, SelectionEditorCursorValid = 0x00000010, InkCollectionBehaviorTransformValid = 0x00000020, EraserBehaviorTransformValid = 0x00000040, LassoSelectionBehaviorTransformValid = 0x00000080, SelectionEditingBehaviorTransformValid= 0x00000100, SelectionEditorTransformValid = 0x00000200, } #endregion Private Enum //------------------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------------------- #region Private Fields /// <summary> /// The InkCanvas this EditingStack is being used in /// </summary> private InkCanvas _inkCanvas; private Stack<EditingBehavior> _activationStack; private InkCollectionBehavior _inkCollectionBehavior; private EraserBehavior _eraserBehavior; private LassoSelectionBehavior _lassoSelectionBehavior; private SelectionEditingBehavior _selectionEditingBehavior; private SelectionEditor _selectionEditor; private bool _moveEnabled = true; private bool _resizeEnabled = true; private bool _userIsEditing = false; /// <summary> /// Flag that indicates if the stylus is inverted /// </summary> private bool _stylusIsInverted = false; private StylusPointDescription _commonDescription; private StylusDevice _capturedStylus; private MouseDevice _capturedMouse; // Fields related to cursor and transform. private BehaviorValidFlag _behaviorValidFlag; #endregion Private Fields } }
using System.Collections.Generic; using System.Linq; using hw.DebugFormatter; using hw.Helper; using Reni.Basics; using Reni.Code; using Reni.Context; using Reni.Feature; using Reni.SyntaxTree; using Reni.Type; using Reni.Validation; namespace Reni.Struct { sealed class Compound : DumpableObject, IContextReference, IChild<ContextBase>, ValueCache.IContainer, IRootProvider { static int NextObjectId; readonly int Order; [Node] internal readonly ContextBase Parent; [Node] internal readonly CompoundSyntax Syntax; [DisableDump] internal readonly FunctionCache<int, CompoundView> View; internal Compound(CompoundSyntax syntax, ContextBase parent) : base(NextObjectId++) { Order = Closures.NextOrder++; Syntax = syntax; Parent = parent; View = new FunctionCache<int, CompoundView> (position => new CompoundView(this, position)); StopByObjectIds(); } ContextBase IChild<ContextBase>.Parent => Parent; ValueCache ValueCache.IContainer.Cache { get; } = new ValueCache(); int IContextReference.Order => Order; Root IRootProvider.Value => Root; [DisableDump] internal TypeBase IndexType => Parent.RootContext.BitType.Number(IndexSize.ToInt()); [DisableDump] internal Root Root => Parent.RootContext; [DisableDump] internal CompoundView CompoundView => Parent.CompoundView(Syntax); Size IndexSize => Syntax.IndexSize; [DisableDump] internal IEnumerable<ResultCache> CachedResults => Syntax.EndPosition.Select(CachedResult); int EndPosition => Syntax.EndPosition; [DisableDump] public bool HasIssue => Issues.Any(); [DisableDump] public Issue[] Issues => GetIssues(); public string GetCompoundIdentificationDump() => Syntax.GetCompoundIdentificationDump(); protected override string GetNodeDump() => base.GetNodeDump() + "(" + GetCompoundIdentificationDump() + ")"; ResultCache CachedResult(int position) => Parent .CompoundPositionContext(Syntax, position) .ResultCache(Syntax.PureStatements[position]); internal Size Size(int? position = null) { if(IsHollow(position)) return Basics.Size.Zero; return ResultsOfStatements(Category.Size, fromPosition: 0, fromNotPosition: position).Size; } internal bool IsHollow(int? accessPosition = null) => ObtainIsHollow(accessPosition); internal Size FieldOffsetFromAccessPoint(int accessPosition, int fieldPosition) => ResultsOfStatements(Category.Size, fieldPosition + 1, accessPosition).Size; Result ResultsOfStatements(Category category, int fromPosition, int? fromNotPosition) { if(category.IsNone) return new Result(); var trace = Syntax.ObjectId.In() && category.HasCode; StartMethodDump(trace, category, fromPosition, fromNotPosition); try { Dump(nameof(Syntax.PureStatements), Syntax.PureStatements); BreakExecution(); var positions = ((fromNotPosition ?? EndPosition) - fromPosition) .Select(i => fromPosition + i) .Where(position => !Syntax.PureStatements[position].IsLambda) .ToArray(); var rawResults = positions .Select(position => AccessResult(category, position)) .ToArray(); var results = rawResults .Select(r => r.Align.LocalBlock(category)) .ToArray(); Dump(nameof(results), results); BreakExecution(); var result = results .Aggregate ( Parent.RootContext.VoidType.Result(category.WithType), (current, next) => current.Sequence(next) ); return ReturnMethodDump(result); } finally { EndMethodDump(); } } internal Result Result(Category category) { var trace = Syntax.ObjectId.In() && category.HasType; StartMethodDump(trace, category); try { BreakExecution(); var resultsOfStatements = ResultsOfStatements (category - Category.Type, fromPosition: 0, fromNotPosition: Syntax.EndPosition); Dump(name: "resultsOfStatements", value: resultsOfStatements); BreakExecution(); var aggregate = Syntax .EndPosition .Select() .Aggregate(resultsOfStatements, Combine); Dump(nameof(aggregate), aggregate); BreakExecution(); var resultWithCleanup = aggregate.ArrangeCleanupCode(); Dump(nameof(resultWithCleanup), resultWithCleanup); BreakExecution(); var result = resultWithCleanup .ReplaceRelative(this, CodeBase.TopRef, Closures.Void) & category; if(result.HasIssue) return ReturnMethodDump(result); if(category.HasType) result.Type = CompoundView.Type; return ReturnMethodDump(result); } finally { EndMethodDump(); } } Result Combine(Result result, int position) => Parent.CompoundView(Syntax, position).ReplaceObjectPointerByContext(result); Result AccessResult(Category category, int position) { (!Syntax.PureStatements[position].IsLambda).Assert(); return AccessResult(category, position, position); } Result AccessResult(Category category, int accessPosition, int position) { var trace = Syntax.ObjectId.In(2) && accessPosition == 4 && position == 2 && category.HasType ; StartMethodDump(trace, category, accessPosition, position); try { var uniqueChildContext = Parent.CompoundPositionContext(Syntax, accessPosition); Dump(nameof(Syntax.PureStatements), Syntax.PureStatements[position]); BreakExecution(); var rawResult = uniqueChildContext.Result (category.WithType, Syntax.PureStatements[position]); Dump(nameof(rawResult), rawResult); BreakExecution(); var unFunction = rawResult.SmartUn<FunctionType>(); Dump(nameof(unFunction), unFunction); BreakExecution(); var result = unFunction.AutomaticDereferenceResult; return ReturnMethodDump(result); } finally { EndMethodDump(); } } internal TypeBase AccessType(int accessPosition, int position) => AccessResult(Category.Type, accessPosition, position).Type; bool ObtainIsHollow(int? accessPosition) { var trace = ObjectId == -10 && accessPosition == 3 && Parent.ObjectId == 4; StartMethodDump(trace, accessPosition); try { var subStatementIds = (accessPosition ?? EndPosition).Select().ToArray(); Dump(name: "subStatementIds", value: subStatementIds); BreakExecution(); if(subStatementIds.Any(position => InnerIsHollowStatic(position) == false)) return ReturnMethodDump(rv: false); var quickNonDataLess = subStatementIds .Where(position => InnerIsHollowStatic(position) == null) .ToArray(); Dump(name: "quickNonDataLess", value: quickNonDataLess); BreakExecution(); if(quickNonDataLess.Length == 0) return ReturnMethodDump(rv: true); if(quickNonDataLess.Any (position => InternalInnerIsHollowStructureElement(position) == false)) return ReturnMethodDump(rv: false); return ReturnMethodDump(rv: true); } finally { EndMethodDump(); } } bool InternalInnerIsHollowStructureElement(int position) { var uniqueChildContext = Parent .CompoundPositionContext(Syntax, position); return Syntax .PureStatements[position] .IsHollowStructureElement(uniqueChildContext); } bool? InnerIsHollowStatic(int position) => Syntax.PureStatements[position].IsHollow; internal Result Cleanup(Category category) { var uniqueChildContext = Parent.CompoundPositionContext(Syntax); var cleanup = Syntax.Cleanup(uniqueChildContext, category); var aggregate = EndPosition .Select() .Reverse() .Select(index => GetCleanup(category, index)) .Aggregate(); return cleanup + aggregate; } Result GetCleanup(Category category, int index) { var result = AccessType(EndPosition, index).Cleanup(category); (result.CompleteCategory == category).Assert(); return result; } internal Issue[] GetIssues(int? viewPosition = null) => ResultsOfStatements(Category.Type, fromPosition: 0, fromNotPosition: viewPosition) .Issues; } }
/*============================================================================== Copyright (c) 2012 QUALCOMM Austria Research Center GmbH. All Rights Reserved. Qualcomm Confidential and Proprietary ==============================================================================*/ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using UnityEngine; public class QCARManager { #region NESTED // This struct stores 3D pose information as a position-vector, // orientation-Quaternion pair. The pose is given relatively to the camera. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct PoseData { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] public Vector3 position; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public Quaternion orientation; } // This struct stores general Trackable data like its 3D pose, its status // and its unique id. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct TrackableData { public PoseData pose; public TrackableBehaviour.Status status; public int id; } // This struct stores Virtual Button data like its current status (pressed // or not pressed) and its unique id. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct VirtualButtonData { public int id; public int isPressed; } // This struct stores data of an image header. It includes the width and // height of the image, the byte stride in the buffer, the buffer size // (which can differ from the image size e.g. when image is converted to a // power of two size) and the format of the image // (e.g. RGB565, grayscale, etc.). [StructLayout(LayoutKind.Sequential, Pack = 1)] private struct ImageHeaderData { public int width; public int height; public int stride; public int bufferWidth; public int bufferHeight; public int format; public int reallocate; public int updated; public IntPtr data; } #endregion // NESTED #region PROPERTIES // Returns an instance of a QCARManager (thread safe) public static QCARManager Instance { get { // Make sure only one instance of QCARManager is created. if (mInstance == null) { lock (typeof(QCARManager)) { if (mInstance == null) { mInstance = new QCARManager(); } } } return mInstance; } } // World Center Mode setting on the ARCamera public QCARBehaviour.WorldCenterMode WorldCenterMode { set { mWorldCenterMode = value; } get { return mWorldCenterMode; } } // World Center setting on the ARCamera public TrackableBehaviour WorldCenter { set { mWorldCenter = value; } get { return mWorldCenter; } } // A handle to the ARCamera object public Camera ARCamera { set { mARCamera = value; } get { return mARCamera; } } // True to have QCAR render the video background image natively // False to bind the video background to the texture set in // QCARRenderer.SetVideoBackgroundTextureID public bool DrawVideoBackground { set { mDrawVideobackground = value; } get { return mDrawVideobackground; } } #endregion // PROPERTIES #region PRIVATE_MEMBER_VARIABLES private static QCARManager mInstance = null; private QCARBehaviour.WorldCenterMode mWorldCenterMode; private TrackableBehaviour mWorldCenter = null; private Camera mARCamera = null; private int mAbsoluteNumTrackables = 0; private int mAbsoluteNumVirtualButtons = 0; private IntPtr mTrackablePtr = IntPtr.Zero; private IntPtr mVirtualButtonPtr = IntPtr.Zero; private TrackableData[] mTrackableDataArray = null; private LinkedList<int> mTrackableFoundQueue = new LinkedList<int>(); private bool mTrackableDataArrayDirty = false; private bool mVBDataArrayDirty = false; private IntPtr mImageHeaderData = IntPtr.Zero; private int mNumImageHeaders = 0; private bool mDrawVideobackground = true; #endregion // PRIVATE_MEMBER_VARIABLES #region PUBLIC_METHODS // Initialization public bool Init() { mAbsoluteNumTrackables = 0; mAbsoluteNumVirtualButtons = 0; mTrackablePtr = IntPtr.Zero; mVirtualButtonPtr = IntPtr.Zero; mTrackableDataArray = null; mTrackableFoundQueue = new LinkedList<int>(); mTrackableDataArrayDirty = false; mVBDataArrayDirty = false; mImageHeaderData = IntPtr.Zero; mNumImageHeaders = 0; InitializeTrackableContainer(); InitializeVirtualButtonContainer(); return true; } // Reinitialize the trackable and virtual button arrays on the next pass public bool Reinit() { mTrackableDataArrayDirty = true; mVBDataArrayDirty = true; return true; } // Process the camera image and tracking data for this frame public void Update(ScreenOrientation counterRotation) { // Reinitialize the trackable data container if required: if (mTrackableDataArrayDirty) { InitializeTrackableContainer(); mTrackableDataArrayDirty = false; } // Reinitialize the virtual button data container if required: if (mVBDataArrayDirty) { InitializeVirtualButtonContainer(); mVBDataArrayDirty = false; } // Prepare the camera image container UpdateImageContainer(); // Draw the video background or update the video texture // Retrieve trackable and virtual button state for this frame // Also retrieve registered camera images for this frame updateQCAR(mTrackablePtr, mAbsoluteNumTrackables, mVirtualButtonPtr, mAbsoluteNumVirtualButtons, mImageHeaderData, mNumImageHeaders, (int)counterRotation, mDrawVideobackground ? 0 : 1); // Handle the camera image data UpdateCameraFrame(); // Handle the trackable data UpdateTrackers(); } // Free globally allocated containers public void Deinit() { Marshal.FreeHGlobal(mTrackablePtr); Marshal.FreeHGlobal(mVirtualButtonPtr); Marshal.FreeHGlobal(mImageHeaderData); } #endregion // PUBLIC_METHODS #region PRIVATE_METHODS // Initialize the container for retrieving tracking data from native private void InitializeTrackableContainer() { // Destroy if the container has been allocated. Marshal.FreeHGlobal(mTrackablePtr); mAbsoluteNumTrackables = 0; ImageTracker imageTracker = (ImageTracker) TrackerManager.Instance.GetTracker( Tracker.Type.IMAGE_TRACKER); MarkerTracker markerTracker = (MarkerTracker) TrackerManager.Instance.GetTracker( Tracker.Type.MARKER_TRACKER); if (imageTracker != null) { DataSet activeDataSet = imageTracker.GetActiveDataSet(); if (activeDataSet != null) { mAbsoluteNumTrackables += activeDataSet.GetNumTrackables(); } } if (markerTracker != null) { mAbsoluteNumTrackables += markerTracker.GetNumMarkers(); } if (mAbsoluteNumTrackables > 0) { mTrackablePtr = Marshal.AllocHGlobal(Marshal.SizeOf( typeof(TrackableData)) * mAbsoluteNumTrackables); } else { mTrackablePtr = IntPtr.Zero; } mTrackableDataArray = new TrackableData[mAbsoluteNumTrackables]; if (!Application.isEditor) { Debug.Log("Absolute number of Trackables: " + mAbsoluteNumTrackables); } } // Initialize the container for retrieving virtual button data from native private void InitializeVirtualButtonContainer() { // Destroy if the container has been allocated. Marshal.FreeHGlobal(mVirtualButtonPtr); mAbsoluteNumVirtualButtons = 0; ImageTracker imageTracker = (ImageTracker) TrackerManager.Instance.GetTracker( Tracker.Type.IMAGE_TRACKER); if (imageTracker != null) { DataSet activeDataSet = imageTracker.GetActiveDataSet(); if (activeDataSet != null) { mAbsoluteNumVirtualButtons = dataSetGetNumVirtualButtons(activeDataSet.DataSetPtr); } } if (mAbsoluteNumVirtualButtons > 0) { mVirtualButtonPtr = Marshal.AllocHGlobal(Marshal.SizeOf( typeof(VirtualButtonData)) * mAbsoluteNumVirtualButtons); } else { mVirtualButtonPtr = IntPtr.Zero; } if (!Application.isEditor) { Debug.Log("Absolute number of virtual buttons: " + mAbsoluteNumVirtualButtons); } } // Unmarshal and process the tracking data private void UpdateTrackers() { if (Application.isEditor) { UpdateTrackablesEditor(); return; } // Unmarshal the trackable data // Take our array of unmanaged data from native and create an array of // TrackableData structures to work with (one per trackable, regardless // of whether or not that trackable is visible this frame). for (int i = 0; i < mAbsoluteNumTrackables; i++) { IntPtr trackablePtr = new IntPtr(mTrackablePtr.ToInt32() + i * Marshal.SizeOf(typeof(TrackableData))); TrackableData trackableData = (TrackableData) Marshal.PtrToStructure(trackablePtr, typeof(TrackableData)); mTrackableDataArray[i] = trackableData; } // Add newly found Trackables to the queue, remove lost ones // We keep track of the order in which Trackables become visible for the // AUTO World Center mode. This keeps the camera from jumping around in the // scene too much. foreach (TrackableData trackableData in mTrackableDataArray) { // We found a trackable (or set of Trackables) that match this id if ((trackableData.status == TrackableBehaviour.Status.DETECTED || trackableData.status == TrackableBehaviour.Status.TRACKED)) { if (!mTrackableFoundQueue.Contains(trackableData.id)) { // The trackable just became visible, add it to the queue mTrackableFoundQueue.AddLast(trackableData.id); } } else { if (mTrackableFoundQueue.Contains(trackableData.id)) { // The trackable just disappeared, remove it from the queue mTrackableFoundQueue.Remove(trackableData.id); } } } ImageTracker imageTracker = (ImageTracker) TrackerManager.Instance.GetTracker(Tracker.Type.IMAGE_TRACKER); MarkerTracker markerTracker = (MarkerTracker) TrackerManager.Instance.GetTracker(Tracker.Type.MARKER_TRACKER); // The "scene origin" is only used in world center mode auto or user. int originTrackableID = -1; if (mWorldCenterMode == QCARBehaviour.WorldCenterMode.USER && mWorldCenter != null) { originTrackableID = mWorldCenter.TrackableID; } else if (mWorldCenterMode == QCARBehaviour.WorldCenterMode.AUTO) { imageTracker.RemoveDisabledTrackablesFromQueue(ref mTrackableFoundQueue); markerTracker.RemoveDisabledTrackablesFromQueue(ref mTrackableFoundQueue); if (mTrackableFoundQueue.Count > 0) { originTrackableID = mTrackableFoundQueue.First.Value; } } // Update the Camera pose before Trackable poses are updated. imageTracker.UpdateCameraPose(mARCamera, mTrackableDataArray, originTrackableID); markerTracker.UpdateCameraPose(mARCamera, mTrackableDataArray, originTrackableID); // Update the Trackable poses. imageTracker.UpdateTrackablePoses(mARCamera, mTrackableDataArray, originTrackableID); markerTracker.UpdateTrackablePoses(mARCamera, mTrackableDataArray, originTrackableID); imageTracker.UpdateVirtualButtons(mAbsoluteNumVirtualButtons, mVirtualButtonPtr); } // Simulate tracking in the editor private void UpdateTrackablesEditor() { // When running within the Unity editor: TrackableBehaviour[] trackableBehaviours = (TrackableBehaviour[]) UnityEngine.Object.FindObjectsOfType(typeof(TrackableBehaviour)); // Simulate all Trackables were tracked successfully: for (int i = 0; i < trackableBehaviours.Length; i++) { TrackableBehaviour trackable = trackableBehaviours[i]; if (trackable.enabled) { trackable.OnTrackerUpdate(TrackableBehaviour.Status.TRACKED); } } } // Update the image container for the currently registered formats private void UpdateImageContainer() { CameraDevice cameraDevice = CameraDevice.Instance; // Reallocate the data container if the number of requested images has // changed, or if the container is not allocated if (mNumImageHeaders != cameraDevice.GetAllImages().Count || (cameraDevice.GetAllImages().Count > 0 && mImageHeaderData == IntPtr.Zero)) { mNumImageHeaders = cameraDevice.GetAllImages().Count; Marshal.FreeHGlobal(mImageHeaderData); mImageHeaderData = Marshal.AllocHGlobal(Marshal.SizeOf( typeof(ImageHeaderData)) * mNumImageHeaders); } // Update the image info: int i = 0; foreach (Image image in cameraDevice.GetAllImages().Values) { IntPtr imagePtr = new IntPtr(mImageHeaderData.ToInt32() + i * Marshal.SizeOf(typeof(ImageHeaderData))); ImageHeaderData imageHeader = new ImageHeaderData(); imageHeader.width = image.Width; imageHeader.height = image.Height; imageHeader.stride = image.Stride; imageHeader.bufferWidth = image.BufferWidth; imageHeader.bufferHeight = image.BufferHeight; imageHeader.format = (int)image.PixelFormat; imageHeader.reallocate = 0; imageHeader.updated = 0; imageHeader.data = image.UnmanagedData; Marshal.StructureToPtr(imageHeader, imagePtr, false); ++i; } } // Unmarshal the camera images for this frame private void UpdateCameraFrame() { // Unmarshal the image data: int i = 0; foreach (Image image in CameraDevice.Instance.GetAllImages().Values) { IntPtr imagePtr = new IntPtr(mImageHeaderData.ToInt32() + i * Marshal.SizeOf(typeof(ImageHeaderData))); ImageHeaderData imageHeader = (ImageHeaderData) Marshal.PtrToStructure(imagePtr, typeof(ImageHeaderData)); // Copy info back to managed Image instance: image.Width = imageHeader.width; image.Height = imageHeader.height; image.Stride = imageHeader.stride; image.BufferWidth = imageHeader.bufferWidth; image.BufferHeight = imageHeader.bufferHeight; image.PixelFormat = (Image.PIXEL_FORMAT) imageHeader.format; // Reallocate if required: if (imageHeader.reallocate == 1) { image.Pixels = new byte[qcarGetBufferSize(image.BufferWidth, image.BufferHeight, (int)image.PixelFormat)]; Marshal.FreeHGlobal(image.UnmanagedData); image.UnmanagedData = Marshal.AllocHGlobal(qcarGetBufferSize(image.BufferWidth, image.BufferHeight, (int)image.PixelFormat)); // Note we don't copy the data this frame as the unmanagedVirtualButtonBehaviour // buffer was not filled. } else if (imageHeader.updated == 1) { // Copy data: image.CopyPixelsFromUnmanagedBuffer(); } ++i; } } #endregion // PRIVATE_METHODS #region NATIVE_FUNCTIONS #if !UNITY_EDITOR [DllImport(QCARMacros.PLATFORM_DLL)] private static extern int updateQCAR([In, Out]IntPtr trackableDataArray, int trackableArrayLength, [In, Out]IntPtr vbDataArray, int vbArrayLength, [In, Out]IntPtr imageHeaderDataArray, int imageHeaderArrayLength, int screenOrientation, int bindVideoBackground); [DllImport(QCARMacros.PLATFORM_DLL)] private static extern int markerGetId(String nTrackableName); [DllImport(QCARMacros.PLATFORM_DLL)] private static extern int markerSetSize(int trackableIndex, [In, Out]IntPtr size); [DllImport(QCARMacros.PLATFORM_DLL)] private static extern int dataSetGetNumVirtualButtons(IntPtr dataSetPtr); [DllImport(QCARMacros.PLATFORM_DLL)] private static extern int qcarGetBitsPerPixel(int format); [DllImport(QCARMacros.PLATFORM_DLL)] private static extern int qcarGetBufferSize(int width, int height, int format); #else private static int updateQCAR([In, Out]IntPtr trackableDataArray, int trackableArrayLength, [In, Out]IntPtr vbDataArray, int vbArrayLength, [In, Out]IntPtr imageHeaderDataArray, int imageHeaderArrayLength, int screenOrientation, int bindVideoBackground) { return 0; } private static int markerGetId(String nTrackableName) { return 0; } private static int markerSetSize(int trackableIndex, [In, Out]IntPtr size) { return 0; } private static int dataSetGetNumVirtualButtons(IntPtr dataSetPtr) { return 0; } private static int qcarGetBitsPerPixel(int format) { return 0; } private static int qcarGetBufferSize(int width, int height, int format) { return 0; } #endif #endregion // NATIVE_FUNCTIONS }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Runtime.Serialization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using JetBrains.Annotations; using NodaTime.Text; using NodaTime.Utility; using NodaTime.Annotations; namespace NodaTime { /// <summary> /// An interval between two instants in time (start and end). /// </summary> /// <remarks> /// <para> /// The interval includes the start instant and excludes the end instant. However, an interval /// may be missing its start or end, in which case the interval is deemed to be infinite in that /// direction. /// </para> /// <para> /// The end may equal the start (resulting in an empty interval), but will not be before the start. /// </para> /// </remarks> /// <threadsafety>This type is an immutable value type. See the thread safety section of the user guide for more information.</threadsafety> #if !PCL [Serializable] #endif public struct Interval : IEquatable<Interval>, IXmlSerializable #if !PCL , ISerializable #endif { /// <summary>The start of the interval.</summary> private readonly Instant start; /// <summary>The end of the interval. This will never be earlier than the start.</summary> private readonly Instant end; /// <summary> /// Initializes a new instance of the <see cref="Interval"/> struct. /// The interval includes the <paramref name="start"/> instant and excludes the /// <paramref name="end"/> instant. The end may equal the start (resulting in an empty interval), but must not be before the start. /// </summary> /// <exception cref="ArgumentOutOfRangeException"><paramref name="end"/> is earlier than <paramref name="start"/>.</exception> /// <param name="start">The start <see cref="Instant"/>.</param> /// <param name="end">The end <see cref="Instant"/>.</param> public Interval(Instant start, Instant end) { if (end < start) { throw new ArgumentOutOfRangeException(nameof(end), "The end parameter must be equal to or later than the start parameter"); } this.start = start; this.end = end; } /// <summary> /// Initializes a new instance of the <see cref="Interval"/> struct from two nullable <see cref="Instant"/> /// values. /// </summary> /// <remarks> /// If the start is null, the interval is deemed to stretch to the start of time. If the end is null, /// the interval is deemed to stretch to the end of time. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"><paramref name="end"/> is earlier than <paramref name="start"/>, /// if they are both non-null.</exception> /// <param name="start">The start <see cref="Instant"/> or null.</param> /// <param name="end">The end <see cref="Instant"/> or null.</param> public Interval(Instant? start, Instant? end) { this.start = start ?? Instant.BeforeMinValue; this.end = end ?? Instant.AfterMaxValue; if (end < start) { throw new ArgumentOutOfRangeException(nameof(end), "The end parameter must be equal to or later than the start parameter"); } } /// <summary> /// Gets the start instant - the inclusive lower bound of the interval. /// </summary> /// <remarks> /// This will never be later than <see cref="End"/>, though it may be equal to it. /// </remarks> /// <value>The start <see cref="Instant"/>.</value> /// <exception cref="InvalidOperationException">The interval extends to the start of time.</exception> /// <seealso cref="HasStart"/> public Instant Start { get { Preconditions.CheckState(start.IsValid, "Interval extends to start of time"); return start; } } /// <summary> /// Returns <c>true</c> if this interval has a fixed start point, or <c>false</c> if it /// extends to the start of time. /// </summary> /// <value><c>true</c> if this interval has a fixed start point, or <c>false</c> if it /// extends to the start of time.</value> public bool HasStart => start.IsValid; /// <summary> /// Gets the end instant - the exclusive upper bound of the interval. /// </summary> /// <value>The end <see cref="Instant"/>.</value> /// <exception cref="InvalidOperationException">The interval extends to the end of time.</exception> /// <seealso cref="HasEnd"/> public Instant End { get { Preconditions.CheckState(end.IsValid, "Interval extends to end of time"); return end; } } /// <summary> /// Returns the raw end value of the interval: a normal instant or <see cref="Instant.AfterMaxValue"/>. /// This value should never be exposed. /// </summary> internal Instant RawEnd => end; /// <summary> /// Returns <c>true</c> if this interval has a fixed end point, or <c>false</c> if it /// extends to the end of time. /// </summary> /// <value><c>true</c> if this interval has a fixed end point, or <c>false</c> if it /// extends to the end of time.</value> public bool HasEnd => end.IsValid; /// <summary> /// Returns the duration of the interval. /// </summary> /// <remarks> /// This will always be a non-negative duration, though it may be zero. /// </remarks> /// <value>The duration of the interval.</value> /// <exception cref="InvalidOperationException">The interval extends to the start or end of time.</exception> public Duration Duration => End - Start; /// <summary> /// Returns whether or not this interval contains the given instant. /// </summary> /// <param name="instant">Instant to test.</param> /// <returns>True if this interval contains the given instant; false otherwise.</returns> [Pure] public bool Contains(Instant instant) => instant >= start && instant < end; #region Implementation of IEquatable<Interval> /// <summary> /// Indicates whether the value of this interval is equal to the value of the specified interval. /// </summary> /// <param name="other">The value to compare with this instance.</param> /// <returns> /// true if the value of this instant is equal to the value of the <paramref name="other" /> parameter; /// otherwise, false. /// </returns> public bool Equals(Interval other) => start == other.start && end == other.end; #endregion #region object overrides /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; /// otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) => obj is Interval && Equals((Interval)obj); /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns> /// A 32-bit signed integer that is the hash code for this instance. /// </returns> /// <filterpriority>2</filterpriority> public override int GetHashCode() => HashCodeHelper.Hash(start, end); /// <summary> /// Returns a string representation of this interval, in extended ISO-8601 format: the format /// is "start/end" where each instant uses a format of "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFF'Z'". /// If the start or end is infinite, the relevant part uses "StartOfTime" or "EndOfTime" to /// represent this. /// </summary> /// <returns>A string representation of this interval.</returns> public override string ToString() { var pattern = InstantPattern.ExtendedIsoPattern; return pattern.Format(start) + "/" + pattern.Format(end); } #endregion #region Operators /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(Interval left, Interval right) => left.Equals(right); /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(Interval left, Interval right) => !(left == right); #endregion #region XML serialization /// <inheritdoc /> XmlSchema IXmlSerializable.GetSchema() => null; /// <inheritdoc /> void IXmlSerializable.ReadXml([NotNull] XmlReader reader) { Preconditions.CheckNotNull(reader, nameof(reader)); var pattern = InstantPattern.ExtendedIsoPattern; Instant newStart = reader.MoveToAttribute("start") ? pattern.Parse(reader.Value).Value : Instant.BeforeMinValue; Instant newEnd = reader.MoveToAttribute("end") ? pattern.Parse(reader.Value).Value : Instant.AfterMaxValue; this = new Interval(newStart, newEnd); // Consume the rest of this element, as per IXmlSerializable.ReadXml contract. reader.Skip(); } /// <inheritdoc /> void IXmlSerializable.WriteXml([NotNull] XmlWriter writer) { Preconditions.CheckNotNull(writer, nameof(writer)); var pattern = InstantPattern.ExtendedIsoPattern; if (HasStart) { writer.WriteAttributeString("start", pattern.Format(start)); } if (HasEnd) { writer.WriteAttributeString("end", pattern.Format(end)); } } #endregion #if !PCL #region Binary serialization private const string StartDaysSerializationName = "startDays"; private const string EndDaysSerializationName = "endDays"; private const string StartNanosecondOfDaySerializationName = "startNanoOfDay"; private const string EndNanosecondOfDaySerializationName = "endNanoOfDay"; private const string PresenceName = "presence"; /// <summary> /// Private constructor only present for serialization. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to fetch data from.</param> /// <param name="context">The source for this deserialization.</param> private Interval([NotNull] SerializationInfo info, StreamingContext context) { var presence = info.GetByte(PresenceName); start = (presence & 1) == 0 ? Instant.BeforeMinValue : Instant.FromUntrustedDuration(new Duration(info, StartDaysSerializationName, StartNanosecondOfDaySerializationName)); end = (presence & 2) == 0 ? Instant.AfterMaxValue : Instant.FromUntrustedDuration(new Duration(info, EndDaysSerializationName, EndNanosecondOfDaySerializationName)); } /// <summary> /// Implementation of <see cref="ISerializable.GetObjectData"/>. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to populate with data.</param> /// <param name="context">The destination for this serialization.</param> [System.Security.SecurityCritical] void ISerializable.GetObjectData([NotNull] SerializationInfo info, StreamingContext context) { // We can't easily tell which fields are present based on SerializationInfo (other than by iterating), // so we add one extra value to say which other values to include. We may wish to generalize this // at some point... info.AddValue(PresenceName, (byte) ((HasStart ? 1 : 0) | (HasEnd ? 2 : 0))); // FIXME:SERIALIZATION if (HasStart) { start.TimeSinceEpoch.Serialize(info, StartDaysSerializationName, StartNanosecondOfDaySerializationName); } if (HasEnd) { end.TimeSinceEpoch.Serialize(info, EndDaysSerializationName, EndNanosecondOfDaySerializationName); } } #endregion #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Text; using Newtonsoft.Json.Bson; using Microsoft.Xunit.Performance; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] public class JsonBenchmarks { #if DEBUG public const int Iterations = 1; public const int JsonNetIterations = 1; #else public const int Iterations = 30000; public const int JsonNetIterations = 90000; #endif const string DataContractXml = @"<JsonBenchmarks.TestObject xmlns=""http://schemas.datacontract.org/2004/07/"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><Id>33</Id><Name>SqMtx</Name><Results xmlns:a=""http://schemas.microsoft.com/2003/10/Serialization/Arrays""><a:double>101.3</a:double><a:double>99.8</a:double><a:double>99.6</a:double><a:double>100.4</a:double></Results><WhenRun>2015-01-01T00:00:00-08:00</WhenRun></JsonBenchmarks.TestObject>"; const string DataContractJson = @"{""Id"":33,""Name"":""SqMtx"",""Results"":[101.3,99.8,99.6,100.4],""WhenRun"":""\/Date(1420099200000-0800)\/""}"; const string JsonNetJson = @"{""Id"":33,""Name"":""SqMtx"",""Results"":[101.3,99.8,99.6,100.4],""WhenRun"":""2015-01-01T00:00:00-08:00""}"; byte[] JsonNetBinary = new byte[] { 0x68, 0x00, 0x00, 0x00, 0x10, 0x49, 0x64, 0x00, 0x21, 0x00, 0x00, 0x00, 0x02, 0x4E, 0x61, 0x6D, 0x65, 0x00, 0x06, 0x00, 0x00, 0x00, 0x53, 0x71, 0x4D, 0x74, 0x78, 0x00, 0x04, 0x52, 0x65, 0x73, 0x75, 0x6C, 0x74, 0x73, 0x00, 0x31, 0x00, 0x00, 0x00, 0x01, 0x30, 0x00, 0x33, 0x33, 0x33, 0x33, 0x33, 0x53, 0x59, 0x40, 0x01, 0x31, 0x00, 0x33, 0x33, 0x33, 0x33, 0x33, 0xF3, 0x58, 0x40, 0x01, 0x32, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0xE6, 0x58, 0x40, 0x01, 0x33, 0x00, 0x9A, 0x99, 0x99, 0x99, 0x99, 0x19, 0x59, 0x40, 0x00, 0x09, 0x57, 0x68, 0x65, 0x6E, 0x52, 0x75, 0x6E, 0x00, 0x00, 0x24, 0x82, 0xA4, 0x4A, 0x01, 0x00, 0x00, 0x00 }; static volatile object VolatileObject; [MethodImpl(MethodImplOptions.NoInlining)] static void Escape(object obj) { VolatileObject = obj; } [DataContract] public class TestObject { [DataMember] public int Id { get; set; } [DataMember] public string Name { get; set; } [DataMember] public double[] Results { get; set; } [DataMember] public DateTime WhenRun { get; set; } public static TestObject Expected() { TestObject t = new TestObject(); t.Id = 33; t.Name = "SqMtx"; t.Results = new double[] { 101.3, 99.8, 99.6, 100.4 }; t.WhenRun = DateTime.Parse("Jan 1, 2015 8:00 GMT"); return t; } } private bool Deserialize() { bool result = true; DeserializeObject(); return result; } private void DeserializeObject() { DeserializeDataContractBench(); DeserializeDataContractJsonBench(); DeserializeJsonNetBinaryBench(); DeserializeJsonNetBench(); } [Benchmark] private void DeserializeDataContract() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { DeserializeDataContractBench(); } } } private void DeserializeDataContractBench() { DataContractSerializer ds = new DataContractSerializer(typeof(TestObject)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(DataContractXml)); DeserializeDataContractBenchInner(ds, ms); } private void DeserializeDataContractBenchInner(DataContractSerializer ds, MemoryStream ms) { TestObject t; for (int i = 0; i < Iterations; i++) { t = (TestObject)ds.ReadObject(ms); Escape(t.Name); ms.Seek(0, SeekOrigin.Begin); } } [Benchmark] private void DeserializeDataContractJson() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { DeserializeDataContractJsonBench(); } } } private void DeserializeDataContractJsonBench() { DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(TestObject)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(DataContractJson)); DeserializeDataContractJsonBenchInner(ds, ms); } private void DeserializeDataContractJsonBenchInner(DataContractJsonSerializer ds, MemoryStream ms) { TestObject t; for (int i = 0; i < Iterations; i++) { t = (TestObject) ds.ReadObject(ms); Escape(t.Name); ms.Seek(0, SeekOrigin.Begin); } } [Benchmark] private void DeserializeJsonNetBinary() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { DeserializeJsonNetBinaryBench(); } } } private void DeserializeJsonNetBinaryBench() { DeserializeJsonNetBinaryBenchInner(); } private void DeserializeJsonNetBinaryBenchInner() { Newtonsoft.Json.JsonSerializer ds = new Newtonsoft.Json.JsonSerializer(); TestObject t; Type ty = typeof(TestObject); for (int i = 0; i < JsonNetIterations; i++) { BsonReader br = new BsonReader(new MemoryStream(JsonNetBinary)); t = (TestObject) ds.Deserialize(br, ty); Escape(t.Name); } } [Benchmark] private void DeserializeJsonNet() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { DeserializeJsonNetBench(); } } } private void DeserializeJsonNetBench() { DeserializeJsonNetBenchInner(); } private void DeserializeJsonNetBenchInner() { Newtonsoft.Json.JsonSerializer ds = new Newtonsoft.Json.JsonSerializer(); TestObject t; Type ty = typeof(TestObject); for (int i = 0; i < JsonNetIterations; i++) { StringReader sr = new StringReader(JsonNetJson); t = (TestObject)ds.Deserialize(sr, ty); Escape(t.Name); } } public static int Main() { var tests = new JsonBenchmarks(); bool result = tests.Deserialize(); return result ? 100 : -1; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// A user account to create on an Azure Batch node. Tasks may be configured to execute in the security context of the /// user account. /// </summary> public partial class UserAccount : ITransportObjectProvider<Models.UserAccount>, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<Common.ElevationLevel?> ElevationLevelProperty; public readonly PropertyAccessor<LinuxUserConfiguration> LinuxUserConfigurationProperty; public readonly PropertyAccessor<string> NameProperty; public readonly PropertyAccessor<string> PasswordProperty; public readonly PropertyAccessor<WindowsUserConfiguration> WindowsUserConfigurationProperty; public PropertyContainer() : base(BindingState.Unbound) { this.ElevationLevelProperty = this.CreatePropertyAccessor<Common.ElevationLevel?>(nameof(ElevationLevel), BindingAccess.Read | BindingAccess.Write); this.LinuxUserConfigurationProperty = this.CreatePropertyAccessor<LinuxUserConfiguration>(nameof(LinuxUserConfiguration), BindingAccess.Read | BindingAccess.Write); this.NameProperty = this.CreatePropertyAccessor<string>(nameof(Name), BindingAccess.Read | BindingAccess.Write); this.PasswordProperty = this.CreatePropertyAccessor<string>(nameof(Password), BindingAccess.Read | BindingAccess.Write); this.WindowsUserConfigurationProperty = this.CreatePropertyAccessor<WindowsUserConfiguration>(nameof(WindowsUserConfiguration), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.UserAccount protocolObject) : base(BindingState.Bound) { this.ElevationLevelProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.ElevationLevel, Common.ElevationLevel>(protocolObject.ElevationLevel), nameof(ElevationLevel), BindingAccess.Read); this.LinuxUserConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.LinuxUserConfiguration, o => new LinuxUserConfiguration(o).Freeze()), nameof(LinuxUserConfiguration), BindingAccess.Read); this.NameProperty = this.CreatePropertyAccessor( protocolObject.Name, nameof(Name), BindingAccess.Read); this.PasswordProperty = this.CreatePropertyAccessor( protocolObject.Password, nameof(Password), BindingAccess.Read); this.WindowsUserConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.WindowsUserConfiguration, o => new WindowsUserConfiguration(o).Freeze()), nameof(WindowsUserConfiguration), BindingAccess.Read); } } private readonly PropertyContainer propertyContainer; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="UserAccount"/> class. /// </summary> /// <param name='name'>The name of the user account.</param> /// <param name='password'>The password for the user account.</param> /// <param name='elevationLevel'>The elevation level of the user account.</param> /// <param name='linuxUserConfiguration'>Additional properties used to create a user account on a Linux node.</param> /// <param name='windowsUserConfiguration'>The Windows-specific user configuration for the user account.</param> public UserAccount( string name, string password, Common.ElevationLevel? elevationLevel = default(Common.ElevationLevel?), LinuxUserConfiguration linuxUserConfiguration = default(LinuxUserConfiguration), WindowsUserConfiguration windowsUserConfiguration = default(WindowsUserConfiguration)) { this.propertyContainer = new PropertyContainer(); this.Name = name; this.Password = password; this.ElevationLevel = elevationLevel; this.LinuxUserConfiguration = linuxUserConfiguration; this.WindowsUserConfiguration = windowsUserConfiguration; } /// <summary> /// Default constructor to support mocking the <see cref="UserAccount"/> class. /// </summary> protected UserAccount() { this.propertyContainer = new PropertyContainer(); } internal UserAccount(Models.UserAccount protocolObject) { this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region UserAccount /// <summary> /// Gets or sets the elevation level of the user account. /// </summary> /// <remarks> /// If omitted, the default is <see cref="Common.ElevationLevel.NonAdmin"/> /// </remarks> public Common.ElevationLevel? ElevationLevel { get { return this.propertyContainer.ElevationLevelProperty.Value; } set { this.propertyContainer.ElevationLevelProperty.Value = value; } } /// <summary> /// Gets or sets additional properties used to create a user account on a Linux node. /// </summary> /// <remarks> /// This property is ignored if specified on a Windows pool. If not specified, the user is created with the default /// options. /// </remarks> public LinuxUserConfiguration LinuxUserConfiguration { get { return this.propertyContainer.LinuxUserConfigurationProperty.Value; } set { this.propertyContainer.LinuxUserConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the name of the user account. /// </summary> public string Name { get { return this.propertyContainer.NameProperty.Value; } set { this.propertyContainer.NameProperty.Value = value; } } /// <summary> /// Gets or sets the password for the user account. /// </summary> public string Password { get { return this.propertyContainer.PasswordProperty.Value; } set { this.propertyContainer.PasswordProperty.Value = value; } } /// <summary> /// Gets or sets the Windows-specific user configuration for the user account. /// </summary> /// <remarks> /// This property can only be specified if the user is on a Windows pool. If not specified and on a Windows pool, /// the user is created with the default options. /// </remarks> public WindowsUserConfiguration WindowsUserConfiguration { get { return this.propertyContainer.WindowsUserConfigurationProperty.Value; } set { this.propertyContainer.WindowsUserConfigurationProperty.Value = value; } } #endregion // UserAccount #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.UserAccount ITransportObjectProvider<Models.UserAccount>.GetTransportObject() { Models.UserAccount result = new Models.UserAccount() { ElevationLevel = UtilitiesInternal.MapNullableEnum<Common.ElevationLevel, Models.ElevationLevel>(this.ElevationLevel), LinuxUserConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.LinuxUserConfiguration, (o) => o.GetTransportObject()), Name = this.Name, Password = this.Password, WindowsUserConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.WindowsUserConfiguration, (o) => o.GetTransportObject()), }; return result; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects. /// </summary> internal static IList<UserAccount> ConvertFromProtocolCollection(IEnumerable<Models.UserAccount> protoCollection) { ConcurrentChangeTrackedModifiableList<UserAccount> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable( items: protoCollection, objectCreationFunc: o => new UserAccount(o)); return converted; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects, in a frozen state. /// </summary> internal static IList<UserAccount> ConvertFromProtocolCollectionAndFreeze(IEnumerable<Models.UserAccount> protoCollection) { ConcurrentChangeTrackedModifiableList<UserAccount> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable( items: protoCollection, objectCreationFunc: o => new UserAccount(o).Freeze()); converted = UtilitiesInternal.CreateObjectWithNullCheck(converted, o => o.Freeze()); return converted; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects, with each object marked readonly /// and returned as a readonly collection. /// </summary> internal static IReadOnlyList<UserAccount> ConvertFromProtocolCollectionReadOnly(IEnumerable<Models.UserAccount> protoCollection) { IReadOnlyList<UserAccount> converted = UtilitiesInternal.CreateObjectWithNullCheck( UtilitiesInternal.CollectionToNonThreadSafeCollection( items: protoCollection, objectCreationFunc: o => new UserAccount(o).Freeze()), o => o.AsReadOnly()); return converted; } #endregion // Internal/private methods } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2015-2016 FUJIWARA, Yusuke // // 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 -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; #if !UNITY using System.Collections.Generic; #endif // !UNITY #if FEATURE_TAP using System.Threading; using System.Threading.Tasks; #endif // FEATURE_TAP using MsgPack.Serialization.CollectionSerializers; namespace MsgPack.Serialization.ReflectionSerializers { [Preserve( AllMembers = true )] #if !UNITY internal sealed class ReflectionEnumerableMessagePackSerializer<TCollection, TItem> : EnumerableMessagePackSerializer<TCollection, TItem> where TCollection : IEnumerable<TItem> #else internal sealed class ReflectionEnumerableMessagePackSerializer : UnityEnumerableMessagePackSerializer #endif // !UNITY { #if !UNITY private readonly Func<int, TCollection> _factory; private readonly Action<TCollection, TItem> _addItem; #else private readonly Func<int, object> _factory; private readonly Action<object, object> _addItem; #endif // !UNITY private readonly bool _isPackable; private readonly bool _isUnpackable; #if FEATURE_TAP private readonly bool _isAsyncPackable; private readonly bool _isAsyncUnpackable; #endif // FEATURE_TAP #if !UNITY public ReflectionEnumerableMessagePackSerializer( SerializationContext ownerContext, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema itemsSchema, SerializationTarget targetInfo ) : base( ownerContext, itemsSchema, targetInfo.GetCapabilitiesForCollection( collectionTraits ) ) { if ( targetInfo.CanDeserialize ) { this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory<TCollection, TItem>( targetInfo.DeserializationConstructor ); this._addItem = ReflectionSerializerHelper.GetAddItem<TCollection, TItem>( targetType, collectionTraits ); } else { this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( targetType ); }; this._addItem = ( c, x ) => { throw SerializationExceptions.NewUnpackFromIsNotSupported( targetType ); }; } this._isPackable = typeof( IPackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); #if FEATURE_TAP this._isAsyncPackable = typeof( IAsyncPackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); this._isAsyncUnpackable = typeof( IAsyncUnpackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); #endif // FEATURE_TAP } #else public ReflectionEnumerableMessagePackSerializer( SerializationContext ownerContext, Type abstractType, Type concreteType, CollectionTraits concreteTypeCollectionTraits, PolymorphismSchema itemsSchema, SerializationTarget targetInfo ) : base( ownerContext, abstractType, concreteTypeCollectionTraits, itemsSchema, targetInfo.GetCapabilitiesForCollection( concreteTypeCollectionTraits ) ) { if ( targetInfo.CanDeserialize ) { this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, concreteTypeCollectionTraits.ElementType, targetInfo.DeserializationConstructor ); this._addItem = ReflectionSerializerHelper.GetAddItem( concreteType, concreteTypeCollectionTraits ); } else { this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( concreteType ); }; this._addItem = ( c, x ) => { throw SerializationExceptions.NewUnpackFromIsNotSupported( concreteType ); }; } this._isPackable = typeof( IPackable ).IsAssignableFrom( concreteType ?? abstractType ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( concreteType ?? abstractType ); } #endif // !UNITY #if !UNITY protected internal override void PackToCore( Packer packer, TCollection objectTree ) #else protected internal override void PackToCore( Packer packer, object objectTree ) #endif { if ( this._isPackable ) { ( ( IPackable )objectTree ).PackToMessage( packer, null ); return; } base.PackToCore( packer, objectTree ); } #if FEATURE_TAP protected internal override Task PackToAsyncCore( Packer packer, TCollection objectTree, CancellationToken cancellationToken ) { if ( this._isAsyncPackable ) { return ( ( IAsyncPackable )objectTree ).PackToMessageAsync( packer, null, cancellationToken ); } return base.PackToAsyncCore( packer, objectTree, cancellationToken ); } #endif // FEATURE_TAP [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] #if !UNITY protected internal override TCollection UnpackFromCore( Unpacker unpacker ) #else protected internal override object UnpackFromCore( Unpacker unpacker ) #endif // !UNITY { if ( this._isUnpackable ) { var result = this.CreateInstance( 0 ); ( ( IUnpackable )result ).UnpackFromMessage( unpacker ); return result; } if ( !unpacker.IsArrayHeader ) { SerializationExceptions.ThrowIsNotArrayHeader( unpacker ); } var itemsCount = UnpackHelpers.GetItemsCount( unpacker ); var collection = this.CreateInstance( itemsCount ); this.UnpackToCore( unpacker, collection, itemsCount ); return collection; } #if FEATURE_TAP protected internal override async Task<TCollection> UnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken ) { if ( this._isAsyncUnpackable ) { var result = this.CreateInstance( 0 ); await ( ( IAsyncUnpackable )result ).UnpackFromMessageAsync( unpacker, cancellationToken ).ConfigureAwait( false ); return result; } if ( !unpacker.IsArrayHeader ) { SerializationExceptions.ThrowIsNotArrayHeader( unpacker ); } var itemsCount = UnpackHelpers.GetItemsCount( unpacker ); var collection = this.CreateInstance( itemsCount ); await this.UnpackToAsyncCore( unpacker, collection, itemsCount, cancellationToken ).ConfigureAwait( false ); return collection; } #endif // FEATURE_TAP #if !UNITY protected override TCollection CreateInstance( int initialCapacity ) #else protected override object CreateInstance( int initialCapacity ) #endif // !UNITY { return this._factory( initialCapacity ); } #if !UNITY protected override void AddItem( TCollection collection, TItem item ) #else protected override void AddItem( object collection, object item ) #endif // !UNITY { this._addItem( collection, item ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Internal; using Xunit; namespace Microsoft.AspNetCore.SignalR.Common.Tests.Internal.Protocol { public class MemoryBufferWriterTests { private static readonly int MinimumSegmentSize; static MemoryBufferWriterTests() { var buffer = ArrayPool<byte>.Shared.Rent(1); // Compute the minimum segment size of the array pool MinimumSegmentSize = buffer.Length; ArrayPool<byte>.Shared.Return(buffer); } [Fact] public void WritingNotingGivesEmptyData() { using (var bufferWriter = new MemoryBufferWriter()) { Assert.Equal(0, bufferWriter.Length); var data = bufferWriter.ToArray(); Assert.Empty(data); } } [Fact] public void WritingNotingGivesEmptyData_CopyTo() { using (var bufferWriter = new MemoryBufferWriter()) { Assert.Equal(0, bufferWriter.Length); var data = new byte[bufferWriter.Length]; bufferWriter.CopyTo(data); Assert.Empty(data); } } [Fact] public void WriteByteWorksAsFirstCall() { using (var bufferWriter = new MemoryBufferWriter()) { bufferWriter.WriteByte(234); var data = bufferWriter.ToArray(); Assert.Equal(1, bufferWriter.Length); Assert.Single(data); Assert.Equal(234, data[0]); } } [Fact] public void WriteByteWorksAsFirstCall_CopyTo() { using (var bufferWriter = new MemoryBufferWriter()) { bufferWriter.WriteByte(234); Assert.Equal(1, bufferWriter.Length); var data = new byte[bufferWriter.Length]; bufferWriter.CopyTo(data); Assert.Equal(234, data[0]); } } [Fact] public void WriteByteWorksIfFirstByteInNewSegment() { var inputSize = MinimumSegmentSize; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(16, bufferWriter.Length); bufferWriter.WriteByte(16); Assert.Equal(17, bufferWriter.Length); var data = bufferWriter.ToArray(); Assert.Equal(input, data.Take(16)); Assert.Equal(16, data[16]); } } [Fact] public void WriteByteWorksIfFirstByteInNewSegment_CopyTo() { var inputSize = MinimumSegmentSize; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(16, bufferWriter.Length); bufferWriter.WriteByte(16); Assert.Equal(17, bufferWriter.Length); var data = new byte[bufferWriter.Length]; bufferWriter.CopyTo(data); Assert.Equal(input, data.Take(16)); Assert.Equal(16, data[16]); } } [Fact] public void WriteByteWorksIfSegmentHasSpace() { var input = new byte[] { 11, 12, 13 }; using (var bufferWriter = new MemoryBufferWriter()) { bufferWriter.Write(input, 0, input.Length); bufferWriter.WriteByte(14); Assert.Equal(4, bufferWriter.Length); var data = bufferWriter.ToArray(); Assert.Equal(4, data.Length); Assert.Equal(11, data[0]); Assert.Equal(12, data[1]); Assert.Equal(13, data[2]); Assert.Equal(14, data[3]); } } [Fact] public void WriteByteWorksIfSegmentHasSpace_CopyTo() { var input = new byte[] { 11, 12, 13 }; using (var bufferWriter = new MemoryBufferWriter()) { bufferWriter.Write(input, 0, input.Length); bufferWriter.WriteByte(14); Assert.Equal(4, bufferWriter.Length); var data = new byte[bufferWriter.Length]; bufferWriter.CopyTo(data); Assert.Equal(11, data[0]); Assert.Equal(12, data[1]); Assert.Equal(13, data[2]); Assert.Equal(14, data[3]); } } [Fact] public void ToArrayWithExactlyFullSegmentsWorks() { var inputSize = MinimumSegmentSize * 2; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(input.Length, bufferWriter.Length); var data = bufferWriter.ToArray(); Assert.Equal(input, data); } } [Fact] public void ToArrayWithExactlyFullSegmentsWorks_CopyTo() { var inputSize = MinimumSegmentSize * 2; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(input.Length, bufferWriter.Length); var data = new byte[bufferWriter.Length]; bufferWriter.CopyTo(data); Assert.Equal(input, data); } } [Fact] public void ToArrayWithSomeFullSegmentsWorks() { var inputSize = (MinimumSegmentSize * 2) + 1; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(input.Length, bufferWriter.Length); var data = bufferWriter.ToArray(); Assert.Equal(input, data); } } [Fact] public void ToArrayWithSomeFullSegmentsWorks_CopyTo() { var inputSize = (MinimumSegmentSize * 2) + 1; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(input.Length, bufferWriter.Length); var data = new byte[bufferWriter.Length]; bufferWriter.CopyTo(data); Assert.Equal(input, data); } } [Fact] public async Task CopyToAsyncWithExactlyFullSegmentsWorks() { var inputSize = MinimumSegmentSize * 2; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(input.Length, bufferWriter.Length); var ms = new MemoryStream(); await bufferWriter.CopyToAsync(ms); var data = ms.ToArray(); Assert.Equal(input, data); } } [Fact] public async Task CopyToAsyncWithSomeFullSegmentsWorks() { // 2 segments + 1 extra byte var inputSize = (MinimumSegmentSize * 2) + 1; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(input.Length, bufferWriter.Length); var ms = new MemoryStream(); await bufferWriter.CopyToAsync(ms); var data = ms.ToArray(); Assert.Equal(input, data); } } [Fact] public void CopyToWithExactlyFullSegmentsWorks() { var inputSize = MinimumSegmentSize * 2; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(input.Length, bufferWriter.Length); using (var destination = new MemoryBufferWriter()) { bufferWriter.CopyTo(destination); var data = destination.ToArray(); Assert.Equal(input, data); } } } [Fact] public void CopyToWithExactlyFullSegmentsWorks_CopyTo() { var inputSize = MinimumSegmentSize * 2; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(input.Length, bufferWriter.Length); using (var destination = new MemoryBufferWriter()) { bufferWriter.CopyTo(destination); var data = new byte[bufferWriter.Length]; bufferWriter.CopyTo(data); Assert.Equal(input, data); Array.Clear(data, 0, data.Length); destination.CopyTo(data); Assert.Equal(input, data); } } } [Fact] public void CopyToWithSomeFullSegmentsWorks() { var inputSize = (MinimumSegmentSize * 2) + 1; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(input.Length, bufferWriter.Length); using (var destination = new MemoryBufferWriter()) { bufferWriter.CopyTo(destination); var data = destination.ToArray(); Assert.Equal(input, data); } } } [Fact] public void CopyToWithSomeFullSegmentsWorks_CopyTo() { var inputSize = (MinimumSegmentSize * 2) + 1; var input = Enumerable.Range(0, inputSize).Select(i => (byte)i).ToArray(); using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { bufferWriter.Write(input, 0, input.Length); Assert.Equal(input.Length, bufferWriter.Length); using (var destination = new MemoryBufferWriter()) { bufferWriter.CopyTo(destination); var data = new byte[bufferWriter.Length]; bufferWriter.CopyTo(data); Assert.Equal(input, data); Array.Clear(data, 0, data.Length); destination.CopyTo(data); Assert.Equal(input, data); } } } #if NETCOREAPP [Fact] public void WriteSpanWorksAtNonZeroOffset() { using (var bufferWriter = new MemoryBufferWriter()) { bufferWriter.WriteByte(1); bufferWriter.Write(new byte[] { 2, 3, 4 }.AsSpan()); Assert.Equal(4, bufferWriter.Length); var data = bufferWriter.ToArray(); Assert.Equal(4, data.Length); Assert.Equal(1, data[0]); Assert.Equal(2, data[1]); Assert.Equal(3, data[2]); Assert.Equal(4, data[3]); } } [Fact] public void WriteSpanWorksAtNonZeroOffset_CopyTo() { using (var bufferWriter = new MemoryBufferWriter()) { bufferWriter.WriteByte(1); bufferWriter.Write(new byte[] { 2, 3, 4 }.AsSpan()); Assert.Equal(4, bufferWriter.Length); var data = new byte[bufferWriter.Length]; bufferWriter.CopyTo(data); Assert.Equal(1, data[0]); Assert.Equal(2, data[1]); Assert.Equal(3, data[2]); Assert.Equal(4, data[3]); } } #endif [Fact] public void GetMemoryAllocatesNewSegmentWhenInsufficientSpaceInCurrentSegment() { // Have the buffer writer rent only the minimum size segments from the pool. using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { var data = new byte[MinimumSegmentSize]; Random.Shared.NextBytes(data); // Write half the minimum segment size bufferWriter.Write(data.AsSpan(0, MinimumSegmentSize / 2)); // Request a new buffer of MinimumSegmentSize var buffer = bufferWriter.GetMemory(MinimumSegmentSize); Assert.Equal(MinimumSegmentSize, buffer.Length); // Write to the buffer bufferWriter.Write(data); // Verify the data was all written correctly var expectedOutput = new byte[MinimumSegmentSize + (MinimumSegmentSize / 2)]; data.AsSpan(0, MinimumSegmentSize / 2).CopyTo(expectedOutput.AsSpan(0, MinimumSegmentSize / 2)); data.CopyTo(expectedOutput, MinimumSegmentSize / 2); Assert.Equal(expectedOutput, bufferWriter.ToArray()); } } [Fact] public void ResetResetsTheMemoryBufferWriter() { var bufferWriter = new MemoryBufferWriter(); bufferWriter.WriteByte(1); Assert.Equal(1, bufferWriter.Length); bufferWriter.Reset(); Assert.Equal(0, bufferWriter.Length); } [Fact] public void DisposeResetsTheMemoryBufferWriter() { var bufferWriter = new MemoryBufferWriter(); bufferWriter.WriteByte(1); Assert.Equal(1, bufferWriter.Length); bufferWriter.Dispose(); Assert.Equal(0, bufferWriter.Length); } } }
using System; using NUnit.Framework; namespace ZptSharp.Dom { [TestFixture,Parallelizable] public class NamespaceTests { #region Equals [Test, AutoMoqData] public void Equals_returns_true_for_itself(string uri, string prefix) { var namespace1 = new Namespace(prefix, uri); #pragma warning disable RECS0088 // Comparing equal expression for equality is usually useless Assert.That(() => namespace1.Equals(namespace1), Is.True); #pragma warning restore RECS0088 // Comparing equal expression for equality is usually useless } [Test, AutoMoqData] public void Equals_returns_false_for_null(string uri, string prefix) { var namespace1 = new Namespace(prefix, uri); Assert.That(() => namespace1.Equals(null), Is.False); } [Test, AutoMoqData] public void Equals_returns_true_for_a_namespace_with_the_same_uri_regardless_of_prefix(string uri) { var namespace1 = new Namespace("Foo", uri); var namespace2 = new Namespace("Bar", uri); Assert.That(() => namespace1.Equals(namespace2), Is.True); } [Test, AutoMoqData] public void Equals_returns_false_for_a_namespace_with_a_different_uri() { var namespace1 = new Namespace("Foo", "A URI"); var namespace2 = new Namespace("Bar", "Different URI"); Assert.That(() => namespace1.Equals(namespace2), Is.False); } [Test, AutoMoqData] public void Equals_returns_false_for_a_namespace_with_a_different_uri_even_when_prefixes_are_the_same(string prefix) { var namespace1 = new Namespace(prefix, "A URI"); var namespace2 = new Namespace(prefix, "Different URI"); Assert.That(() => namespace1.Equals(namespace2), Is.False); } [Test, AutoMoqData] public void Equals_returns_false_for_a_namespace_with_a_null_uri_if_the_first_namespace_uri_is_not_null(string uri, string prefix) { var namespace1 = new Namespace(prefix, uri); var namespace2 = new Namespace(prefix, null); Assert.That(() => namespace1.Equals(namespace2), Is.False); } [Test, AutoMoqData] public void Equals_returns_false_for_a_namespace_with_a_uri_if_the_first_namespace_uri_is_null(string uri, string prefix) { var namespace1 = new Namespace(prefix); var namespace2 = new Namespace(prefix, uri); Assert.That(() => namespace1.Equals(namespace2), Is.False); } [Test, AutoMoqData] public void Equals_returns_true_for_a_namespace_with_the_same_prefix_if_uris_are_both_null(string prefix) { var namespace1 = new Namespace(prefix); var namespace2 = new Namespace(prefix); Assert.That(() => namespace1.Equals(namespace2), Is.True); } [Test, AutoMoqData] public void Equals_returns_false_for_a_namespace_with_different_prefixes_if_uris_are_both_null() { var namespace1 = new Namespace("Foo"); var namespace2 = new Namespace("Bar"); Assert.That(() => namespace1.Equals(namespace2), Is.False); } [Test, AutoMoqData] public void Equals_returns_true_for_a_namespace_with_null_prefixes_if_uris_are_both_null() { var namespace1 = new Namespace(); var namespace2 = new Namespace(); Assert.That(() => namespace1.Equals(namespace2), Is.True); } [Test, AutoMoqData] public void Equals_returns_false_for_an_unrelated_object(object other) { var namespace1 = new Namespace(); Assert.That(() => namespace1.Equals(other), Is.False); } #endregion #region GetHashCode [Test, AutoMoqData] public void GetHashCode_returns_hash_code_of_uri_if_it_is_set(string uri) { var namespace1 = new Namespace(uri: uri); var expected = uri.GetHashCode(); Assert.That(() => namespace1.GetHashCode(), Is.EqualTo(expected)); } [Test, AutoMoqData] public void GetHashCode_returns_hash_code_of_uri_if_both_uri_and_prefix_are_set(string uri, string prefix) { var namespace1 = new Namespace(prefix, uri); var expected = uri.GetHashCode(); Assert.That(() => namespace1.GetHashCode(), Is.EqualTo(expected)); } [Test, AutoMoqData] public void GetHashCode_returns_hash_code_of_prefix_if_uri_is_null_but_prefix_is_set(string prefix) { var namespace1 = new Namespace(prefix); var expected = prefix.GetHashCode(); Assert.That(() => namespace1.GetHashCode(), Is.EqualTo(expected)); } [Test, AutoMoqData] public void GetHashCode_returns_zero_if_both_prefix_and_uri_are_null() { var namespace1 = new Namespace(); Assert.That(() => namespace1.GetHashCode(), Is.EqualTo(0)); } #endregion #region ToString [Test, AutoMoqData] public void ToString_returns_uri_if_it_is_set(string uri) { var namespace1 = new Namespace(uri: uri); Assert.That(() => namespace1.ToString(), Is.EqualTo(uri)); } [Test, AutoMoqData] public void ToString_returns_prefix_and_uri_if_both_are_set() { var namespace1 = new Namespace("Foo", "Bar"); Assert.That(() => namespace1.ToString(), Is.EqualTo("Foo:Bar")); } [Test, AutoMoqData] public void ToString_returns_prefix_if_uri_is_null_but_prefix_is_set(string prefix) { var namespace1 = new Namespace(prefix); Assert.That(() => namespace1.ToString(), Is.EqualTo(prefix)); } [Test, AutoMoqData] public void ToString_returns_empty_string_if_both_prefix_and_uri_are_null() { var namespace1 = new Namespace(); Assert.That(() => namespace1.ToString(), Is.Empty); } #endregion #region operators [Test, AutoMoqData] public void Operator_equals_returns_true_if_namespaces_are_equal(string uri) { var namespace1 = new Namespace(uri: uri); var namespace2 = new Namespace(uri: uri); Assert.That(() => namespace1 == namespace2, Is.True); } [Test, AutoMoqData] public void Operator_equals_returns_false_if_namespaces_are_not_equal() { var namespace1 = new Namespace(uri: "Foo"); var namespace2 = new Namespace(uri: "Bar"); Assert.That(() => namespace1 == namespace2, Is.False); } [Test, AutoMoqData] public void Operator_notequals_returns_false_if_namespaces_are_equal(string uri) { var namespace1 = new Namespace(uri: uri); var namespace2 = new Namespace(uri: uri); Assert.That(() => namespace1 != namespace2, Is.False); } [Test, AutoMoqData] public void Operator_notequals_returns_true_if_namespaces_are_not_equal() { var namespace1 = new Namespace(uri: "Foo"); var namespace2 = new Namespace(uri: "Bar"); Assert.That(() => namespace1 != namespace2, Is.True); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.IO { // A MemoryStream represents a Stream in memory (i.e, it has no backing store). // This stream may reduce the need for temporary buffers and files in // an application. // // There are two ways to create a MemoryStream. You can initialize one // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. private int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. [ContractPublicPropertyName("Length")] private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream // Note that _capacity == _buffer.Length for non-user-provided byte[]'s private bool _expandable; // User-provided buffers aren't expandable. private bool _writable; // Can user write to this stream? private bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? // <TODO>In V2, if we get support for arrays of more than 2 GB worth of elements, // consider removing this constraint, or setting it to Int64.MaxValue.</TODO> private const int MemStreamMaxLength = int.MaxValue; public MemoryStream() : this(0) { } public MemoryStream(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity); } _buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>(); _capacity = capacity; _expandable = true; _writable = true; _exposable = true; _origin = 0; // Must be 0 for byte[]'s created by MemoryStream _isOpen = true; } public MemoryStream(byte[] buffer) : this(buffer, true) { } public MemoryStream(byte[] buffer, bool writable) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; _exposable = false; _origin = 0; _isOpen = true; } public MemoryStream(byte[] buffer, int index, int count) : this(buffer, index, count, true, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable) : this(buffer, index, count, writable, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } _buffer = buffer; _origin = _position = index; _length = _capacity = index + count; _writable = writable; _exposable = publiclyVisible; // Can TryGetBuffer return the array? _expandable = false; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _writable; } } private void EnsureWriteable() { if (!CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } } protected override void Dispose(bool disposing) { try { if (disposing) { _isOpen = false; _writable = false; _expandable = false; // Don't set buffer to null - allow TryGetBuffer & ToArray to work. } } finally { // Call base.Close() to cleanup async IO resources base.Dispose(disposing); } } // returns a bool saying whether we allocated a new array. private bool EnsureCapacity(int value) { // Check for overflow if (value < 0) { throw new IOException(SR.IO_IO_StreamTooLong); } if (value > _capacity) { int newCapacity = value; if (newCapacity < 256) { newCapacity = 256; } if (newCapacity < _capacity * 2) { newCapacity = _capacity * 2; } Capacity = newCapacity; return true; } return false; } public override void Flush() { } #pragma warning disable 1998 //async method with no await operators public override async Task FlushAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Flush(); } #pragma warning restore 1998 public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) { if (!_exposable) { buffer = default(ArraySegment<byte>); return false; } buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin)); return true; } public virtual byte[] GetBuffer() { if (!_exposable) throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer); return _buffer; } // PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer()) internal byte[] InternalGetBuffer() { return _buffer; } // PERF: True cursor position, we don't need _origin for direct access internal int InternalGetPosition() { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _position; } // PERF: Takes out Int32 as fast as possible internal int InternalReadInt32() { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } int pos = (_position += 4); // use temp to avoid race if (pos > _length) { _position = _length; throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF); } return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24); } // PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes internal int InternalEmulateRead(int count) { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } int n = _length - _position; if (n > count) { n = count; } if (n < 0) { n = 0; } Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. _position += n; return n; } // Gets & sets the capacity (number of bytes allocated) for this stream. // The capacity cannot be set to a value less than the current length // of the stream. // public virtual int Capacity { get { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _capacity - _origin; } set { // Only update the capacity if the MS is expandable and the value is different than the current capacity. // Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity if (value < Length) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (!_expandable && (value != Capacity)) { throw new NotSupportedException(SR.NotSupported_MemStreamNotExpandable); } // MemoryStream has this invariant: _origin > 0 => !expandable (see ctors) if (_expandable && value != _capacity) { if (value > 0) { byte[] newBuffer = new byte[value]; if (_length > 0) { Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _length); } _buffer = newBuffer; } else { _buffer = null; } _capacity = value; } } } public override long Length { get { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _length - _origin; } } public override long Position { get { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _position - _origin; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (value > MemStreamMaxLength) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } _position = _origin + (int)value; } } public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } int n = _length - _position; if (n > count) { n = count; } if (n <= 0) { return 0; } Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. if (n <= 8) { int byteCount = n; while (--byteCount >= 0) buffer[offset + byteCount] = _buffer[_position + byteCount]; } else Buffer.BlockCopy(_buffer, _position, buffer, offset, n); _position += n; return n; } public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return ReadAsyncImpl(buffer, offset, count, cancellationToken); } #pragma warning disable 1998 //async method with no await operators private async Task<int> ReadAsyncImpl(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Read(buffer, offset, count); } #pragma warning restore 1998 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); public override int ReadByte() { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (_position >= _length) { return -1; } return _buffer[_position++]; } public override void CopyTo(Stream destination, int bufferSize) { // Since we did not originally override this method, validate the arguments // the same way Stream does for back-compat. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read) when we are not sure. if (GetType() != typeof(MemoryStream)) { base.CopyTo(destination, bufferSize); return; } int originalPosition = _position; // Seek to the end of the MemoryStream. int remaining = InternalEmulateRead(_length - originalPosition); // If we were already at or past the end, there's no copying to do so just quit. if (remaining > 0) { // Call Write() on the other Stream, using our internal buffer and avoiding any // intermediary allocations. destination.Write(_buffer, originalPosition, remaining); } } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // This implementation offers better performance compared to the base class version. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to ReadAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into ReadAsync) when we are not sure. if (GetType() != typeof(MemoryStream)) { return base.CopyToAsync(destination, bufferSize, cancellationToken); } return CopyToAsyncImpl(destination, bufferSize, cancellationToken); } private async Task CopyToAsyncImpl(Stream destination, int bufferSize, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Avoid copying data from this buffer into a temp buffer: // (require that InternalEmulateRead does not throw, // otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below) int pos = _position; int n = InternalEmulateRead(_length - _position); // If destination is not a memory stream, write there asynchronously: MemoryStream memStrDest = destination as MemoryStream; if (memStrDest == null) { await destination.WriteAsync(_buffer, pos, n, cancellationToken).ConfigureAwait(false); } else { memStrDest.Write(_buffer, pos, n); } } public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (offset > MemStreamMaxLength) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength); } switch (loc) { case SeekOrigin.Begin: { int tempPosition = unchecked(_origin + (int)offset); if (offset < 0 || tempPosition < _origin) { throw new IOException(SR.IO_IO_SeekBeforeBegin); } _position = tempPosition; break; } case SeekOrigin.Current: { int tempPosition = unchecked(_position + (int)offset); if (unchecked(_position + offset) < _origin || tempPosition < _origin) { throw new IOException(SR.IO_IO_SeekBeforeBegin); } _position = tempPosition; break; } case SeekOrigin.End: { int tempPosition = unchecked(_length + (int)offset); if (unchecked(_length + offset) < _origin || tempPosition < _origin) { throw new IOException(SR.IO_IO_SeekBeforeBegin); } _position = tempPosition; break; } default: throw new ArgumentException(SR.Argument_InvalidSeekOrigin); } Debug.Assert(_position >= 0, "_position >= 0"); return _position; } // Sets the length of the stream to a given value. The new // value must be nonnegative and less than the space remaining in // the array, Int32.MaxValue - origin // Origin is 0 in all cases other than a MemoryStream created on // top of an existing array and a specific starting offset was passed // into the MemoryStream constructor. The upper bounds prevents any // situations where a stream may be created on top of an array then // the stream is made longer than the maximum possible length of the // array (Int32.MaxValue). // public override void SetLength(long value) { if (value < 0 || value > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } EnsureWriteable(); // Origin wasn't publicly exposed above. Debug.Assert(MemStreamMaxLength == int.MaxValue); // Check parameter validation logic in this method if this fails. if (value > (int.MaxValue - _origin)) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } int newLength = _origin + (int)value; bool allocatedNewArray = EnsureCapacity(newLength); if (!allocatedNewArray && newLength > _length) { Array.Clear(_buffer, _length, newLength - _length); } _length = newLength; if (_position > newLength) { _position = newLength; } } public virtual byte[] ToArray() { //BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy."); int count = _length - _origin; if (count == 0) { return Array.Empty<byte>(); } byte[] copy = new byte[count]; Buffer.BlockCopy(_buffer, _origin, copy, 0, _length - _origin); return copy; } public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } EnsureWriteable(); int i = _position + count; // Check for overflow if (i < 0) { throw new IOException(SR.IO_IO_StreamTooLong); } if (i > _length) { bool mustZero = _position > _length; if (i > _capacity) { bool allocatedNewArray = EnsureCapacity(i); if (allocatedNewArray) { mustZero = false; } } if (mustZero) { Array.Clear(_buffer, _length, i - _length); } _length = i; } if ((count <= 8) && (buffer != _buffer)) { int byteCount = count; while (--byteCount >= 0) { _buffer[_position + byteCount] = buffer[offset + byteCount]; } } else { Buffer.BlockCopy(buffer, offset, _buffer, _position, count); } _position = i; } public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return WriteAsyncImpl(buffer, offset, count, cancellationToken); } #pragma warning disable 1998 //async method with no await operators private async Task WriteAsyncImpl(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Write(buffer, offset, count); } #pragma warning restore 1998 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override void WriteByte(byte value) { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } EnsureWriteable(); if (_position >= _length) { int newLength = _position + 1; bool mustZero = _position > _length; if (newLength >= _capacity) { bool allocatedNewArray = EnsureCapacity(newLength); if (allocatedNewArray) { mustZero = false; } } if (mustZero) { Array.Clear(_buffer, _length, _position - _length); } _length = newLength; } _buffer[_position++] = value; } // Writes this MemoryStream to another stream. public virtual void WriteTo(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } stream.Write(_buffer, _origin, _length - _origin); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace WebAPIConnectWithChrist.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Reactive.Linq; using Avalonia.Input.TextInput; using Avalonia.Media; using Avalonia.Metadata; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Layout; using Avalonia.Media.Immutable; namespace Avalonia.Controls.Presenters { public class TextPresenter : Control { public static readonly DirectProperty<TextPresenter, int> CaretIndexProperty = TextBox.CaretIndexProperty.AddOwner<TextPresenter>( o => o.CaretIndex, (o, v) => o.CaretIndex = v); public static readonly StyledProperty<bool> RevealPasswordProperty = AvaloniaProperty.Register<TextPresenter, bool>(nameof(RevealPassword)); public static readonly StyledProperty<char> PasswordCharProperty = AvaloniaProperty.Register<TextPresenter, char>(nameof(PasswordChar)); public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(SelectionBrushProperty)); public static readonly StyledProperty<IBrush> SelectionForegroundBrushProperty = AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(SelectionForegroundBrushProperty)); public static readonly StyledProperty<IBrush> CaretBrushProperty = AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(CaretBrushProperty)); public static readonly DirectProperty<TextPresenter, int> SelectionStartProperty = TextBox.SelectionStartProperty.AddOwner<TextPresenter>( o => o.SelectionStart, (o, v) => o.SelectionStart = v); public static readonly DirectProperty<TextPresenter, int> SelectionEndProperty = TextBox.SelectionEndProperty.AddOwner<TextPresenter>( o => o.SelectionEnd, (o, v) => o.SelectionEnd = v); /// <summary> /// Defines the <see cref="Text"/> property. /// </summary> public static readonly DirectProperty<TextPresenter, string> TextProperty = AvaloniaProperty.RegisterDirect<TextPresenter, string>( nameof(Text), o => o.Text, (o, v) => o.Text = v); /// <summary> /// Defines the <see cref="TextAlignment"/> property. /// </summary> public static readonly StyledProperty<TextAlignment> TextAlignmentProperty = TextBlock.TextAlignmentProperty.AddOwner<TextPresenter>(); /// <summary> /// Defines the <see cref="TextWrapping"/> property. /// </summary> public static readonly StyledProperty<TextWrapping> TextWrappingProperty = TextBlock.TextWrappingProperty.AddOwner<TextPresenter>(); /// <summary> /// Defines the <see cref="Background"/> property. /// </summary> public static readonly StyledProperty<IBrush> BackgroundProperty = Border.BackgroundProperty.AddOwner<TextPresenter>(); private readonly DispatcherTimer _caretTimer; private int _caretIndex; private int _selectionStart; private int _selectionEnd; private bool _caretBlink; private string _text; private FormattedText _formattedText; private Size _constraint; static TextPresenter() { AffectsRender<TextPresenter>(SelectionBrushProperty, TextBlock.ForegroundProperty, SelectionForegroundBrushProperty, CaretBrushProperty, SelectionStartProperty, SelectionEndProperty); AffectsMeasure<TextPresenter>(TextProperty, PasswordCharProperty, RevealPasswordProperty, TextAlignmentProperty, TextWrappingProperty, TextBlock.FontSizeProperty, TextBlock.FontStyleProperty, TextBlock.FontWeightProperty, TextBlock.FontFamilyProperty); Observable.Merge<AvaloniaPropertyChangedEventArgs>(TextProperty.Changed, TextBlock.ForegroundProperty.Changed, TextAlignmentProperty.Changed, TextWrappingProperty.Changed, TextBlock.FontSizeProperty.Changed, TextBlock.FontStyleProperty.Changed, TextBlock.FontWeightProperty.Changed, TextBlock.FontFamilyProperty.Changed, SelectionStartProperty.Changed, SelectionEndProperty.Changed, SelectionForegroundBrushProperty.Changed, PasswordCharProperty.Changed, RevealPasswordProperty.Changed ).AddClassHandler<TextPresenter>((x, _) => x.InvalidateFormattedText()); CaretIndexProperty.Changed.AddClassHandler<TextPresenter>((x, e) => x.CaretIndexChanged((int)e.NewValue)); } public TextPresenter() { _text = string.Empty; _caretTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) }; _caretTimer.Tick += CaretTimerTick; } /// <summary> /// Gets or sets a brush used to paint the control's background. /// </summary> public IBrush Background { get => GetValue(BackgroundProperty); set => SetValue(BackgroundProperty, value); } /// <summary> /// Gets or sets the text. /// </summary> [Content] public string Text { get => _text; set => SetAndRaise(TextProperty, ref _text, value); } /// <summary> /// Gets or sets the font family. /// </summary> public FontFamily FontFamily { get => TextBlock.GetFontFamily(this); set => TextBlock.SetFontFamily(this, value); } /// <summary> /// Gets or sets the font size. /// </summary> public double FontSize { get => TextBlock.GetFontSize(this); set => TextBlock.SetFontSize(this, value); } /// <summary> /// Gets or sets the font style. /// </summary> public FontStyle FontStyle { get => TextBlock.GetFontStyle(this); set => TextBlock.SetFontStyle(this, value); } /// <summary> /// Gets or sets the font weight. /// </summary> public FontWeight FontWeight { get => TextBlock.GetFontWeight(this); set => TextBlock.SetFontWeight(this, value); } /// <summary> /// Gets or sets a brush used to paint the text. /// </summary> public IBrush Foreground { get => TextBlock.GetForeground(this); set => TextBlock.SetForeground(this, value); } /// <summary> /// Gets or sets the control's text wrapping mode. /// </summary> public TextWrapping TextWrapping { get => GetValue(TextWrappingProperty); set => SetValue(TextWrappingProperty, value); } /// <summary> /// Gets or sets the text alignment. /// </summary> public TextAlignment TextAlignment { get => GetValue(TextAlignmentProperty); set => SetValue(TextAlignmentProperty, value); } /// <summary> /// Gets the <see cref="FormattedText"/> used to render the text. /// </summary> public FormattedText FormattedText { get { return _formattedText ?? (_formattedText = CreateFormattedText()); } } public int CaretIndex { get { return _caretIndex; } set { value = CoerceCaretIndex(value); SetAndRaise(CaretIndexProperty, ref _caretIndex, value); } } public char PasswordChar { get => GetValue(PasswordCharProperty); set => SetValue(PasswordCharProperty, value); } public bool RevealPassword { get => GetValue(RevealPasswordProperty); set => SetValue(RevealPasswordProperty, value); } public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } public IBrush SelectionForegroundBrush { get => GetValue(SelectionForegroundBrushProperty); set => SetValue(SelectionForegroundBrushProperty, value); } public IBrush CaretBrush { get => GetValue(CaretBrushProperty); set => SetValue(CaretBrushProperty, value); } public int SelectionStart { get { return _selectionStart; } set { value = CoerceCaretIndex(value); SetAndRaise(SelectionStartProperty, ref _selectionStart, value); } } public int SelectionEnd { get { return _selectionEnd; } set { value = CoerceCaretIndex(value); SetAndRaise(SelectionEndProperty, ref _selectionEnd, value); } } public int GetCaretIndex(Point point) { var hit = FormattedText.HitTestPoint(point); return hit.TextPosition + (hit.IsTrailing ? 1 : 0); } /// <summary> /// Creates the <see cref="FormattedText"/> used to render the text. /// </summary> /// <param name="constraint">The constraint of the text.</param> /// <param name="text">The text to format.</param> /// <returns>A <see cref="FormattedText"/> object.</returns> private FormattedText CreateFormattedTextInternal(Size constraint, string text) { return new FormattedText { Constraint = constraint, Typeface = new Typeface(FontFamily, FontStyle, FontWeight), FontSize = FontSize, Text = text ?? string.Empty, TextAlignment = TextAlignment, TextWrapping = TextWrapping, }; } /// <summary> /// Invalidates <see cref="FormattedText"/>. /// </summary> protected void InvalidateFormattedText() { _formattedText = null; } /// <summary> /// Renders the <see cref="TextPresenter"/> to a drawing context. /// </summary> /// <param name="context">The drawing context.</param> private void RenderInternal(DrawingContext context) { var background = Background; if (background != null) { context.FillRectangle(background, new Rect(Bounds.Size)); } double top = 0; var textSize = FormattedText.Bounds.Size; if (Bounds.Height < textSize.Height) { switch (VerticalAlignment) { case VerticalAlignment.Center: top += (Bounds.Height - textSize.Height) / 2; break; case VerticalAlignment.Bottom: top += (Bounds.Height - textSize.Height); break; } } context.DrawText(Foreground, new Point(0, top), FormattedText); } public override void Render(DrawingContext context) { FormattedText.Constraint = Bounds.Size; _constraint = Bounds.Size; var selectionStart = SelectionStart; var selectionEnd = SelectionEnd; if (selectionStart != selectionEnd) { var start = Math.Min(selectionStart, selectionEnd); var length = Math.Max(selectionStart, selectionEnd) - start; var rects = FormattedText.HitTestTextRange(start, length); foreach (var rect in rects) { context.FillRectangle(SelectionBrush, rect); } } RenderInternal(context); if (selectionStart == selectionEnd && _caretBlink) { var caretBrush = CaretBrush?.ToImmutable(); if (caretBrush is null) { var backgroundColor = (Background as ISolidColorBrush)?.Color; if (backgroundColor.HasValue) { byte red = (byte)~(backgroundColor.Value.R); byte green = (byte)~(backgroundColor.Value.G); byte blue = (byte)~(backgroundColor.Value.B); caretBrush = new ImmutableSolidColorBrush(Color.FromRgb(red, green, blue)); } else { caretBrush = Brushes.Black; } } var (p1, p2) = GetCaretPoints(); context.DrawLine( new ImmutablePen(caretBrush, 1), p1, p2); } } (Point, Point) GetCaretPoints() { var charPos = FormattedText.HitTestTextPosition(CaretIndex); var x = Math.Floor(charPos.X) + 0.5; var y = Math.Floor(charPos.Y) + 0.5; var b = Math.Ceiling(charPos.Bottom) - 0.5; return (new Point(x, y), new Point(x, b)); } public void ShowCaret() { _caretBlink = true; _caretTimer.Start(); InvalidateVisual(); } public void HideCaret() { _caretBlink = false; _caretTimer.Stop(); InvalidateVisual(); } internal void CaretIndexChanged(int caretIndex) { if (this.GetVisualParent() != null) { if (_caretTimer.IsEnabled) { _caretBlink = true; _caretTimer.Stop(); _caretTimer.Start(); InvalidateVisual(); } else { _caretTimer.Start(); InvalidateVisual(); _caretTimer.Stop(); } if (IsMeasureValid) { var rect = FormattedText.HitTestTextPosition(caretIndex); this.BringIntoView(rect); } else { // The measure is currently invalid so there's no point trying to bring the // current char into view until a measure has been carried out as the scroll // viewer extents may not be up-to-date. Dispatcher.UIThread.Post( () => { var rect = FormattedText.HitTestTextPosition(caretIndex); this.BringIntoView(rect); }, DispatcherPriority.Render); } } } /// <summary> /// Creates the <see cref="FormattedText"/> used to render the text. /// </summary> /// <returns>A <see cref="FormattedText"/> object.</returns> protected virtual FormattedText CreateFormattedText() { FormattedText result = null; var text = Text; if (PasswordChar != default(char) && !RevealPassword) { result = CreateFormattedTextInternal(_constraint, new string(PasswordChar, text?.Length ?? 0)); } else { result = CreateFormattedTextInternal(_constraint, text); } var selectionStart = SelectionStart; var selectionEnd = SelectionEnd; var start = Math.Min(selectionStart, selectionEnd); var length = Math.Max(selectionStart, selectionEnd) - start; if (length > 0) { result.Spans = new[] { new FormattedTextStyleSpan(start, length, SelectionForegroundBrush), }; } return result; } /// <summary> /// Measures the control. /// </summary> /// <param name="availableSize">The available size for the control.</param> /// <returns>The desired size.</returns> private Size MeasureInternal(Size availableSize) { if (!string.IsNullOrEmpty(Text)) { if (TextWrapping == TextWrapping.Wrap) { _constraint = new Size(availableSize.Width, double.PositiveInfinity); } else { _constraint = Size.Infinity; } _formattedText = null; return FormattedText.Bounds.Size; } return new Size(); } protected override Size MeasureOverride(Size availableSize) { var text = Text; if (!string.IsNullOrEmpty(text)) { return MeasureInternal(availableSize); } else { return new FormattedText { Text = "X", Typeface = new Typeface(FontFamily, FontStyle, FontWeight), FontSize = FontSize, TextAlignment = TextAlignment, Constraint = availableSize, }.Bounds.Size; } } private int CoerceCaretIndex(int value) { var text = Text; var length = text?.Length ?? 0; return Math.Max(0, Math.Min(length, value)); } private void CaretTimerTick(object sender, EventArgs e) { _caretBlink = !_caretBlink; InvalidateVisual(); } internal Rect GetCursorRectangle() { var (p1, p2) = GetCaretPoints(); return new Rect(p1, p2); } } }
//! \file Encryption.cs //! \date Sat Oct 01 22:25:09 2016 //! \brief Encryption used in Primel the Adventure System. // // Copyright (C) 2016 by morkt // // 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.Security.Cryptography; using System.Linq; using GameRes.Utility; namespace GameRes.Formats.Primel { internal abstract class PrimelEncyptionBase : ICryptoTransform { internal const int BlockSize = 16; public bool CanTransformMultipleBlocks { get { return true; } } public bool CanReuseTransform { get { return false; } } public int InputBlockSize { get { return BlockSize; } } public int OutputBlockSize { get { return BlockSize; } } #region Static tables internal static readonly uint[] DefaultKey = { 0x243F6A89, 0xB7E15163, 0x9E3779B9, 0x6F2DEC55, 0x6A09E668, 0xBB67AE86, 0xB504F334, 0x93CD3A2D, }; internal static readonly byte[,] CodeTable = new byte[4,256] { { 0x29, 0x4e, 0xf8, 0x6c, 0x4d, 0xd1, 0x52, 0x5b, 0x2f, 0x4b, 0xe5, 0x0a, 0xa4, 0xbb, 0xf7, 0xdf, 0x9f, 0x8c, 0x27, 0xb9, 0x25, 0xfd, 0x07, 0x4a, 0x7c, 0x81, 0x10, 0x26, 0x46, 0x11, 0xa3, 0xdb, 0x39, 0x08, 0x55, 0x36, 0x96, 0xc4, 0x5c, 0xfe, 0x2e, 0x66, 0xa6, 0x74, 0x45, 0x60, 0xf3, 0x83, 0x72, 0x3f, 0xc5, 0x99, 0x0d, 0x16, 0x3d, 0x6d, 0x5d, 0x57, 0xae, 0x35, 0xde, 0x8e, 0xa0, 0x41, 0x8b, 0x34, 0xd7, 0xe3, 0xbe, 0x33, 0xb0, 0x44, 0xeb, 0xec, 0xff, 0x91, 0x6e, 0x85, 0x9d, 0x12, 0xaf, 0x8d, 0xe9, 0xba, 0x1c, 0x05, 0xee, 0x3a, 0x03, 0xfa, 0x7b, 0x23, 0xd4, 0x8a, 0xd9, 0x67, 0xca, 0x97, 0x02, 0x70, 0xd8, 0xfc, 0xe4, 0x78, 0x73, 0x19, 0x5e, 0x77, 0x59, 0x69, 0xe0, 0xd6, 0x14, 0x37, 0x00, 0x6b, 0x13, 0x17, 0x0f, 0x49, 0xaa, 0x22, 0x89, 0xe1, 0x7a, 0xad, 0x6a, 0x30, 0x2b, 0xb4, 0xfb, 0xb6, 0x88, 0xf0, 0x7e, 0xa1, 0x18, 0xe7, 0xd2, 0x3c, 0x9a, 0x84, 0xa7, 0x54, 0x40, 0x64, 0x90, 0x9b, 0x3e, 0x6f, 0xcf, 0x80, 0xf4, 0x93, 0x75, 0x1b, 0x51, 0xd3, 0x79, 0xe2, 0x42, 0x15, 0xe8, 0xb3, 0x0b, 0x9e, 0x31, 0xda, 0xac, 0x50, 0x7d, 0x87, 0xea, 0xdd, 0x04, 0x56, 0xc9, 0x28, 0x1e, 0x94, 0x63, 0x47, 0x8f, 0xc6, 0x1a, 0xc7, 0xf1, 0xf2, 0x71, 0xce, 0x1d, 0x53, 0x06, 0x0c, 0xdc, 0x82, 0x48, 0xbc, 0xcb, 0xa2, 0xab, 0x4f, 0x98, 0xb2, 0xcd, 0x1f, 0xa8, 0x3b, 0xef, 0xf5, 0x58, 0x20, 0xb8, 0xc0, 0xc1, 0x21, 0x2c, 0x86, 0x32, 0xa9, 0x2d, 0xc3, 0xbd, 0x62, 0xb7, 0x76, 0x95, 0xd5, 0x9c, 0x68, 0xe6, 0x92, 0x2a, 0xc8, 0x43, 0x4c, 0x0e, 0x7f, 0x01, 0x5f, 0xd0, 0x38, 0x65, 0x61, 0x24, 0xb1, 0xf6, 0xcc, 0xbf, 0xc2, 0x5a, 0x09, 0xb5, 0xed, 0xa5, 0xf9, }, { 0xc5, 0xe6, 0xf6, 0x06, 0x9b, 0x77, 0xb8, 0x61, 0x95, 0x14, 0x6c, 0x01, 0xe5, 0xc8, 0xd3, 0x20, 0xfe, 0x73, 0xec, 0x3b, 0xcb, 0x07, 0xa3, 0x28, 0xde, 0x99, 0x2a, 0xc0, 0x90, 0x42, 0x10, 0x0a, 0x19, 0x16, 0xcc, 0xc3, 0x92, 0x86, 0x4b, 0x80, 0xc1, 0xae, 0xd1, 0x9f, 0x2f, 0x41, 0xe9, 0x63, 0x6e, 0x22, 0x55, 0x9c, 0x5d, 0x81, 0xa2, 0xb4, 0x0d, 0xa0, 0x4a, 0xdd, 0xd8, 0x54, 0x39, 0xfd, 0x8f, 0x49, 0xdc, 0x6d, 0x1e, 0x36, 0x02, 0xb3, 0x52, 0x85, 0x21, 0xe1, 0xdb, 0xe3, 0x23, 0x33, 0x00, 0x12, 0x04, 0x7f, 0x98, 0x79, 0xc6, 0x60, 0x8e, 0x03, 0x3c, 0x1c, 0xfb, 0x09, 0x6f, 0xad, 0x6b, 0xbb, 0x18, 0x3a, 0xbc, 0xf8, 0x3d, 0x9e, 0x9d, 0x26, 0xda, 0xff, 0xaf, 0xa5, 0xaa, 0x3f, 0x5b, 0x71, 0xa1, 0x70, 0xee, 0x4f, 0x68, 0xb0, 0x13, 0xd5, 0x87, 0x4d, 0x35, 0xf5, 0xa8, 0x17, 0xd4, 0xf1, 0x40, 0x57, 0x59, 0x1a, 0x93, 0x47, 0xbf, 0x05, 0x67, 0x8c, 0x1b, 0x69, 0x25, 0xc9, 0xbe, 0x5c, 0xea, 0x74, 0xc4, 0x2d, 0x38, 0xce, 0x5a, 0xe4, 0x94, 0x30, 0xc7, 0x65, 0x5f, 0x64, 0x7e, 0xe7, 0xd7, 0x8a, 0x0c, 0x2e, 0x9a, 0x82, 0xcf, 0x2b, 0x62, 0xf3, 0xb7, 0xcd, 0x3e, 0xf4, 0xbd, 0x83, 0xac, 0x0b, 0x7b, 0x45, 0xf9, 0x75, 0x32, 0xa4, 0x50, 0x58, 0xca, 0x78, 0xf7, 0xb6, 0x84, 0x51, 0x31, 0xab, 0x56, 0x11, 0x72, 0x76, 0xd9, 0x29, 0x43, 0x15, 0x4c, 0xe2, 0xe0, 0x4e, 0x89, 0x7a, 0xfa, 0x44, 0x6a, 0x91, 0xba, 0xb9, 0x7d, 0x2c, 0x46, 0x8b, 0xb1, 0x66, 0xdf, 0x08, 0x8d, 0xd6, 0xef, 0xd0, 0xb5, 0xa9, 0xeb, 0xfc, 0xed, 0x88, 0x7c, 0xf0, 0x27, 0x53, 0xe8, 0x96, 0x24, 0x5e, 0xd2, 0x1d, 0x0e, 0x48, 0x34, 0xa7, 0x1f, 0xc2, 0x0f, 0x37, 0xf2, 0xa6, 0xb2, 0x97, }, { 0xe7, 0xf2, 0x6f, 0xcd, 0x4b, 0x52, 0xbc, 0x8b, 0xd1, 0x14, 0x68, 0xac, 0xd2, 0x92, 0x9f, 0x78, 0x4f, 0x59, 0x47, 0x15, 0x02, 0x79, 0x53, 0x93, 0x8d, 0x94, 0x03, 0x9e, 0x3e, 0x72, 0x19, 0x48, 0x89, 0x0f, 0x27, 0xd7, 0xe6, 0xaf, 0x91, 0x39, 0x9b, 0x44, 0xa8, 0xfe, 0x18, 0xa5, 0x8c, 0x42, 0x7c, 0x74, 0xea, 0x9c, 0x97, 0xe9, 0xdf, 0x65, 0x2e, 0xfb, 0xd6, 0xda, 0x5d, 0x49, 0x9d, 0x04, 0x81, 0xb2, 0xe4, 0x6c, 0x8f, 0xf7, 0x4d, 0x85, 0xa9, 0xb5, 0xce, 0xbf, 0xbe, 0xe3, 0x50, 0x21, 0x54, 0x46, 0xb6, 0x16, 0xef, 0x1e, 0x08, 0xcc, 0x6b, 0x35, 0xab, 0x7b, 0xc7, 0xa1, 0xc5, 0x90, 0x20, 0x63, 0x55, 0x1c, 0xc3, 0xb8, 0x3c, 0x3a, 0x29, 0xd5, 0x0b, 0x41, 0x5c, 0xc0, 0x57, 0x05, 0x0c, 0x0a, 0x4e, 0xa2, 0xfd, 0x28, 0x9a, 0x70, 0xdc, 0x51, 0x2a, 0xb4, 0x8e, 0x7e, 0x34, 0x10, 0xc1, 0x25, 0x4c, 0xe2, 0x6e, 0x84, 0x1d, 0x61, 0x17, 0xb3, 0x6d, 0xc2, 0x43, 0xeb, 0x24, 0x83, 0xff, 0x1b, 0x76, 0xae, 0x67, 0x87, 0x5a, 0x69, 0x58, 0xcb, 0x32, 0xdd, 0x26, 0x3f, 0x96, 0x5f, 0x82, 0x5e, 0x01, 0x7a, 0x2d, 0xf9, 0xf5, 0xf0, 0xad, 0x37, 0x45, 0xf8, 0x31, 0x38, 0x88, 0x75, 0x36, 0x7f, 0x64, 0x5b, 0x1a, 0xbd, 0xe0, 0xfa, 0x11, 0xb9, 0x33, 0xa3, 0x6a, 0x23, 0xf6, 0xdb, 0x66, 0x71, 0xf3, 0x77, 0x1f, 0xcf, 0x22, 0x3b, 0xe8, 0xec, 0x95, 0x98, 0x99, 0xd3, 0xca, 0x40, 0xb1, 0x30, 0x12, 0x3d, 0xa7, 0x06, 0x0d, 0xbb, 0xed, 0x07, 0xd4, 0xc4, 0x7d, 0xf1, 0xe1, 0xa4, 0x13, 0xa0, 0xde, 0x80, 0xc6, 0x2c, 0xba, 0x0e, 0xc8, 0xd9, 0xd0, 0x00, 0xee, 0xb0, 0x86, 0xaa, 0xfc, 0x73, 0xd8, 0xa6, 0x56, 0x2f, 0x2b, 0xb7, 0x09, 0x4a, 0xf4, 0xe5, 0x62, 0x8a, 0x60, 0xc9, }, { 0x7a, 0x26, 0x6e, 0x12, 0x08, 0x7e, 0xe6, 0x15, 0xe8, 0x0e, 0x3d, 0x6a, 0x29, 0x5a, 0x45, 0xe4, 0x2f, 0x86, 0x5f, 0x76, 0xdf, 0xea, 0x09, 0xc5, 0x83, 0x16, 0xeb, 0xa0, 0x23, 0x9f, 0xd7, 0x30, 0x02, 0x79, 0x81, 0xaf, 0x97, 0x58, 0xd4, 0xba, 0xd5, 0xb1, 0x73, 0x6c, 0x2a, 0xab, 0x2e, 0x7b, 0x34, 0xd9, 0xf8, 0xb2, 0x67, 0xb6, 0x7d, 0xf3, 0x1e, 0xc1, 0x5c, 0xb7, 0x88, 0xf2, 0x0d, 0x1a, 0x8a, 0x5b, 0x55, 0xa8, 0xee, 0x78, 0x70, 0xed, 0x7c, 0xf9, 0xf6, 0xd3, 0x50, 0xbd, 0x56, 0xdc, 0x38, 0x21, 0xbc, 0x9b, 0x03, 0xf0, 0xe1, 0x04, 0x8f, 0x6d, 0x31, 0xc9, 0x8d, 0xfb, 0xbe, 0x14, 0x54, 0x3f, 0x91, 0x35, 0x72, 0xa7, 0xe9, 0x19, 0xfa, 0x17, 0xb8, 0x9d, 0xde, 0x24, 0x25, 0xa1, 0xdb, 0xcb, 0xcc, 0x39, 0xa5, 0xe0, 0xef, 0x57, 0x85, 0xbf, 0x49, 0x1b, 0x7f, 0x3b, 0x65, 0xc3, 0x77, 0x00, 0x10, 0x59, 0xb3, 0xc6, 0x95, 0x1c, 0x60, 0x5d, 0x41, 0xaa, 0x51, 0x71, 0xd6, 0x99, 0x1f, 0x52, 0x82, 0xcd, 0x2b, 0xd1, 0x61, 0xb9, 0x43, 0x63, 0x69, 0x46, 0xa2, 0x47, 0x8e, 0x36, 0x42, 0x87, 0xd8, 0xb4, 0xd2, 0x53, 0xec, 0x06, 0x6b, 0xc8, 0xe5, 0x33, 0x6f, 0x4b, 0x8b, 0x66, 0xe3, 0x74, 0xfe, 0x4d, 0xad, 0x28, 0x48, 0xe2, 0x90, 0xf5, 0x84, 0xb0, 0xda, 0xd0, 0x20, 0xac, 0xdd, 0x75, 0x92, 0xca, 0xf7, 0x2d, 0x3a, 0x9c, 0x0a, 0xb5, 0xc4, 0x07, 0x5e, 0x13, 0x05, 0xbb, 0x0c, 0xff, 0xa4, 0xf1, 0x27, 0x4e, 0xa3, 0x98, 0x11, 0xa9, 0x96, 0x93, 0x68, 0x4f, 0xfc, 0x37, 0x80, 0x4a, 0xcf, 0x01, 0x9a, 0xc0, 0x1d, 0x3c, 0x8c, 0x4c, 0x3e, 0x0b, 0xc7, 0xa6, 0xae, 0x0f, 0x2c, 0x62, 0xf4, 0x94, 0xce, 0x89, 0x40, 0x22, 0xfd, 0x18, 0x32, 0xc2, 0x9e, 0x64, 0x44, 0xe7, } }; #endregion public abstract int TransformBlock (byte[] inBuffer, int offset, int count, byte[] outBuffer, int outOffset); public byte[] TransformFinalBlock (byte[] inBuffer, int offset, int count) { if (count < BlockSize) return new ArraySegment<byte> (inBuffer, offset, count).ToArray(); var output = new byte[count]; int tail = count / BlockSize * BlockSize; count -= TransformBlock (inBuffer, offset, count, output, 0); if (count > 0) Buffer.BlockCopy (inBuffer, offset+tail, output, tail, count); return output; } static protected uint MutateKey (uint k) { return (uint)CodeTable[0, k & 0xFF] | (uint)CodeTable[1, (k >> 8) & 0xFF] << 8 | (uint)CodeTable[2, (k >> 16) & 0xFF] << 16 | (uint)CodeTable[3, k >> 24] << 24; } #region IDisposable implementation bool _disposed = false; public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (!_disposed) { _disposed = true; } } #endregion } internal class Primel1Encyption : PrimelEncyptionBase { uint[] m_key = new uint[4]; byte[] m_iv; public Primel1Encyption (byte[] key, byte[] iv) { m_iv = iv.Clone() as byte[]; Buffer.BlockCopy (key, 0, m_key, 0, 0x10); uint k = 0; for (int i = 0; i < 0x10; ++i) { k = m_key[i & 3] ^ (k + DefaultKey[i & 7]); m_key[i & 3] = MutateKey (k); } } public override int TransformBlock (byte[] inBuffer, int offset, int count, byte[] outBuffer, int outOffset) { int out_count = count / BlockSize; for (int i = 0; i < out_count; ++i) { Transform (inBuffer, offset, outBuffer, outOffset); for (int j = 0; j < BlockSize; ++j) { outBuffer[outOffset++] ^= m_iv[j]; } Buffer.BlockCopy (inBuffer, offset, m_iv, 0, BlockSize); offset += BlockSize; } return out_count * BlockSize; } private void Transform (byte[] input, int src, byte[] output, int dst) { for (int k = 0; k < BlockSize / 4; ++k) { uint v = LittleEndian.ToUInt32 (input, src); v ^= m_key[(k - 1) & 3]; v -= m_key[(k - 2) & 3]; v ^= m_key[(k - 3) & 3]; v -= m_key[(k - 4) & 3]; LittleEndian.Pack (v, output, dst); src += 4; dst += 4; } } } internal class Primel2Encyption : PrimelEncyptionBase { int[] m_shifts = new int[8]; uint[] m_key = new uint[4]; byte[] m_iv; public Primel2Encyption (byte[] key, byte[] iv) { m_iv = iv.Clone() as byte[]; Buffer.BlockCopy (key, 0, m_key, 0, 0x10); uint k = 0; for (int i = 0; i < 0x10; ++i) { k = m_key[i & 3] ^ (k + DefaultKey[(i + 3) & 7]); m_key[i & 3] = MutateKey (k); } for (int i = 0; i < 4; ++i) { uint x = m_key[i]; x = (x & 0x55555555) + ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F); x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF); int s = (int)(x + (x >> 16)); m_shifts[i + 4] = (s ^ ((s + i) >> 1)) & 0xF; m_shifts[i] = (s + i) & 0x1F; } } public override int TransformBlock (byte[] inBuffer, int offset, int count, byte[] outBuffer, int outOffset) { int out_count = count / BlockSize; for (int i = 0; i < out_count; ++i) { Transform (inBuffer, offset, outBuffer, outOffset); for (int j = 0; j < BlockSize; ++j) { outBuffer[outOffset++] ^= m_iv[j]; } Buffer.BlockCopy (inBuffer, offset, m_iv, 0, BlockSize); offset += BlockSize; } return out_count * BlockSize; } private void Transform (byte[] input, int src, byte[] output, int dst) { for (int k = 0; k < BlockSize / 4; ++k) { int i = (k - 1) & 3; int j = (k - 2) & 3; int m = (k - 3) & 3; int n = (k - 4) & 3; uint v = LittleEndian.ToUInt32 (input, src); v = Binary.RotR (v, m_shifts[i]) + m_key[i]; v = Binary.RotR (v ^ m_key[j], m_shifts[j]); v = Binary.RotR (v, m_shifts[m]) - m_key[m]; v = Binary.RotR (v ^ m_key[n], m_shifts[n]); LittleEndian.Pack (v, output, dst); src += 4; dst += 4; } } } internal class Primel3Encyption : PrimelEncyptionBase { int[] m_shifts = new int[8]; int[] m_offsets = new int[4]; uint[] m_key = new uint[8]; byte[] m_iv; public Primel3Encyption (byte[] key, byte[] iv) { m_iv = iv.Clone() as byte[]; Buffer.BlockCopy (key, 0, m_key, 0, 0x10); uint k = 0; for (int i = 0; i < 0x20; ++i) { k = m_key[i & 7] ^ (k + DefaultKey[(i - 3) & 7]); m_key[i & 7] = MutateKey (k); m_offsets[i & 3] = (int)(k >> 7) & 0xF; } for (int i = 0; i < 8; ++i) { uint x = m_key[i]; x = (x & 0x55555555) + ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F); x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF); int s = (int)(x + (x >> 16)); m_shifts[i] = (s + i) & 0x1F; } } public override int TransformBlock (byte[] inBuffer, int offset, int count, byte[] outBuffer, int outOffset) { int out_count = count / BlockSize; for (int i = 0; i < out_count; ++i) { Buffer.BlockCopy (inBuffer, offset, outBuffer, outOffset, BlockSize); for (int j = 7; j >= 0; --j) { Transform (outBuffer, outOffset, j); } for (int j = 0; j < BlockSize; ++j) { outBuffer[outOffset++] ^= m_iv[j]; } Buffer.BlockCopy (inBuffer, offset, m_iv, 0, BlockSize); offset += BlockSize; } return out_count * BlockSize; } private void Transform (byte[] buf, int src, int i) { i &= 3; for (int k = BlockSize / 4 - 2; k >= 0; --k) { int pos = src + k * 4 + 2; uint v = LittleEndian.ToUInt32 (buf, pos); v = Binary.RotL (v + m_key[i + 4], m_shifts[i + 4]); LittleEndian.Pack (v ^ m_key[i], buf, pos); } int s = 8 * m_offsets[i] + 4; for (int k = BlockSize / 4 - 1; k >= 0; --k) { int pos = src + k * 4; uint v = LittleEndian.ToUInt32 (buf, pos); v = Binary.RotR (m_key[i + 4] ^ v, m_shifts[i]); uint u = ByteMap[Offsets[s], v & 0xFF]; u |= (uint)ByteMap[Offsets[s+1], (v >> 8) & 0xFF] << 8; u |= (uint)ByteMap[Offsets[s+2], (v >> 16) & 0xFF] << 16; u |= (uint)ByteMap[Offsets[s+3], v >> 24] << 24; u -= m_key[i]; LittleEndian.Pack (u, buf, pos); } } readonly static byte[] Offsets = { 3, 0, 6, 5, 2, 1, 7, 4, 2, 4, 0, 6, 3, 5, 1, 7, 3, 1, 7, 5, 2, 0, 6, 4, 0, 3, 6, 5, 1, 2, 7, 4, 3, 1, 4, 7, 2, 0, 5, 6, 6, 3, 4, 0, 7, 2, 5, 1, 4, 6, 2, 1, 5, 7, 3, 0, 6, 5, 2, 1, 7, 4, 3, 0, 6, 2, 4, 0, 7, 3, 5, 1, 7, 4, 2, 1, 6, 5, 3, 0, 5, 1, 3, 6, 4, 0, 2, 7, 1, 4, 6, 2, 0, 5, 7, 3, 6, 3, 1, 4, 7, 2, 0, 5, 7, 3, 5, 1, 6, 2, 4, 0, 3, 4, 6, 1, 2, 5, 7, 0, 5, 6, 1, 3, 4, 7, 0, 2, }; readonly static byte[,] ByteMap = new byte[8,256] { { 0x57, 0x38, 0x08, 0xE3, 0xCA, 0xDC, 0x8C, 0x62, 0x3C, 0x36, 0x0C, 0x5C, 0xC3, 0x63, 0x04, 0x77, 0x12, 0x51, 0x5F, 0x73, 0x94, 0x76, 0x0A, 0xB5, 0x1B, 0xD1, 0x32, 0xA6, 0xF5, 0xFF, 0x44, 0x4D, 0x02, 0x24, 0xA5, 0xBA, 0x59, 0xF2, 0x3A, 0x28, 0x5E, 0xEE, 0xE2, 0x98, 0xD4, 0x35, 0x90, 0xAE, 0x4A, 0x6A, 0x29, 0x78, 0xE6, 0xDD, 0x14, 0x43, 0xE0, 0x5D, 0x8E, 0x33, 0xBF, 0x5B, 0xED, 0xC1, 0x8B, 0x7E, 0x8A, 0x13, 0x1C, 0xC5, 0x79, 0x49, 0x2D, 0x9F, 0xA9, 0x6B, 0xC6, 0x58, 0x39, 0x68, 0xB3, 0xE1, 0x61, 0x9A, 0xAF, 0xC9, 0x74, 0x48, 0xE7, 0x1D, 0x82, 0x52, 0x56, 0xDA, 0x2F, 0xFE, 0xFD, 0xE9, 0x67, 0xBC, 0xD2, 0x2E, 0xA4, 0x10, 0x9D, 0xC8, 0x11, 0xCD, 0x86, 0x03, 0x64, 0x17, 0xF4, 0x15, 0x81, 0xA0, 0xD5, 0x1E, 0x89, 0x71, 0xCC, 0xD3, 0x47, 0x72, 0xFA, 0xD9, 0x93, 0x6F, 0x6D, 0x3E, 0x91, 0x00, 0x05, 0xB6, 0xE4, 0xC0, 0xB1, 0xC7, 0x7D, 0xBE, 0xBB, 0x01, 0x97, 0x70, 0x07, 0xD6, 0x0F, 0x9C, 0x87, 0xF1, 0xEF, 0x8F, 0xA8, 0x8D, 0x46, 0x42, 0xB0, 0x21, 0x6C, 0xAC, 0xF3, 0xAA, 0xF9, 0x66, 0x9B, 0xB4, 0xA1, 0x4B, 0xDF, 0x0E, 0xF8, 0x2A, 0x45, 0x41, 0xF6, 0x40, 0xB8, 0xE5, 0x96, 0x23, 0x53, 0x0D, 0x2C, 0x54, 0xAD, 0x60, 0x34, 0xDB, 0x7F, 0xD0, 0x85, 0xD7, 0xCE, 0x7C, 0x92, 0xBD, 0xCB, 0x4F, 0xC2, 0xAB, 0x3B, 0xA7, 0xEA, 0x84, 0x5A, 0xB9, 0x26, 0x1A, 0x18, 0xB2, 0xDE, 0x27, 0x7B, 0x3F, 0xB7, 0x19, 0x0B, 0x50, 0xD8, 0xF0, 0x37, 0x06, 0xFC, 0xA3, 0x9E, 0x3D, 0x2B, 0x22, 0x65, 0xEC, 0x95, 0xCF, 0x30, 0x6E, 0xA2, 0xC4, 0xEB, 0xFB, 0xF7, 0x1F, 0x99, 0x4E, 0x20, 0xE8, 0x75, 0x09, 0x4C, 0x88, 0x69, 0x80, 0x16, 0x31, 0x7A, 0x55, 0x25, 0x83, }, { 0x83, 0x8D, 0x20, 0x6D, 0x0E, 0x84, 0xDD, 0x90, 0x02, 0xF5, 0x16, 0xD8, 0x0A, 0xB5, 0xA9, 0x92, 0x67, 0x6A, 0x10, 0x43, 0x36, 0x71, 0xFA, 0x6F, 0xD0, 0xD7, 0xCF, 0x18, 0x44, 0x59, 0x75, 0xEF, 0xF2, 0x9D, 0xE3, 0xB3, 0x21, 0xFE, 0xCE, 0xD3, 0x27, 0x32, 0xAB, 0xE2, 0xB6, 0x48, 0x65, 0x5E, 0xE8, 0xFB, 0x1A, 0x3B, 0xBA, 0x2D, 0x09, 0xDC, 0x01, 0x4E, 0x26, 0xC8, 0x08, 0xE1, 0x81, 0xD5, 0xAF, 0xAD, 0x9B, 0x37, 0x1E, 0xAC, 0x9A, 0x7A, 0x57, 0x47, 0x30, 0xA7, 0xF6, 0x1F, 0xF1, 0xC5, 0xD9, 0x11, 0x5B, 0xB4, 0xB7, 0xFD, 0x5C, 0x00, 0x4D, 0x24, 0xCC, 0x3D, 0x0B, 0x39, 0x28, 0x12, 0xB9, 0x52, 0x07, 0x0D, 0x6E, 0xE4, 0xA3, 0x62, 0x4F, 0xF8, 0x31, 0x4B, 0x9E, 0x80, 0xE9, 0x7F, 0x8F, 0x77, 0x7B, 0x13, 0x56, 0xF4, 0x15, 0x0F, 0x33, 0x46, 0xFC, 0xD4, 0xC1, 0x8A, 0x41, 0xBC, 0xF9, 0x72, 0x5A, 0xFF, 0xCB, 0xBE, 0x6C, 0x94, 0xF7, 0x76, 0x42, 0x40, 0x06, 0x99, 0x3A, 0x97, 0x2E, 0x82, 0xC2, 0x7E, 0x14, 0xE6, 0xB2, 0x8E, 0x2B, 0xF0, 0x53, 0xA4, 0x93, 0x68, 0xE0, 0x49, 0x73, 0xA6, 0xEA, 0xDF, 0x66, 0x22, 0x1B, 0xC9, 0x98, 0x4A, 0xA1, 0xC7, 0x9F, 0xB8, 0x2F, 0x54, 0x9C, 0x88, 0xD1, 0x50, 0xA5, 0x17, 0x85, 0xD6, 0xB0, 0xCD, 0x23, 0x8C, 0x63, 0xC3, 0x8B, 0x3C, 0x87, 0x3F, 0xC6, 0x0C, 0xEB, 0x45, 0x4C, 0x89, 0x69, 0x55, 0x04, 0xC4, 0x78, 0x6B, 0xC0, 0xE7, 0xBD, 0x19, 0x64, 0x79, 0x2C, 0x74, 0x91, 0xBF, 0xDA, 0x7D, 0x5D, 0xBB, 0x05, 0x35, 0xD2, 0xA8, 0x38, 0x51, 0x2A, 0x03, 0x86, 0xB1, 0x34, 0x58, 0xF3, 0x61, 0xCA, 0xEC, 0xE5, 0x3E, 0x29, 0x96, 0xDB, 0x95, 0x25, 0xA0, 0x70, 0x1C, 0xAE, 0xEE, 0xAA, 0xA2, 0x7C, 0xED, 0xDE, 0x60, 0x5F, 0x1D, }, { 0xCB, 0x33, 0x9C, 0x03, 0xFB, 0x49, 0x07, 0xB5, 0xDF, 0x95, 0x0B, 0x43, 0x45, 0xDE, 0x5F, 0xFD, 0x0C, 0x8A, 0x1B, 0xFC, 0x7F, 0x60, 0xB9, 0xD8, 0x10, 0xBA, 0x6B, 0x39, 0x5E, 0xD4, 0xEF, 0x84, 0xE1, 0xB0, 0xA5, 0x16, 0x27, 0x55, 0x35, 0xA2, 0x0A, 0xA7, 0xB7, 0x5D, 0xC2, 0x2C, 0x61, 0xBB, 0x82, 0x02, 0x24, 0x71, 0x67, 0x1D, 0x2D, 0x4B, 0xFE, 0x56, 0xAE, 0x65, 0x13, 0xA4, 0x7E, 0xF9, 0xD7, 0xE5, 0xB2, 0xBD, 0x5B, 0x08, 0x1E, 0x74, 0x4C, 0x54, 0x48, 0x22, 0x29, 0x26, 0x3F, 0xEC, 0x40, 0x3E, 0x09, 0xB1, 0x34, 0x01, 0xD6, 0xFF, 0x4D, 0x25, 0x50, 0xDA, 0xC7, 0x23, 0xE6, 0xEE, 0xD9, 0xAC, 0x5A, 0xC9, 0x7C, 0x37, 0x98, 0xB3, 0x9D, 0x97, 0xE9, 0xE0, 0x2E, 0xE2, 0x8C, 0x04, 0x62, 0xCF, 0xE7, 0x2A, 0xED, 0x19, 0x32, 0xAB, 0xCE, 0x42, 0x9E, 0x52, 0x51, 0xF8, 0x85, 0x80, 0xD3, 0x72, 0xF2, 0x1C, 0xBE, 0x92, 0xAA, 0xA9, 0xD1, 0x57, 0xEB, 0x93, 0xF3, 0xC6, 0x14, 0x47, 0x99, 0x6A, 0x7B, 0x1A, 0x12, 0x7D, 0x89, 0x15, 0xC0, 0xDC, 0x9B, 0xBC, 0x9A, 0x86, 0x91, 0x79, 0xD5, 0xF5, 0x20, 0x38, 0x46, 0xBF, 0x75, 0xAD, 0x06, 0x1F, 0x18, 0x44, 0x36, 0xA3, 0xAF, 0x4E, 0x28, 0x0E, 0xF7, 0xD0, 0x0D, 0x3C, 0xF4, 0xE8, 0xA6, 0x2F, 0x4F, 0x70, 0x31, 0x2B, 0xDD, 0x88, 0xFA, 0x8F, 0x4A, 0x21, 0x64, 0x96, 0xF1, 0x8D, 0x8B, 0x6D, 0xCD, 0x05, 0x87, 0xCA, 0x3B, 0x90, 0x41, 0x66, 0x3D, 0xDB, 0x30, 0x6E, 0x69, 0xC8, 0x81, 0xE3, 0xB4, 0x58, 0x6C, 0xB8, 0xA1, 0xCC, 0xC3, 0xA8, 0x76, 0x94, 0x77, 0x3A, 0xC4, 0xC1, 0x83, 0x59, 0xA0, 0x5C, 0xF0, 0x73, 0x78, 0x68, 0x7A, 0x8E, 0x11, 0x9F, 0xB6, 0x00, 0x6F, 0xE4, 0x0F, 0xC5, 0xD2, 0x53, 0x63, 0x17, 0xEA, 0xF6, }, { 0xF5, 0x55, 0x31, 0x03, 0x6F, 0xCB, 0xA8, 0x06, 0x45, 0x52, 0x28, 0x0A, 0x10, 0xB4, 0xB1, 0xF8, 0x18, 0xF2, 0x94, 0x3C, 0x8E, 0x97, 0x23, 0xFD, 0xAA, 0x75, 0x93, 0x12, 0x83, 0x35, 0x46, 0xA9, 0xA2, 0xC3, 0x4B, 0x5D, 0x32, 0x59, 0x4D, 0x24, 0xB0, 0x4C, 0x73, 0xBD, 0x2D, 0x36, 0x6C, 0xB9, 0xD4, 0xBC, 0x76, 0x01, 0x54, 0x26, 0xAC, 0x65, 0xA3, 0x1B, 0xE5, 0xCE, 0xB5, 0xD2, 0x51, 0x4E, 0x50, 0xD0, 0x79, 0x0B, 0xAB, 0x0C, 0xA4, 0x8F, 0x4A, 0x05, 0xC2, 0x37, 0x48, 0x58, 0xAF, 0xBA, 0x5A, 0x7C, 0x7B, 0xFB, 0x49, 0x25, 0x39, 0x89, 0xDB, 0xE9, 0x62, 0x44, 0xEB, 0x2B, 0x1C, 0x0E, 0x15, 0x2E, 0x70, 0xFC, 0xC4, 0x3B, 0xD1, 0x34, 0xEF, 0xD6, 0x91, 0x1A, 0xDC, 0xC9, 0xD5, 0xF6, 0xBB, 0x33, 0x81, 0xED, 0x47, 0xA6, 0xE2, 0xE4, 0xEE, 0x9F, 0xF0, 0x92, 0x64, 0x95, 0x3E, 0x14, 0x7F, 0xD8, 0x30, 0xE8, 0x1F, 0x7E, 0x9D, 0xCC, 0xBF, 0x96, 0x11, 0xC8, 0x6E, 0xC7, 0xF1, 0xC1, 0xCF, 0x9E, 0x85, 0x8B, 0xE3, 0x09, 0xC5, 0x69, 0x66, 0x90, 0x9C, 0x9A, 0x02, 0x68, 0x7A, 0xF3, 0xEA, 0xDE, 0x27, 0xAD, 0x3D, 0x22, 0xB8, 0x29, 0xE1, 0x87, 0x86, 0x77, 0x61, 0xA7, 0x3A, 0xAE, 0x21, 0x53, 0x42, 0x67, 0xDA, 0x07, 0xF4, 0x2A, 0xDD, 0x16, 0x19, 0x2F, 0x9B, 0x43, 0x84, 0xA5, 0x98, 0xE7, 0x2C, 0xE0, 0xE6, 0xF9, 0x8D, 0x5C, 0xD7, 0x63, 0xCD, 0x00, 0xDF, 0xCA, 0x78, 0x71, 0xB3, 0x88, 0xFA, 0x80, 0x1D, 0xA0, 0x56, 0x40, 0x17, 0x60, 0x5B, 0xD3, 0x99, 0xBE, 0x0D, 0x08, 0x6B, 0x20, 0x6D, 0xD9, 0xF7, 0x41, 0x5E, 0x72, 0xB7, 0x6A, 0xFE, 0x8A, 0x4F, 0x74, 0x5F, 0x1E, 0xEC, 0xC6, 0x82, 0x8C, 0xB6, 0xA1, 0xFF, 0xB2, 0x7D, 0x3F, 0xC0, 0x04, 0x13, 0x0F, 0x38, 0x57, }, { 0x61, 0xA3, 0xDC, 0x11, 0x55, 0x8C, 0x67, 0x44, 0xA5, 0x26, 0x32, 0x6A, 0x43, 0xBC, 0x0B, 0xB6, 0x01, 0x0E, 0xE7, 0xC9, 0x5D, 0xEF, 0x2A, 0xE2, 0xD7, 0xC7, 0xFF, 0xF6, 0xDE, 0xCA, 0x57, 0x24, 0xB4, 0x5E, 0x1B, 0x75, 0xD9, 0x8D, 0x12, 0xA2, 0x53, 0x85, 0xD8, 0x59, 0xBF, 0xE1, 0x70, 0xC3, 0x72, 0xC5, 0x28, 0xF9, 0x76, 0x90, 0x83, 0x62, 0x6E, 0x8B, 0xAF, 0x48, 0xBB, 0x8A, 0xC8, 0xBE, 0x79, 0x0F, 0x8E, 0x91, 0xF2, 0x1C, 0x97, 0xF4, 0xC2, 0xE5, 0x10, 0x29, 0x51, 0xD3, 0xDD, 0x2E, 0xCD, 0xC4, 0x06, 0x3E, 0x41, 0x7D, 0x99, 0xA7, 0xAB, 0x3D, 0x30, 0x00, 0xB5, 0x9E, 0x42, 0x09, 0x1E, 0x08, 0xB1, 0x33, 0x1D, 0xB3, 0xF3, 0x04, 0x86, 0x0C, 0x80, 0xFA, 0xF8, 0xB0, 0x2B, 0xB8, 0x07, 0xD5, 0xB7, 0x22, 0x73, 0x17, 0x5A, 0x9C, 0x3B, 0x98, 0x74, 0xB9, 0xEE, 0x8F, 0x64, 0x52, 0x92, 0x5C, 0xB2, 0xE8, 0x18, 0x02, 0x89, 0xCB, 0x5B, 0x4B, 0xF1, 0xAE, 0xEC, 0x4D, 0x6F, 0x82, 0x63, 0xDF, 0x56, 0xA8, 0x35, 0xF5, 0x66, 0x78, 0x1F, 0xA4, 0x13, 0xA6, 0xD6, 0xCC, 0x84, 0x05, 0x15, 0x1A, 0x6D, 0x4A, 0xA0, 0xE6, 0xFB, 0x96, 0x16, 0xAA, 0x7E, 0xA9, 0xD1, 0xBD, 0xFD, 0x46, 0x2C, 0x77, 0xED, 0x7B, 0xC0, 0xCE, 0x7A, 0xE9, 0x65, 0x37, 0x45, 0x88, 0x7C, 0xD0, 0xBA, 0xAD, 0xEA, 0x03, 0x50, 0x40, 0xDA, 0x47, 0x71, 0xD2, 0x94, 0x2D, 0xF7, 0x19, 0x39, 0x25, 0xFC, 0x69, 0x21, 0x4F, 0x9D, 0x4C, 0xE4, 0x9B, 0x3C, 0x87, 0xFE, 0x93, 0x95, 0xD4, 0x23, 0xE0, 0xCF, 0x9F, 0x54, 0x6C, 0xEB, 0xAC, 0x2F, 0x81, 0xDB, 0x27, 0x4E, 0x49, 0x34, 0x0A, 0x68, 0x5F, 0x7F, 0xF0, 0xC1, 0x20, 0x58, 0xA1, 0xE3, 0x60, 0x3A, 0x6B, 0x9A, 0x0D, 0x38, 0x14, 0x36, 0x31, 0xC6, 0x3F, }, { 0x5B, 0x10, 0x85, 0xC1, 0x67, 0x9F, 0x52, 0x70, 0x61, 0x5F, 0xEB, 0x0E, 0x69, 0xF9, 0x11, 0x41, 0x4A, 0x03, 0x26, 0x9A, 0xFB, 0xA0, 0xA8, 0x75, 0x84, 0xCB, 0xA1, 0x22, 0x45, 0x64, 0x60, 0x98, 0xF1, 0xD0, 0x73, 0xDC, 0x1F, 0xCD, 0x09, 0xE7, 0x32, 0x4B, 0x16, 0x6E, 0xB0, 0xC9, 0x4F, 0xE4, 0x5A, 0xFD, 0x0A, 0x63, 0xEA, 0x94, 0xFC, 0xB9, 0xFA, 0xCC, 0xF6, 0x78, 0xD6, 0x59, 0x53, 0xFF, 0xC3, 0x54, 0x5E, 0x0C, 0x07, 0xBA, 0xAF, 0xC5, 0x3B, 0xE9, 0xA3, 0x89, 0xD3, 0x8D, 0xE8, 0xD1, 0xC2, 0x4C, 0x7F, 0x28, 0xE0, 0x04, 0x92, 0x1E, 0xF2, 0x2B, 0x76, 0x88, 0x81, 0x14, 0x21, 0xED, 0xF5, 0x00, 0x37, 0x90, 0x7E, 0xB8, 0x96, 0x06, 0xEC, 0xCF, 0x0B, 0xF7, 0xE1, 0xA2, 0x38, 0x8E, 0x2E, 0xC6, 0x30, 0x74, 0x7A, 0x23, 0x34, 0xB1, 0x97, 0x40, 0xB6, 0xB3, 0xBC, 0x55, 0xAA, 0xEE, 0x6A, 0xE5, 0x8F, 0x36, 0x9E, 0x29, 0x68, 0xD7, 0xBB, 0x86, 0x3D, 0x39, 0x05, 0x25, 0x42, 0x7D, 0x35, 0x43, 0x80, 0xD9, 0xC8, 0xDA, 0xA7, 0x46, 0x79, 0x56, 0xF8, 0xD5, 0x77, 0xD2, 0x5D, 0xDF, 0xA4, 0xF3, 0x27, 0x01, 0x99, 0x08, 0x9B, 0x57, 0x93, 0xAB, 0xA9, 0x58, 0xE3, 0xBF, 0x8B, 0x3A, 0x6D, 0x62, 0x82, 0x65, 0x20, 0x5C, 0x0F, 0x72, 0x6F, 0x7B, 0xBE, 0x3C, 0x0D, 0xAD, 0x3F, 0x2C, 0xB4, 0xF0, 0x48, 0x2F, 0x51, 0x31, 0xFE, 0x19, 0x3E, 0x13, 0x1D, 0x87, 0x9D, 0x50, 0xB5, 0xDE, 0xBD, 0xAC, 0xC7, 0x4D, 0xDB, 0x71, 0x9C, 0x18, 0x2A, 0x24, 0xC4, 0xE6, 0x02, 0x4E, 0x1C, 0x91, 0xDD, 0x2D, 0x17, 0xF4, 0xD4, 0x49, 0xA5, 0x12, 0x83, 0xB7, 0xC0, 0xE2, 0x8C, 0xB2, 0x7C, 0x15, 0xEF, 0x8A, 0x44, 0x66, 0x47, 0x95, 0x1B, 0xCA, 0x6C, 0x33, 0x6B, 0xA6, 0xCE, 0xAE, 0xD8, 0x1A, }, { 0x1B, 0x5C, 0x4D, 0x4C, 0xF3, 0x7B, 0x93, 0x44, 0x13, 0x90, 0x02, 0xD3, 0x4A, 0xB3, 0x69, 0x92, 0x30, 0xCA, 0x62, 0x89, 0xD4, 0x1D, 0xD6, 0x25, 0xE2, 0xAD, 0xED, 0x33, 0x72, 0x71, 0x61, 0xFB, 0xC1, 0xC3, 0x37, 0x1E, 0x8A, 0xE6, 0xC6, 0x95, 0xAE, 0x27, 0x00, 0x91, 0xF4, 0x43, 0x23, 0x64, 0x7D, 0x55, 0xB1, 0xC0, 0x3A, 0x78, 0x0F, 0x03, 0x0D, 0xA1, 0x32, 0x4B, 0x20, 0xD5, 0x04, 0x6C, 0xAC, 0xEE, 0x0C, 0x5F, 0xA5, 0xE0, 0xD2, 0xB5, 0xEB, 0xE9, 0x8E, 0x24, 0x4F, 0x17, 0x10, 0xAF, 0x75, 0x15, 0x2C, 0x05, 0x8F, 0x63, 0x3F, 0xC2, 0x6E, 0x50, 0x66, 0x09, 0x85, 0x51, 0xBB, 0x47, 0x57, 0x3B, 0xFE, 0xAA, 0x40, 0x8B, 0xBF, 0x56, 0xFC, 0x97, 0x98, 0xDE, 0x41, 0x94, 0x68, 0x84, 0xC5, 0x5E, 0xBC, 0xF0, 0x70, 0x6B, 0xA7, 0x1C, 0x21, 0xCD, 0xBD, 0xEF, 0xD1, 0x87, 0x5D, 0xE1, 0x74, 0x7A, 0x0A, 0x6D, 0x26, 0xA9, 0x39, 0x9A, 0x28, 0x9F, 0xE3, 0x16, 0x5A, 0x1F, 0x79, 0x42, 0xF7, 0x58, 0xE8, 0x53, 0x49, 0x59, 0xB0, 0x29, 0x07, 0x88, 0x60, 0x80, 0x3E, 0x5B, 0x86, 0xF1, 0xB6, 0x76, 0xFD, 0x46, 0x0B, 0x7E, 0x7F, 0x4E, 0x67, 0xDD, 0xA3, 0x8C, 0xBA, 0xB8, 0x35, 0xCC, 0x99, 0xA4, 0xC8, 0x82, 0xD7, 0xF9, 0x01, 0x22, 0x3C, 0x81, 0xC7, 0x9C, 0x45, 0x54, 0x6A, 0xCF, 0x0E, 0xDA, 0x65, 0x2D, 0xA6, 0x77, 0xCE, 0x52, 0xF5, 0xD0, 0xD8, 0x08, 0xA8, 0xEC, 0x2A, 0x18, 0x06, 0xFF, 0x9E, 0x73, 0xE7, 0xBE, 0xCB, 0xDB, 0x83, 0xDF, 0xF6, 0xB9, 0x11, 0xB2, 0xFA, 0xDC, 0x14, 0x3D, 0xB7, 0x34, 0xAB, 0x48, 0xC4, 0xA2, 0x96, 0x8D, 0xB4, 0x9B, 0x31, 0x2F, 0x12, 0xE5, 0x36, 0x19, 0xA0, 0x2B, 0x2E, 0x7C, 0x9D, 0xF8, 0xC9, 0xE4, 0x1A, 0x38, 0x6F, 0xEA, 0xF2, 0xD9, }, { 0x2A, 0xB6, 0x0A, 0x37, 0x3E, 0x53, 0xD0, 0x98, 0xCB, 0x5B, 0x82, 0xA4, 0x42, 0x38, 0xC0, 0x36, 0x4E, 0xDC, 0xEE, 0x08, 0xE0, 0x51, 0x8B, 0x4D, 0xCF, 0xF1, 0xFA, 0x00, 0x77, 0x15, 0x23, 0x8D, 0x3C, 0x78, 0xB7, 0x2E, 0x4B, 0x17, 0x84, 0x29, 0x88, 0x97, 0xCE, 0xF3, 0x52, 0xC3, 0xF4, 0xED, 0x10, 0xEC, 0x3A, 0x1B, 0xE3, 0xAE, 0xF0, 0x22, 0xFB, 0x86, 0x34, 0x61, 0xB8, 0xE1, 0x9C, 0x56, 0x64, 0x6C, 0x8F, 0x2D, 0x07, 0xBC, 0xA3, 0x5F, 0xE5, 0x94, 0x0C, 0x3B, 0x03, 0x02, 0xA7, 0x4C, 0x59, 0x5D, 0xC7, 0x93, 0xBD, 0x31, 0x67, 0x60, 0x91, 0x95, 0x8C, 0x9D, 0x01, 0x7E, 0x71, 0x43, 0x9A, 0x1E, 0x12, 0x55, 0x2F, 0xC2, 0x5A, 0xA8, 0x6E, 0x0E, 0xBE, 0x75, 0x3F, 0x83, 0x58, 0xFC, 0x74, 0x1D, 0x1C, 0xD3, 0x80, 0x50, 0xA1, 0xC5, 0x35, 0x8E, 0x81, 0x05, 0xF5, 0x30, 0xA5, 0xA6, 0x9B, 0xB9, 0xB3, 0xD8, 0x6F, 0x5C, 0x9E, 0x7D, 0x99, 0x13, 0x24, 0x65, 0xAB, 0xE9, 0x4A, 0x54, 0x09, 0x2B, 0x0F, 0x06, 0x6D, 0x27, 0xE8, 0x69, 0x6A, 0xB0, 0x87, 0xEB, 0xBB, 0xF6, 0xD2, 0x89, 0xF2, 0x39, 0xE7, 0xAA, 0xB1, 0x44, 0xC4, 0x76, 0xCC, 0x85, 0x63, 0xE4, 0x40, 0x19, 0x28, 0x4F, 0x96, 0x32, 0xDD, 0x0D, 0xEA, 0x47, 0xA0, 0xE2, 0xAD, 0xDB, 0xAC, 0x5E, 0x72, 0x7A, 0xD5, 0x66, 0x33, 0x20, 0x57, 0x21, 0xE6, 0x70, 0x26, 0xBA, 0xB2, 0xF8, 0x11, 0xD6, 0xAF, 0x79, 0xC6, 0xBF, 0xC9, 0x7C, 0x46, 0x0B, 0x14, 0x3D, 0x16, 0xB4, 0xCA, 0xFF, 0xC1, 0xD7, 0xDF, 0xA9, 0x6B, 0xD9, 0x45, 0x7F, 0x18, 0x8A, 0xF9, 0xEF, 0x25, 0xD4, 0x92, 0x49, 0xFD, 0x48, 0xCD, 0x1A, 0x41, 0x7B, 0x73, 0x9F, 0xFE, 0x04, 0x2C, 0xC8, 0xDA, 0x90, 0xF7, 0xB5, 0xDE, 0x1F, 0x68, 0xA2, 0x62, 0xD1, } }; } }
using System; using System.Collections.Generic; using System.Text; namespace Lidgren.Library.Network { // A fast random number generator for .NET by Colin Green, January 2005 // // September 4th 2005 // Added NextBytesUnsafe() - commented out by default. // Fixed bug in Reinitialize() - y,z and w variables were not being reset. // // Key points: // 1) Based on a simple and fast xor-shift pseudo random number generator (RNG) specified in: // Marsaglia, George. (2003). Xorshift RNGs. // http://www.jstatsoft.org/v08/i14/xorshift.pdf // // This particular implementation of xorshift has a period of 2^128-1. See the above paper to see // how this can be easily extened if you need a longer period. At the time of writing I could find no // information on the period of System.Random for comparison. // // 2) Faster than System.Random. Up to 15x faster, depending on which methods are called. // // 3) Direct replacement for System.Random. This class implements all of the methods that System.Random // does plus some additional methods. The like named methods are functionally equivalent. // // 4) Allows fast re-initialisation with a seed, unlike System.Random which accepts a seed at construction // time which then executes a relatively expensive initialisation routine. This provides a vast speed improvement // if you need to reset the pseudo-random number sequence many times, e.g. if you want to re-generate the same // sequence many times. An alternative might be to cache random numbers in an array, but that approach is limited // by memory capacity and the fact that you may also want a large number of different sequences cached. Each sequence // can each be represented by a single seed value (int) when using FastRandom. // // Notes. // A further performance improvement can be obtained by declaring local variables as static, thus avoiding // re-allocation of variables on each call. However care should be taken if multiple instances of // FastRandom are in use or if being used in a multi-threaded environment. // /// <summary> /// A fast random number generator for .NET by Colin Green, January 2005 /// </summary> public sealed class NetRandom { // The +1 ensures NextDouble doesn't generate 1.0 const double REAL_UNIT_INT = 1.0 / ((double)int.MaxValue + 1.0); const double REAL_UNIT_UINT = 1.0 / ((double)uint.MaxValue + 1.0); const uint Y = 842502087, Z = 3579807591, W = 273326509; private static int m_extraSeed = 42; uint x, y, z, w; public static NetRandom Default = new NetRandom(); #region Constructors /// <summary> /// Initialises a new instance using time dependent seed. /// </summary> public NetRandom() { // Initialise using the system tick count. Reinitialize((int)Environment.TickCount + m_extraSeed); m_extraSeed++; // in case several initializations at the same time } /// <summary> /// Initialises a new instance using an int value as seed. /// This constructor signature is provided to maintain compatibility with /// System.Random /// </summary> public NetRandom(int seed) { Reinitialize(seed); } #endregion #region Public Methods [Reinitialization] /// <summary> /// Reinitializes using an int value as a seed. /// </summary> /// <param name="seed"></param> public void Reinitialize(int seed) { // The only stipulation stated for the xorshift RNG is that at least one of // the seeds x,y,z,w is non-zero. We fulfill that requirement by only allowing // resetting of the x seed x = (uint)seed; y = Y; z = Z; w = W; } #endregion #region Public Methods [Next* methods] /// <summary> /// Generates a uint. Values returned are over the full range of a uint, /// uint.MinValue to uint.MaxValue, including the min and max values. /// </summary> /// <returns></returns> public uint NextUInt() { uint t = (x ^ (x << 11)); x = y; y = z; z = w; return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))); } /// <summary> /// Generates a random int. Values returned are over the range 0 to int.MaxValue-1. /// MaxValue is not generated to remain functionally equivalent to System.Random.Next(). /// If you require an int from the full range, including negative values then call /// NextUint() and cast the value to an int. /// </summary> /// <returns></returns> public int Next() { uint t = (x ^ (x << 11)); x = y; y = z; z = w; return (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)))); } /// <summary> /// Generates a random int over the range 0 to upperBound-1, and not including upperBound. /// </summary> /// <param name="upperBound"></param> /// <returns></returns> public int Next(int upperBound) { if (upperBound < 0) throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=0"); uint t = (x ^ (x << 11)); x = y; y = z; z = w; // The explicit int cast before the first multiplication gives better performance. // See comments in NextDouble. return (int)((REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))) * upperBound); } /// <summary> /// Generates a random int over the range lowerBound to upperBound-1, and not including upperBound. /// upperBound must be >= lowerBound. lowerBound may be negative. /// </summary> /// <param name="lowerBound"></param> /// <param name="upperBound"></param> /// <returns></returns> public int Next(int lowerBound, int upperBound) { if (lowerBound > upperBound) throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=lowerBound"); uint t = (x ^ (x << 11)); x = y; y = z; z = w; // The explicit int cast before the first multiplication gives better performance. // See comments in NextDouble. int range = upperBound - lowerBound; if (range < 0) { // If range is <0 then an overflow has occured and must resort to using long integer arithmetic instead (slower). // We also must use all 32 bits of precision, instead of the normal 31, which again is slower. return lowerBound + (int)((REAL_UNIT_UINT * (double)(w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)))) * (double)((long)upperBound - (long)lowerBound)); } // 31 bits of precision will suffice if range<=int.MaxValue. This allows us to cast to an int anf gain // a little more performance. return lowerBound + (int)((REAL_UNIT_INT * (double)(int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))) * (double)range); } /// <summary> /// Generates a random double. Values returned are from 0.0 up to but not including 1.0. /// </summary> /// <returns></returns> public double NextDouble() { uint t = (x ^ (x << 11)); x = y; y = z; z = w; // Here we can gain a 2x speed improvement by generating a value that can be cast to // an int instead of the more easily available uint. If we then explicitly cast to an // int the compiler will then cast the int to a double to perform the multiplication, // this final cast is a lot faster than casting from a uint to a double. The extra cast // to an int is very fast (the allocated bits remain the same) and so the overall effect // of the extra cast is a significant performance improvement. return (REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))); } /// <summary> /// Generates a random double. Values returned are from 0.0 up to but not including 1.0. /// </summary> /// <returns></returns> public float NextFloat() { uint t = (x ^ (x << 11)); x = y; y = z; z = w; // Here we can gain a 2x speed improvement by generating a value that can be cast to // an int instead of the more easily available uint. If we then explicitly cast to an // int the compiler will then cast the int to a double to perform the multiplication, // this final cast is a lot faster than casting from a uint to a double. The extra cast // to an int is very fast (the allocated bits remain the same) and so the overall effect // of the extra cast is a significant performance improvement. return (float)(REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))); } /// <summary> /// Generates a random double. Values returned are from 0.0 up to but not including roof /// </summary> /// <returns></returns> public float NextFloat(float roof) { uint t = (x ^ (x << 11)); x = y; y = z; z = w; // Here we can gain a 2x speed improvement by generating a value that can be cast to // an int instead of the more easily available uint. If we then explicitly cast to an // int the compiler will then cast the int to a double to perform the multiplication, // this final cast is a lot faster than casting from a uint to a double. The extra cast // to an int is very fast (the allocated bits remain the same) and so the overall effect // of the extra cast is a significant performance improvement. float f = (float)(REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))); return f * roof; } /// <summary> /// Generates a random double. Values returned are from min up to but not including min + variance /// </summary> /// <returns></returns> public float NextFloat(float min, float variance) { uint t = (x ^ (x << 11)); x = y; y = z; z = w; // Here we can gain a 2x speed improvement by generating a value that can be cast to // an int instead of the more easily available uint. If we then explicitly cast to an // int the compiler will then cast the int to a double to perform the multiplication, // this final cast is a lot faster than casting from a uint to a double. The extra cast // to an int is very fast (the allocated bits remain the same) and so the overall effect // of the extra cast is a significant performance improvement. float f = (float)(REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))); return min + f * variance; } /// <summary> /// If passed 0.7f it will return true 7 times out of 10 /// </summary> /// <returns></returns> public bool Chance(float percentChance) { uint t = (x ^ (x << 11)); x = y; y = z; z = w; // Here we can gain a 2x speed improvement by generating a value that can be cast to // an int instead of the more easily available uint. If we then explicitly cast to an // int the compiler will then cast the int to a double to perform the multiplication, // this final cast is a lot faster than casting from a uint to a double. The extra cast // to an int is very fast (the allocated bits remain the same) and so the overall effect // of the extra cast is a significant performance improvement. double hit = (REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))); if (hit < percentChance) return true; return false; } /// <summary> /// Fills the provided byte array with random bytes. /// Increased performance is achieved by dividing and packaging bits directly from the /// random number generator and storing them in 4 byte 'chunks'. /// </summary> /// <param name="buffer"></param> public void NextBytes(byte[] buffer) { if (buffer == null) throw new ArgumentNullException("buffer", "Invalid buffer object."); // Fill up the bulk of the buffer in chunks of 4 bytes at a time. uint x = this.x, y = this.y, z = this.z, w = this.w; int i = 0; uint t; for (; i < buffer.Length - 3; ) { // Generate 4 bytes. t = (x ^ (x << 11)); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); buffer[i++] = (byte)(w & 0x000000FF); buffer[i++] = (byte)((w & 0x0000FF00) >> 8); buffer[i++] = (byte)((w & 0x00FF0000) >> 16); buffer[i++] = (byte)((w & 0xFF000000) >> 24); } // Fill up any remaining bytes in the buffer. if (i < buffer.Length) { // Generate 4 bytes. t = (x ^ (x << 11)); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); buffer[i++] = (byte)(w & 0x000000FF); if (i < buffer.Length) { buffer[i++] = (byte)((w & 0x0000FF00) >> 8); if (i < buffer.Length) { buffer[i++] = (byte)((w & 0x00FF0000) >> 16); if (i < buffer.Length) { buffer[i] = (byte)((w & 0xFF000000) >> 24); } } } } this.x = x; this.y = y; this.z = z; this.w = w; } // /// <summary> // /// A version of NextBytes that uses a pointer to set 4 bytes of the byte buffer in one operation // /// thus providing a nice speedup. Note that this requires the unsafe compilation flag to be specified // /// and so is commented out by default. // /// </summary> // /// <param name="buffer"></param> // public unsafe void NextBytesUnsafe(byte[] buffer) // { // if(buffer.Length % 4 != 0) // throw new ArgumentException("Buffer length must be divisible by 4", "buffer"); // // uint x=this.x, y=this.y, z=this.z, w=this.w; // uint t; // // fixed(byte* pByte0 = buffer) // { // uint* pDWord = (uint*)pByte0; // for(int i = 0, len = buffer.Length>>2; i < len; i++) // { // t=(x^(x<<11)); // x=y; y=z; z=w; // *pDWord++ = w = (w^(w>>19))^(t^(t>>8)); // } // } // // this.x=x; this.y=y; this.z=z; this.w=w; // } // Buffer 32 bits in bitBuffer, return 1 at a time, keep track of how many have been returned // with bitBufferIdx. uint bitBuffer; int bitBufferIdx = 32; /// <summary> /// Generates random bool. /// Increased performance is achieved by buffering 32 random bits for /// future calls. Thus the random number generator is only invoked once /// in every 32 calls. /// </summary> /// <returns></returns> public bool NextBool() { if (bitBufferIdx == 32) { // Generate 32 more bits. uint t = (x ^ (x << 11)); x = y; y = z; z = w; bitBuffer = w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); // Reset the idx that tells us which bit to read next. bitBufferIdx = 1; return (bitBuffer & 0x1) == 1; } bitBufferIdx++; return ((bitBuffer >>= 1) & 0x1) == 1; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.IO.Tests { public class Directory_Delete_str : FileSystemTest { #region Utilities public virtual void Delete(string path) { Directory.Delete(path); } #endregion #region UniversalTests [Fact] public void NullParameters() { Assert.Throws<ArgumentNullException>(() => Delete(null)); } [Fact] public void InvalidParameters() { Assert.Throws<ArgumentException>(() => Delete(string.Empty)); } [Fact] public void ShouldThrowIOExceptionIfContainedFileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { Assert.Throws<IOException>(() => Delete(testDir.FullName)); } Assert.True(testDir.Exists); } [Fact] public void ShouldThrowIOExceptionForDirectoryWithFiles() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] public void DirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] [OuterLoop] public void DeleteRoot() { Assert.Throws<IOException>(() => Delete(Path.GetPathRoot(Directory.GetCurrentDirectory()))); } [Fact] public void PositiveTest() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] public void ShouldThrowDirectoryNotFoundExceptionForNonexistentDirectory() { Assert.Throws<DirectoryNotFoundException>(() => Delete(GetTestFilePath())); } [Fact] public void ShouldThrowIOExceptionDeletingCurrentDirectory() { Assert.Throws<IOException>(() => Delete(Directory.GetCurrentDirectory())); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsExtendedDirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsLongPathExtendedDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500).FullPath); Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsDeleteExtendedReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsShouldBeAbleToDeleteHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsShouldBeAbleToDeleteExtendedHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixShouldBeAbleToDeleteHiddenDirectory() { string testDir = "." + GetTestFileName(); Directory.CreateDirectory(Path.Combine(TestDirectory, testDir)); Assert.True(0 != (new DirectoryInfo(Path.Combine(TestDirectory, testDir)).Attributes & FileAttributes.Hidden)); Delete(Path.Combine(TestDirectory, testDir)); Assert.False(Directory.Exists(testDir)); } #endregion } public class Directory_Delete_str_bool : Directory_Delete_str { #region Utilities public override void Delete(string path) { Directory.Delete(path, false); } public virtual void Delete(string path, bool recursive) { Directory.Delete(path, recursive); } #endregion [Fact] public void RecursiveDelete() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); testDir.CreateSubdirectory(GetTestFileName()); Delete(testDir.FullName, true); Assert.False(testDir.Exists); } [Fact] public void RecursiveDeleteWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Delete(testDir.FullName + Path.DirectorySeparatorChar, true); Assert.False(testDir.Exists); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text.Encodings.Web; using System.Text.Unicode; using Xunit; namespace Microsoft.Framework.WebEncoders { public static class TextEncoderSettingsExtensions { public static bool IsCharacterAllowed(this TextEncoderSettings settings, char character) { var bitmap = settings.GetAllowedCharacters(); return bitmap.IsCharacterAllowed(character); } } public class TextEncoderSettingsTests { [Fact] public void Ctor_Parameterless_CreatesEmptyFilter() { var filter = new TextEncoderSettings(); Assert.Equal(0, filter.GetAllowedCodePoints().Count()); } [Fact] public void Ctor_OtherTextEncoderSettingsAsInterface() { // Arrange var originalFilter = new OddTextEncoderSettings(); // Act var newFilter = new TextEncoderSettings(originalFilter); // Assert for (int i = 0; i <= char.MaxValue; i++) { Assert.Equal((i % 2) == 1, newFilter.IsCharacterAllowed((char)i)); } } [Fact] public void Ctor_OtherTextEncoderSettingsAsConcreteType_Clones() { // Arrange var originalFilter = new TextEncoderSettings(); originalFilter.AllowCharacter('x'); // Act var newFilter = new TextEncoderSettings(originalFilter); newFilter.AllowCharacter('y'); // Assert Assert.True(originalFilter.IsCharacterAllowed('x')); Assert.False(originalFilter.IsCharacterAllowed('y')); Assert.True(newFilter.IsCharacterAllowed('x')); Assert.True(newFilter.IsCharacterAllowed('y')); } [Fact] public void Ctor_UnicodeRanges() { // Act var filter = new TextEncoderSettings(UnicodeRanges.LatinExtendedA, UnicodeRanges.LatinExtendedC); // Assert for (int i = 0; i < 0x0100; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } for (int i = 0x0100; i <= 0x017F; i++) { Assert.True(filter.IsCharacterAllowed((char)i)); } for (int i = 0x0180; i < 0x2C60; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } for (int i = 0x2C60; i <= 0x2C7F; i++) { Assert.True(filter.IsCharacterAllowed((char)i)); } for (int i = 0x2C80; i <= char.MaxValue; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } } [Fact] public void Ctor_Null_UnicodeRanges() { Assert.Throws<ArgumentNullException>("allowedRanges", () => new TextEncoderSettings(default(UnicodeRange[]))); } [Fact] public void Ctor_Null_TextEncoderSettings() { Assert.Throws<ArgumentNullException>("other", () => new TextEncoderSettings(default(TextEncoderSettings))); } [Fact] public void AllowChar() { // Arrange var filter = new TextEncoderSettings(); filter.AllowCharacter('\u0100'); // Assert Assert.True(filter.IsCharacterAllowed('\u0100')); Assert.False(filter.IsCharacterAllowed('\u0101')); } [Fact] public void AllowChars_Array() { // Arrange var filter = new TextEncoderSettings(); filter.AllowCharacters('\u0100', '\u0102'); // Assert Assert.True(filter.IsCharacterAllowed('\u0100')); Assert.False(filter.IsCharacterAllowed('\u0101')); Assert.True(filter.IsCharacterAllowed('\u0102')); Assert.False(filter.IsCharacterAllowed('\u0103')); } [Fact] public void AllowChars_String() { // Arrange var filter = new TextEncoderSettings(); filter.AllowCharacters('\u0100', '\u0102'); // Assert Assert.True(filter.IsCharacterAllowed('\u0100')); Assert.False(filter.IsCharacterAllowed('\u0101')); Assert.True(filter.IsCharacterAllowed('\u0102')); Assert.False(filter.IsCharacterAllowed('\u0103')); } [Fact] public void AllowChars_Null() { TextEncoderSettings filter = new TextEncoderSettings(); Assert.Throws<ArgumentNullException>("characters", () => filter.AllowCharacters(null)); } [Fact] public void AllowFilter() { // Arrange var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin); filter.AllowCodePoints(new OddTextEncoderSettings().GetAllowedCodePoints()); // Assert for (int i = 0; i <= 0x007F; i++) { Assert.True(filter.IsCharacterAllowed((char)i)); } for (int i = 0x0080; i <= char.MaxValue; i++) { Assert.Equal((i % 2) == 1, filter.IsCharacterAllowed((char)i)); } } [Fact] public void AllowFilter_NullCodePoints() { TextEncoderSettings filter = new TextEncoderSettings(UnicodeRanges.BasicLatin); Assert.Throws<ArgumentNullException>("codePoints", () => filter.AllowCodePoints(null)); } [Fact] public void AllowFilter_NonBMP() { TextEncoderSettings filter = new TextEncoderSettings(); filter.AllowCodePoints(Enumerable.Range(0x10000, 20)); Assert.Empty(filter.GetAllowedCodePoints()); } [Fact] public void AllowRange() { // Arrange var filter = new TextEncoderSettings(); filter.AllowRange(UnicodeRanges.LatinExtendedA); // Assert for (int i = 0; i < 0x0100; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } for (int i = 0x0100; i <= 0x017F; i++) { Assert.True(filter.IsCharacterAllowed((char)i)); } for (int i = 0x0180; i <= char.MaxValue; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } } [Fact] public void AllowRange_NullRange() { TextEncoderSettings filter = new TextEncoderSettings(); Assert.Throws<ArgumentNullException>("range", () => filter.AllowRange(null)); } [Fact] public void AllowRanges() { // Arrange var filter = new TextEncoderSettings(); filter.AllowRanges(UnicodeRanges.LatinExtendedA, UnicodeRanges.LatinExtendedC); // Assert for (int i = 0; i < 0x0100; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } for (int i = 0x0100; i <= 0x017F; i++) { Assert.True(filter.IsCharacterAllowed((char)i)); } for (int i = 0x0180; i < 0x2C60; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } for (int i = 0x2C60; i <= 0x2C7F; i++) { Assert.True(filter.IsCharacterAllowed((char)i)); } for (int i = 0x2C80; i <= char.MaxValue; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } } [Fact] public void AllowRanges_NullRange() { TextEncoderSettings filter = new TextEncoderSettings(); Assert.Throws<ArgumentNullException>("ranges", () => filter.AllowRanges(null)); } [Fact] public void Clear() { // Arrange var filter = new TextEncoderSettings(); for (int i = 1; i <= char.MaxValue; i++) { filter.AllowCharacter((char)i); } // Act filter.Clear(); // Assert for (int i = 0; i <= char.MaxValue; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } } [Fact] public void ForbidChar() { // Arrange var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin); filter.ForbidCharacter('x'); // Assert Assert.True(filter.IsCharacterAllowed('w')); Assert.False(filter.IsCharacterAllowed('x')); Assert.True(filter.IsCharacterAllowed('y')); Assert.True(filter.IsCharacterAllowed('z')); } [Fact] public void ForbidChars_Array() { // Arrange var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin); filter.ForbidCharacters('x', 'z'); // Assert Assert.True(filter.IsCharacterAllowed('w')); Assert.False(filter.IsCharacterAllowed('x')); Assert.True(filter.IsCharacterAllowed('y')); Assert.False(filter.IsCharacterAllowed('z')); } [Fact] public void ForbidChars_String() { // Arrange var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin); filter.ForbidCharacters('x', 'z'); // Assert Assert.True(filter.IsCharacterAllowed('w')); Assert.False(filter.IsCharacterAllowed('x')); Assert.True(filter.IsCharacterAllowed('y')); Assert.False(filter.IsCharacterAllowed('z')); } [Fact] public void ForbidChars_Null() { TextEncoderSettings filter = new TextEncoderSettings(UnicodeRanges.BasicLatin); Assert.Throws<ArgumentNullException>("characters", () => filter.ForbidCharacters(null)); } [Fact] public void ForbidRange() { // Arrange var filter = new TextEncoderSettings(new OddTextEncoderSettings()); filter.ForbidRange(UnicodeRanges.Specials); // Assert for (int i = 0; i <= 0xFFEF; i++) { Assert.Equal((i % 2) == 1, filter.IsCharacterAllowed((char)i)); } for (int i = 0xFFF0; i <= char.MaxValue; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } } [Fact] public void ForbidRange_Null() { TextEncoderSettings filter = new TextEncoderSettings(); Assert.Throws<ArgumentNullException>("range", () => filter.ForbidRange(null)); } [Fact] public void ForbidRanges() { // Arrange var filter = new TextEncoderSettings(new OddTextEncoderSettings()); filter.ForbidRanges(UnicodeRanges.BasicLatin, UnicodeRanges.Specials); // Assert for (int i = 0; i <= 0x007F; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } for (int i = 0x0080; i <= 0xFFEF; i++) { Assert.Equal((i % 2) == 1, filter.IsCharacterAllowed((char)i)); } for (int i = 0xFFF0; i <= char.MaxValue; i++) { Assert.False(filter.IsCharacterAllowed((char)i)); } } [Fact] public void ForbidRanges_Null() { TextEncoderSettings filter = new TextEncoderSettings(new OddTextEncoderSettings()); Assert.Throws<ArgumentNullException>("ranges", () => filter.ForbidRanges(null)); } [Fact] public void GetAllowedCodePoints() { // Arrange var expected = Enumerable.Range(UnicodeRanges.BasicLatin.FirstCodePoint, UnicodeRanges.BasicLatin.Length) .Concat(Enumerable.Range(UnicodeRanges.Specials.FirstCodePoint, UnicodeRanges.Specials.Length)) .Except(new int[] { 'x' }) .OrderBy(i => i) .ToArray(); var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Specials); filter.ForbidCharacter('x'); // Act var retVal = filter.GetAllowedCodePoints().OrderBy(i => i).ToArray(); // Assert Assert.Equal<int>(expected, retVal); } // a code point filter which allows only odd code points through private sealed class OddTextEncoderSettings : TextEncoderSettings { public override IEnumerable<int> GetAllowedCodePoints() { for (int i = 1; i <= char.MaxValue; i += 2) { yield return i; } } } } }
// 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.Specialized; using System.Configuration; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Caching.Configuration; using System.Runtime.InteropServices; using System.Security; using System.Threading; namespace System.Runtime.Caching { internal sealed class MemoryCacheStatistics : IDisposable { private const int MEMORYSTATUS_INTERVAL_5_SECONDS = 5 * 1000; private const int MEMORYSTATUS_INTERVAL_30_SECONDS = 30 * 1000; private int _configCacheMemoryLimitMegabytes; private int _configPhysicalMemoryLimitPercentage; private int _configPollingInterval; private int _inCacheManagerThread; private int _disposed; private long _lastTrimCount; private long _lastTrimDurationTicks; // used only for debugging private int _lastTrimGen2Count; private int _lastTrimPercent; private DateTime _lastTrimTime; private int _pollingInterval; private GCHandleRef<Timer> _timerHandleRef; private readonly object _timerLock; private long _totalCountBeforeTrim; private CacheMemoryMonitor _cacheMemoryMonitor; private readonly MemoryCache _memoryCache; private readonly PhysicalMemoryMonitor _physicalMemoryMonitor; // private private MemoryCacheStatistics() { //hide default ctor } private void AdjustTimer() { lock (_timerLock) { if (_timerHandleRef == null) return; Timer timer = _timerHandleRef.Target; // the order of these if statements is important // When above the high pressure mark, interval should be 5 seconds or less if (_physicalMemoryMonitor.IsAboveHighPressure() || _cacheMemoryMonitor.IsAboveHighPressure()) { if (_pollingInterval > MEMORYSTATUS_INTERVAL_5_SECONDS) { _pollingInterval = MEMORYSTATUS_INTERVAL_5_SECONDS; timer.Change(_pollingInterval, _pollingInterval); } return; } // When above half the low pressure mark, interval should be 30 seconds or less if ((_cacheMemoryMonitor.PressureLast > _cacheMemoryMonitor.PressureLow / 2) || (_physicalMemoryMonitor.PressureLast > _physicalMemoryMonitor.PressureLow / 2)) { // allow interval to fall back down when memory pressure goes away int newPollingInterval = Math.Min(_configPollingInterval, MEMORYSTATUS_INTERVAL_30_SECONDS); if (_pollingInterval != newPollingInterval) { _pollingInterval = newPollingInterval; timer.Change(_pollingInterval, _pollingInterval); } return; } // there is no pressure, interval should be the value from config if (_pollingInterval != _configPollingInterval) { _pollingInterval = _configPollingInterval; timer.Change(_pollingInterval, _pollingInterval); } } } // timer callback private void CacheManagerTimerCallback(object state) { CacheManagerThread(0); } internal long GetLastSize() { return _cacheMemoryMonitor.PressureLast; } private int GetPercentToTrim() { int gen2Count = GC.CollectionCount(2); // has there been a Gen 2 Collection since the last trim? if (gen2Count != _lastTrimGen2Count) { return Math.Max(_physicalMemoryMonitor.GetPercentToTrim(_lastTrimTime, _lastTrimPercent), _cacheMemoryMonitor.GetPercentToTrim(_lastTrimTime, _lastTrimPercent)); } else { return 0; } } private void InitializeConfiguration(NameValueCollection config) { MemoryCacheElement element = null; if (!_memoryCache.ConfigLess) { MemoryCacheSection section = ConfigurationManager.GetSection("system.runtime.caching/memoryCache") as MemoryCacheSection; if (section != null) { element = section.NamedCaches[_memoryCache.Name]; } } if (element != null) { _configCacheMemoryLimitMegabytes = element.CacheMemoryLimitMegabytes; _configPhysicalMemoryLimitPercentage = element.PhysicalMemoryLimitPercentage; double milliseconds = element.PollingInterval.TotalMilliseconds; _configPollingInterval = (milliseconds < (double)int.MaxValue) ? (int)milliseconds : int.MaxValue; } else { _configPollingInterval = ConfigUtil.DefaultPollingTimeMilliseconds; _configCacheMemoryLimitMegabytes = 0; _configPhysicalMemoryLimitPercentage = 0; } if (config != null) { _configPollingInterval = ConfigUtil.GetIntValueFromTimeSpan(config, ConfigUtil.PollingInterval, _configPollingInterval); _configCacheMemoryLimitMegabytes = ConfigUtil.GetIntValue(config, ConfigUtil.CacheMemoryLimitMegabytes, _configCacheMemoryLimitMegabytes, true, int.MaxValue); _configPhysicalMemoryLimitPercentage = ConfigUtil.GetIntValue(config, ConfigUtil.PhysicalMemoryLimitPercentage, _configPhysicalMemoryLimitPercentage, true, 100); } if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && _configPhysicalMemoryLimitPercentage > 0) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_PhysicalMemoryLimitPercentage); } } private void InitDisposableMembers() { bool dispose = true; try { _cacheMemoryMonitor = new CacheMemoryMonitor(_memoryCache, _configCacheMemoryLimitMegabytes); Timer timer; // Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever bool restoreFlow = false; try { if (!ExecutionContext.IsFlowSuppressed()) { ExecutionContext.SuppressFlow(); restoreFlow = true; } timer = new Timer(new TimerCallback(CacheManagerTimerCallback), null, _configPollingInterval, _configPollingInterval); } finally { // Restore the current ExecutionContext if (restoreFlow) ExecutionContext.RestoreFlow(); } _timerHandleRef = new GCHandleRef<Timer>(timer); dispose = false; } finally { if (dispose) { Dispose(); } } } private void SetTrimStats(long trimDurationTicks, long totalCountBeforeTrim, long trimCount) { _lastTrimDurationTicks = trimDurationTicks; int gen2Count = GC.CollectionCount(2); // has there been a Gen 2 Collection since the last trim? if (gen2Count != _lastTrimGen2Count) { _lastTrimTime = DateTime.UtcNow; _totalCountBeforeTrim = totalCountBeforeTrim; _lastTrimCount = trimCount; } else { // we've done multiple trims between Gen 2 collections, so only add to the trim count _lastTrimCount += trimCount; } _lastTrimGen2Count = gen2Count; _lastTrimPercent = (int)((_lastTrimCount * 100L) / _totalCountBeforeTrim); } private void Update() { _physicalMemoryMonitor.Update(); _cacheMemoryMonitor.Update(); } // public/internal internal long CacheMemoryLimit { get { return _cacheMemoryMonitor.MemoryLimit; } } internal long PhysicalMemoryLimit { get { return _physicalMemoryMonitor.MemoryLimit; } } internal TimeSpan PollingInterval { get { return TimeSpan.FromMilliseconds(_configPollingInterval); } } internal MemoryCacheStatistics(MemoryCache memoryCache, NameValueCollection config) { _memoryCache = memoryCache; _lastTrimGen2Count = -1; _lastTrimTime = DateTime.MinValue; _timerLock = new object(); InitializeConfiguration(config); _pollingInterval = _configPollingInterval; _physicalMemoryMonitor = new PhysicalMemoryMonitor(_configPhysicalMemoryLimitPercentage); InitDisposableMembers(); } internal long CacheManagerThread(int minPercent) { if (Interlocked.Exchange(ref _inCacheManagerThread, 1) != 0) return 0; try { if (_disposed == 1) { return 0; } Dbg.Trace("MemoryCacheStats", "**BEG** CacheManagerThread " + DateTime.Now.ToString("T", CultureInfo.InvariantCulture)); // The timer thread must always call Update so that the CacheManager // knows the size of the cache. Update(); AdjustTimer(); int percent = Math.Max(minPercent, GetPercentToTrim()); long beginTotalCount = _memoryCache.GetCount(); Stopwatch sw = Stopwatch.StartNew(); long trimmedOrExpired = _memoryCache.Trim(percent); sw.Stop(); // 1) don't update stats if the trim happend because MAX_COUNT was exceeded // 2) don't update stats unless we removed at least one entry if (percent > 0 && trimmedOrExpired > 0) { SetTrimStats(sw.Elapsed.Ticks, beginTotalCount, trimmedOrExpired); } Dbg.Trace("MemoryCacheStats", "**END** CacheManagerThread: " + ", percent=" + percent + ", beginTotalCount=" + beginTotalCount + ", trimmed=" + trimmedOrExpired + ", Milliseconds=" + sw.ElapsedMilliseconds); #if PERF Debug.WriteLine("CacheCommon.CacheManagerThread:" + " minPercent= " + minPercent + ", percent= " + percent + ", beginTotalCount=" + beginTotalCount + ", trimmed=" + trimmedOrExpired + ", Milliseconds=" + sw.ElapsedMilliseconds + Environment.NewLine); #endif return trimmedOrExpired; } finally { Interlocked.Exchange(ref _inCacheManagerThread, 0); } } public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) { lock (_timerLock) { GCHandleRef<Timer> timerHandleRef = _timerHandleRef; if (timerHandleRef != null && Interlocked.CompareExchange(ref _timerHandleRef, null, timerHandleRef) == timerHandleRef) { timerHandleRef.Dispose(); Dbg.Trace("MemoryCacheStats", "Stopped CacheMemoryTimers"); } } while (_inCacheManagerThread != 0) { Thread.Sleep(100); } if (_cacheMemoryMonitor != null) { _cacheMemoryMonitor.Dispose(); } // Don't need to call GC.SuppressFinalize(this) for sealed types without finalizers. } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")] internal void UpdateConfig(NameValueCollection config) { int pollingInterval = ConfigUtil.GetIntValueFromTimeSpan(config, ConfigUtil.PollingInterval, _configPollingInterval); int cacheMemoryLimitMegabytes = ConfigUtil.GetIntValue(config, ConfigUtil.CacheMemoryLimitMegabytes, _configCacheMemoryLimitMegabytes, true, int.MaxValue); int physicalMemoryLimitPercentage = ConfigUtil.GetIntValue(config, ConfigUtil.PhysicalMemoryLimitPercentage, _configPhysicalMemoryLimitPercentage, true, 100); if (pollingInterval != _configPollingInterval) { lock (_timerLock) { _configPollingInterval = pollingInterval; } } if (cacheMemoryLimitMegabytes == _configCacheMemoryLimitMegabytes && physicalMemoryLimitPercentage == _configPhysicalMemoryLimitPercentage) { return; } try { try { } finally { // prevent ThreadAbortEx from interrupting while (Interlocked.Exchange(ref _inCacheManagerThread, 1) != 0) { Thread.Sleep(100); } } if (_disposed == 0) { if (cacheMemoryLimitMegabytes != _configCacheMemoryLimitMegabytes) { _cacheMemoryMonitor.SetLimit(cacheMemoryLimitMegabytes); _configCacheMemoryLimitMegabytes = cacheMemoryLimitMegabytes; } if (physicalMemoryLimitPercentage != _configPhysicalMemoryLimitPercentage) { _physicalMemoryMonitor.SetLimit(physicalMemoryLimitPercentage); _configPhysicalMemoryLimitPercentage = physicalMemoryLimitPercentage; } } } finally { Interlocked.Exchange(ref _inCacheManagerThread, 0); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using Microsoft.SqlServer.Server; using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; using System.Text; using MSS = Microsoft.SqlServer.Server; namespace System.Data.SqlClient { // TdsValueSetter handles writing a single value out to a TDS stream // This class can easily be extended to handle multiple versions of TDS by sub-classing and virtualizing // methods that have different formats or are not supported in one or the other version. internal class TdsValueSetter { #region Private fields private TdsParserStateObject _stateObj; // target to write to private SmiMetaData _metaData; // metadata describing value private bool _isPlp; // should this column be sent in PLP format? private bool _plpUnknownSent;// did we send initial UNKNOWN_LENGTH marker? private Encoder _encoder; // required for chunking character type data private SmiMetaData _variantType; // required for sql_variant #if DEBUG private int _currentOffset; // for chunking, verify that caller is using correct offsets #endif #endregion #region Exposed Construct/factory methods internal TdsValueSetter(TdsParserStateObject stateObj, SmiMetaData md) { _stateObj = stateObj; _metaData = md; _isPlp = MetaDataUtilsSmi.IsPlpFormat(md); _plpUnknownSent = false; _encoder = null; #if DEBUG _currentOffset = 0; #endif } #endregion #region Setters // Set value to null // valid for all types internal void SetDBNull() { Debug.Assert(!_plpUnknownSent, "Setting a column to null that we already stated sending!"); if (_isPlp) { _stateObj.Parser.WriteUnsignedLong(TdsEnums.SQL_PLP_NULL, _stateObj); } else { switch (_metaData.SqlDbType) { case SqlDbType.BigInt: case SqlDbType.Bit: case SqlDbType.DateTime: case SqlDbType.Decimal: case SqlDbType.Float: case SqlDbType.Int: case SqlDbType.Money: case SqlDbType.Real: case SqlDbType.UniqueIdentifier: case SqlDbType.SmallDateTime: case SqlDbType.SmallInt: case SqlDbType.SmallMoney: case SqlDbType.TinyInt: case SqlDbType.Date: case SqlDbType.Time: case SqlDbType.DateTime2: case SqlDbType.DateTimeOffset: _stateObj.WriteByte(TdsEnums.FIXEDNULL); break; case SqlDbType.Binary: case SqlDbType.Char: case SqlDbType.Image: case SqlDbType.NChar: case SqlDbType.NText: case SqlDbType.NVarChar: case SqlDbType.Text: case SqlDbType.Timestamp: case SqlDbType.VarBinary: case SqlDbType.VarChar: _stateObj.Parser.WriteShort(TdsEnums.VARNULL, _stateObj); break; case SqlDbType.Udt: case SqlDbType.Xml: Debug.Assert(false, "PLP-only types shouldn't get to this point. Type: " + _metaData.SqlDbType); break; case SqlDbType.Variant: _stateObj.Parser.WriteInt(TdsEnums.FIXEDNULL, _stateObj); break; case SqlDbType.Structured: Debug.Assert(false, "Not yet implemented. Not needed until Structured UDTs"); break; default: Debug.Assert(false, "Unexpected SqlDbType: " + _metaData.SqlDbType); break; } } } // valid for SqlDbType.Bit internal void SetBoolean(Boolean value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetBoolean)); if (SqlDbType.Variant == _metaData.SqlDbType) { _stateObj.Parser.WriteSqlVariantHeader(3, TdsEnums.SQLBIT, 0, _stateObj); } else { _stateObj.WriteByte((byte)_metaData.MaxLength); } if (value) { _stateObj.WriteByte(1); } else { _stateObj.WriteByte(0); } } // valid for SqlDbType.TinyInt internal void SetByte(Byte value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetByte)); if (SqlDbType.Variant == _metaData.SqlDbType) { _stateObj.Parser.WriteSqlVariantHeader(3, TdsEnums.SQLINT1, 0, _stateObj); } else { _stateObj.WriteByte((byte)_metaData.MaxLength); } _stateObj.WriteByte(value); } // Semantics for SetBytes are to modify existing value, not overwrite // Use in combination with SetLength to ensure overwriting when necessary // valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml // (VarBinary assumed for variants) internal int SetBytes(long fieldOffset, byte[] buffer, int bufferOffset, int length) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetBytes)); CheckSettingOffset(fieldOffset); SetBytesNoOffsetHandling(fieldOffset, buffer, bufferOffset, length); #if DEBUG _currentOffset += length; #endif return length; } private void SetBytesNoOffsetHandling(long fieldOffset, byte[] buffer, int bufferOffset, int length) { if (_isPlp) { if (!_plpUnknownSent) { _stateObj.Parser.WriteUnsignedLong(TdsEnums.SQL_PLP_UNKNOWNLEN, _stateObj); _plpUnknownSent = true; } // Write chunk length & chunk _stateObj.Parser.WriteInt(length, _stateObj); _stateObj.WriteByteArray(buffer, length, bufferOffset); } else { // Non-plp data must be sent in one chunk for now. #if DEBUG Debug.Assert(0 == _currentOffset, "SetBytes doesn't yet support chunking for non-plp data: " + _currentOffset); #endif Debug.Assert(!MetaType.GetMetaTypeFromSqlDbType(_metaData.SqlDbType, _metaData.IsMultiValued).IsLong, "We're assuming long length types are sent as PLP. SqlDbType = " + _metaData.SqlDbType); if (SqlDbType.Variant == _metaData.SqlDbType) { _stateObj.Parser.WriteSqlVariantHeader(4 + length, TdsEnums.SQLBIGVARBINARY, 2, _stateObj); } _stateObj.Parser.WriteShort(length, _stateObj); _stateObj.WriteByteArray(buffer, length, bufferOffset); } } internal void SetBytesLength(long length) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetBytes)); CheckSettingOffset(length); if (0 == length) { if (_isPlp) { Debug.Assert(!_plpUnknownSent, "A plpUnknown has already been sent before setting length to zero."); _stateObj.Parser.WriteLong(0, _stateObj); _plpUnknownSent = true; } else { Debug.Assert(!MetaType.GetMetaTypeFromSqlDbType(_metaData.SqlDbType, _metaData.IsMultiValued).IsLong, "We're assuming long length types are sent as PLP. SqlDbType = " + _metaData.SqlDbType); if (SqlDbType.Variant == _metaData.SqlDbType) { _stateObj.Parser.WriteSqlVariantHeader(4, TdsEnums.SQLBIGVARBINARY, 2, _stateObj); } _stateObj.Parser.WriteShort(0, _stateObj); } } if (_plpUnknownSent) { _stateObj.Parser.WriteInt(TdsEnums.SQL_PLP_CHUNK_TERMINATOR, _stateObj); _plpUnknownSent = false; } #if DEBUG _currentOffset = 0; #endif } // Semantics for SetChars are to modify existing value, not overwrite // Use in combination with SetLength to ensure overwriting when necessary // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText // (NVarChar and global clr collation assumed for variants) internal int SetChars(long fieldOffset, char[] buffer, int bufferOffset, int length) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetChars)); // ANSI types must convert to byte[] because that's the tool we have. if (MetaDataUtilsSmi.IsAnsiType(_metaData.SqlDbType)) { if (null == _encoder) { _encoder = _stateObj.Parser._defaultEncoding.GetEncoder(); } byte[] bytes = new byte[_encoder.GetByteCount(buffer, bufferOffset, length, false)]; _encoder.GetBytes(buffer, bufferOffset, length, bytes, 0, false); SetBytesNoOffsetHandling(fieldOffset, bytes, 0, bytes.Length); } else { CheckSettingOffset(fieldOffset); // Send via PLP format if we can. if (_isPlp) { // Handle initial PLP markers if (!_plpUnknownSent) { _stateObj.Parser.WriteUnsignedLong(TdsEnums.SQL_PLP_UNKNOWNLEN, _stateObj); _plpUnknownSent = true; } // Write chunk length _stateObj.Parser.WriteInt(length * ADP.CharSize, _stateObj); _stateObj.Parser.WriteCharArray(buffer, length, bufferOffset, _stateObj); } else { // Non-plp data must be sent in one chunk for now. #if DEBUG Debug.Assert(0 == _currentOffset, "SetChars doesn't yet support chunking for non-plp data: " + _currentOffset); #endif if (SqlDbType.Variant == _metaData.SqlDbType) { _stateObj.Parser.WriteSqlVariantValue(new String(buffer, bufferOffset, length), length, 0, _stateObj); } else { Debug.Assert(!MetaType.GetMetaTypeFromSqlDbType(_metaData.SqlDbType, _metaData.IsMultiValued).IsLong, "We're assuming long length types are sent as PLP. SqlDbType = " + _metaData.SqlDbType); _stateObj.Parser.WriteShort(length * ADP.CharSize, _stateObj); _stateObj.Parser.WriteCharArray(buffer, length, bufferOffset, _stateObj); } } } #if DEBUG _currentOffset += length; #endif return length; } internal void SetCharsLength(long length) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetChars)); CheckSettingOffset(length); if (0 == length) { if (_isPlp) { Debug.Assert(!_plpUnknownSent, "A plpUnknown has already been sent before setting length to zero."); _stateObj.Parser.WriteLong(0, _stateObj); _plpUnknownSent = true; } else { Debug.Assert(!MetaType.GetMetaTypeFromSqlDbType(_metaData.SqlDbType, _metaData.IsMultiValued).IsLong, "We're assuming long length types are sent as PLP. SqlDbType = " + _metaData.SqlDbType); _stateObj.Parser.WriteShort(0, _stateObj); } } if (_plpUnknownSent) { _stateObj.Parser.WriteInt(TdsEnums.SQL_PLP_CHUNK_TERMINATOR, _stateObj); _plpUnknownSent = false; } _encoder = null; #if DEBUG _currentOffset = 0; #endif } // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText internal void SetString(string value, int offset, int length) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetString)); // ANSI types must convert to byte[] because that's the tool we have. if (MetaDataUtilsSmi.IsAnsiType(_metaData.SqlDbType)) { byte[] bytes; // Optimize for common case of writing entire string if (offset == 0 && value.Length <= length) { bytes = _stateObj.Parser._defaultEncoding.GetBytes(value); } else { char[] chars = value.ToCharArray(offset, length); bytes = _stateObj.Parser._defaultEncoding.GetBytes(chars); } SetBytes(0, bytes, 0, bytes.Length); SetBytesLength(bytes.Length); } else if (SqlDbType.Variant == _metaData.SqlDbType) { Debug.Assert(null != _variantType && SqlDbType.NVarChar == _variantType.SqlDbType, "Invalid variant type"); SqlCollation collation = new SqlCollation(); collation.LCID = checked((int)_variantType.LocaleId); collation.SqlCompareOptions = _variantType.CompareOptions; if (length * ADP.CharSize > TdsEnums.TYPE_SIZE_LIMIT) { // send as varchar for length greater than 4000 byte[] bytes; // Optimize for common case of writing entire string if (offset == 0 && value.Length <= length) { bytes = _stateObj.Parser._defaultEncoding.GetBytes(value); } else { bytes = _stateObj.Parser._defaultEncoding.GetBytes(value.ToCharArray(offset, length)); } _stateObj.Parser.WriteSqlVariantHeader(9 + bytes.Length, TdsEnums.SQLBIGVARCHAR, 7, _stateObj); _stateObj.Parser.WriteUnsignedInt(collation.info, _stateObj); // propbytes: collation.Info _stateObj.WriteByte(collation.sortId); // propbytes: collation.SortId _stateObj.Parser.WriteShort(bytes.Length, _stateObj); // propbyte: varlen _stateObj.WriteByteArray(bytes, bytes.Length, 0); } else { _stateObj.Parser.WriteSqlVariantHeader(9 + length * ADP.CharSize, TdsEnums.SQLNVARCHAR, 7, _stateObj); _stateObj.Parser.WriteUnsignedInt(collation.info, _stateObj); // propbytes: collation.Info _stateObj.WriteByte(collation.sortId); // propbytes: collation.SortId _stateObj.Parser.WriteShort(length * ADP.CharSize, _stateObj); // propbyte: varlen _stateObj.Parser.WriteString(value, length, offset, _stateObj); } _variantType = null; } else if (_isPlp) { // Send the string as a complete PLP chunk. _stateObj.Parser.WriteLong(length * ADP.CharSize, _stateObj); // PLP total length _stateObj.Parser.WriteInt(length * ADP.CharSize, _stateObj); // Chunk length _stateObj.Parser.WriteString(value, length, offset, _stateObj); // Data if (length != 0) { _stateObj.Parser.WriteInt(TdsEnums.SQL_PLP_CHUNK_TERMINATOR, _stateObj); // Terminator } } else { _stateObj.Parser.WriteShort(length * ADP.CharSize, _stateObj); _stateObj.Parser.WriteString(value, length, offset, _stateObj); } } // valid for SqlDbType.SmallInt internal void SetInt16(Int16 value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetInt16)); if (SqlDbType.Variant == _metaData.SqlDbType) { _stateObj.Parser.WriteSqlVariantHeader(4, TdsEnums.SQLINT2, 0, _stateObj); } else { _stateObj.WriteByte((byte)_metaData.MaxLength); } _stateObj.Parser.WriteShort(value, _stateObj); } // valid for SqlDbType.Int internal void SetInt32(Int32 value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetInt32)); if (SqlDbType.Variant == _metaData.SqlDbType) { _stateObj.Parser.WriteSqlVariantHeader(6, TdsEnums.SQLINT4, 0, _stateObj); } else { _stateObj.WriteByte((byte)_metaData.MaxLength); } _stateObj.Parser.WriteInt(value, _stateObj); } // valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney internal void SetInt64(Int64 value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetInt64)); if (SqlDbType.Variant == _metaData.SqlDbType) { if (null == _variantType) { _stateObj.Parser.WriteSqlVariantHeader(10, TdsEnums.SQLINT8, 0, _stateObj); _stateObj.Parser.WriteLong(value, _stateObj); } else { Debug.Assert(SqlDbType.Money == _variantType.SqlDbType, "Invalid variant type"); _stateObj.Parser.WriteSqlVariantHeader(10, TdsEnums.SQLMONEY, 0, _stateObj); _stateObj.Parser.WriteInt((int)(value >> 0x20), _stateObj); _stateObj.Parser.WriteInt((int)value, _stateObj); _variantType = null; } } else { _stateObj.WriteByte((byte)_metaData.MaxLength); if (SqlDbType.SmallMoney == _metaData.SqlDbType) { _stateObj.Parser.WriteInt((int)value, _stateObj); } else if (SqlDbType.Money == _metaData.SqlDbType) { _stateObj.Parser.WriteInt((int)(value >> 0x20), _stateObj); _stateObj.Parser.WriteInt((int)value, _stateObj); } else { _stateObj.Parser.WriteLong(value, _stateObj); } } } // valid for SqlDbType.Real internal void SetSingle(Single value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetSingle)); if (SqlDbType.Variant == _metaData.SqlDbType) { _stateObj.Parser.WriteSqlVariantHeader(6, TdsEnums.SQLFLT4, 0, _stateObj); } else { _stateObj.WriteByte((byte)_metaData.MaxLength); } _stateObj.Parser.WriteFloat(value, _stateObj); } // valid for SqlDbType.Float internal void SetDouble(Double value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetDouble)); if (SqlDbType.Variant == _metaData.SqlDbType) { _stateObj.Parser.WriteSqlVariantHeader(10, TdsEnums.SQLFLT8, 0, _stateObj); } else { _stateObj.WriteByte((byte)_metaData.MaxLength); } _stateObj.Parser.WriteDouble(value, _stateObj); } // valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range) internal void SetSqlDecimal(SqlDecimal value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetSqlDecimal)); if (SqlDbType.Variant == _metaData.SqlDbType) { _stateObj.Parser.WriteSqlVariantHeader(21, TdsEnums.SQLNUMERICN, 2, _stateObj); _stateObj.WriteByte(value.Precision); // propbytes: precision _stateObj.WriteByte(value.Scale); // propbytes: scale _stateObj.Parser.WriteSqlDecimal(value, _stateObj); } else { _stateObj.WriteByte(checked((byte)MetaType.MetaDecimal.FixedLength)); // SmiMetaData's length and actual wire format's length are different _stateObj.Parser.WriteSqlDecimal(SqlDecimal.ConvertToPrecScale(value, _metaData.Precision, _metaData.Scale), _stateObj); } } // valid for DateTime, SmallDateTime, Date, DateTime2 internal void SetDateTime(DateTime value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetDateTime)); if (SqlDbType.Variant == _metaData.SqlDbType) { if ((_variantType != null) && (_variantType.SqlDbType == SqlDbType.DateTime2)) { _stateObj.Parser.WriteSqlVariantDateTime2(value, _stateObj); } else if ((_variantType != null) && (_variantType.SqlDbType == SqlDbType.Date)) { _stateObj.Parser.WriteSqlVariantDate(value, _stateObj); } else { TdsDateTime dt = MetaType.FromDateTime(value, 8); _stateObj.Parser.WriteSqlVariantHeader(10, TdsEnums.SQLDATETIME, 0, _stateObj); _stateObj.Parser.WriteInt(dt.days, _stateObj); _stateObj.Parser.WriteInt(dt.time, _stateObj); } // Clean the variant metadata to prevent sharing it with next row. // As a reminder, SetVariantType raises an assert if _variantType is not clean _variantType = null; } else { _stateObj.WriteByte((byte)_metaData.MaxLength); if (SqlDbType.SmallDateTime == _metaData.SqlDbType) { TdsDateTime dt = MetaType.FromDateTime(value, (byte)_metaData.MaxLength); Debug.Assert(0 <= dt.days && dt.days <= UInt16.MaxValue, "Invalid DateTime '" + value + "' for SmallDateTime"); _stateObj.Parser.WriteShort(dt.days, _stateObj); _stateObj.Parser.WriteShort(dt.time, _stateObj); } else if (SqlDbType.DateTime == _metaData.SqlDbType) { TdsDateTime dt = MetaType.FromDateTime(value, (byte)_metaData.MaxLength); _stateObj.Parser.WriteInt(dt.days, _stateObj); _stateObj.Parser.WriteInt(dt.time, _stateObj); } else { // date and datetime2 int days = value.Subtract(DateTime.MinValue).Days; if (SqlDbType.DateTime2 == _metaData.SqlDbType) { Int64 time = value.TimeOfDay.Ticks / TdsEnums.TICKS_FROM_SCALE[_metaData.Scale]; _stateObj.WriteByteArray(BitConverter.GetBytes(time), (int)_metaData.MaxLength - 3, 0); } _stateObj.WriteByteArray(BitConverter.GetBytes(days), 3, 0); } } } // valid for UniqueIdentifier internal void SetGuid(Guid value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetGuid)); byte[] bytes = value.ToByteArray(); Debug.Assert(SmiMetaData.DefaultUniqueIdentifier.MaxLength == bytes.Length, "Invalid length for guid bytes: " + bytes.Length); if (SqlDbType.Variant == _metaData.SqlDbType) { _stateObj.Parser.WriteSqlVariantHeader(18, TdsEnums.SQLUNIQUEID, 0, _stateObj); } else { Debug.Assert(_metaData.MaxLength == bytes.Length, "Unexpected uniqueid metadata length: " + _metaData.MaxLength); _stateObj.WriteByte((byte)_metaData.MaxLength); } _stateObj.WriteByteArray(bytes, bytes.Length, 0); } // valid for SqlDbType.Time internal void SetTimeSpan(TimeSpan value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetTime)); byte scale; byte length; if (SqlDbType.Variant == _metaData.SqlDbType) { scale = SmiMetaData.DefaultTime.Scale; length = (byte)SmiMetaData.DefaultTime.MaxLength; _stateObj.Parser.WriteSqlVariantHeader(8, TdsEnums.SQLTIME, 1, _stateObj); _stateObj.WriteByte(scale); //propbytes: scale } else { scale = _metaData.Scale; length = (byte)_metaData.MaxLength; _stateObj.WriteByte(length); } Int64 time = value.Ticks / TdsEnums.TICKS_FROM_SCALE[scale]; _stateObj.WriteByteArray(BitConverter.GetBytes(time), length, 0); } // valid for DateTimeOffset internal void SetDateTimeOffset(DateTimeOffset value) { Debug.Assert( SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetDateTimeOffset)); byte scale; byte length; if (SqlDbType.Variant == _metaData.SqlDbType) { // VSTFDevDiv #885208 - DateTimeOffset throws ArgumentException for when passing DateTimeOffset value to a sql_variant TVP // using a SqlDataRecord or SqlDataReader MSS.SmiMetaData dateTimeOffsetMetaData = MSS.SmiMetaData.DefaultDateTimeOffset; scale = MetaType.MetaDateTimeOffset.Scale; length = (byte)dateTimeOffsetMetaData.MaxLength; _stateObj.Parser.WriteSqlVariantHeader(13, TdsEnums.SQLDATETIMEOFFSET, 1, _stateObj); _stateObj.WriteByte(scale); //propbytes: scale } else { scale = _metaData.Scale; length = (byte)_metaData.MaxLength; _stateObj.WriteByte(length); } DateTime utcDateTime = value.UtcDateTime; Int64 time = utcDateTime.TimeOfDay.Ticks / TdsEnums.TICKS_FROM_SCALE[scale]; int days = utcDateTime.Subtract(DateTime.MinValue).Days; Int16 offset = (Int16)value.Offset.TotalMinutes; _stateObj.WriteByteArray(BitConverter.GetBytes(time), length - 5, 0); // time _stateObj.WriteByteArray(BitConverter.GetBytes(days), 3, 0); // date _stateObj.WriteByte((byte)(offset & 0xff)); // offset byte 1 _stateObj.WriteByte((byte)((offset >> 8) & 0xff)); // offset byte 2 } internal void SetVariantType(SmiMetaData value) { Debug.Assert(null == _variantType, "Variant type can only be set once"); Debug.Assert(value != null && (value.SqlDbType == SqlDbType.Money || value.SqlDbType == SqlDbType.NVarChar || value.SqlDbType == SqlDbType.Date || value.SqlDbType == SqlDbType.DateTime || value.SqlDbType == SqlDbType.DateTime2 || value.SqlDbType == SqlDbType.DateTimeOffset || value.SqlDbType == SqlDbType.SmallDateTime ), "Invalid variant type"); _variantType = value; } #endregion #region private methods [Conditional("DEBUG")] private void CheckSettingOffset(long offset) { #if DEBUG Debug.Assert(offset == _currentOffset, "Invalid offset passed. Should be: " + _currentOffset + ", but was: " + offset); #endif } #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace Orc.DependencyGraph.GraphB { public class GraphB<T> : Orc.Sort.TopologicalSort.TopologicalSort<T>, IGraph<T> where T : IEquatable<T> { protected IList<INode<T>> graphList; protected IList<INode<T>> graphSort; protected List<int> levelList; public GraphB() :this(true, false, 0) { } public GraphB(bool usesPriority, bool usesTracking, int capacity) : base(usesPriority, usesTracking) { this.graphList = new List<INode<T>>(capacity); this.graphSort = new List<INode<T>>(capacity); this.levelList = new List<int>(capacity); } public bool CanSort() { try { this.Sort(); } catch (TopologicalSortException) { return false; } return true; } public int CountNodes { get { return this.graphList.Count; } } public int CountLevels { get { return this.levelList.Max() + 1; } } public void AddSequence(IEnumerable<T> sequence) { var sequence_count = sequence.Count(); if (sequence_count == 0) { throw new ArgumentException("Adding failed because sequence cannot be empty."); } base.Add(sequence); int node_level = -1; foreach (var node in sequence) { int key = this.NodeKey(node); if (this.graphList.Count <= key) { this.graphList.Add(new Node<T>(this, key)); this.levelList.Add(node_level + 1); } node_level = this.levelList[key]; } if (sequence_count == 1) { return; } int key_next = 0; int key_prev = this.NodeKey(sequence.First()); foreach (var node in sequence.Skip(1)) { key_next = this.NodeKey(node); int lvl_diff = this.levelList[key_prev] - this.levelList[key_next] + 1; int lvl_root = 0; if (lvl_diff > 0) { this.levelList[key_prev] -= lvl_diff; lvl_root = Math.Min(lvl_root, this.levelList[key_prev]); foreach (int key_prec in this.GetPrecedents(key_prev, false, false)) { this.levelList[key_prec] -= lvl_diff; lvl_root = Math.Min(lvl_root, this.levelList[key_prec]); } } if (lvl_root < 0) { for (int key = 0; key < this.levelList.Count; key++) { this.levelList[key] -= lvl_root; } } key_prev = key_next; } this.levelList[key_next] = this.GetPrecedents(key_next, true, false).Max(i => this.levelList[i]) + 1; } public void AddSequences(IEnumerable<IEnumerable<T>> sequences) { foreach (var sequence in sequences) { this.AddSequence(sequence); } } public IEnumerable<INode<T>> Nodes { get; private set; } public INode<T> Find(T node) { int key; if (!nodesDict.TryGetValue(node, out key)) return null; else return this.graphList[key]; } public IOrderedEnumerable<INode<T>> GetNodes(int level) { return new OrderedEnumerable<INode<T>>(() => this.graphList.Where(n => n.Level == level)); } public IOrderedEnumerable<INode<T>> GetNodesBetween(int levelFrom, int levelTo) { return new OrderedEnumerable<INode<T>>(() => this.graphList.Where(n => levelFrom <= n.Level && n.Level <= levelTo).OrderBy(n => n.Level)); } public IEnumerable<INode<T>> GetNodesRelatedTo(T node) { int key; if (!nodesDict.TryGetValue(node, out key)) throw new ArgumentException("node note present in graph"); var set = new SortedSet<int>(); set.UnionWith(GetPrecedents(key, false, false)); set.UnionWith(GetDependents(key, false, false)); return set.Select(k => this.graphList[k]); } public IEnumerable<INode<T>> GetNodesRelatedTo(T node, int levelFrom, int levelTo) { return this.GetNodesRelatedTo(node).Where(n => levelFrom <= n.Level && n.Level <= levelTo); } public IOrderedEnumerable<INode<T>> Sort() { base.Sort(); if (nodesSort == null) { // return null; throw new TopologicalSortException("Topological sort failed due to loops in the graph"); } else if (nodesSort.Count != this.graphSort.Count) { this.graphSort = nodesSort.Select(this.Find).ToList(); } return new OrderedEnumerable<INode<T>>(() => this.graphSort); } public IEnumerable<INode<T>> GetRootNodes() { return GetNodes(0); } public IEnumerable<INode<T>> GetLeafNodes() { return GetNodes(this.levelList.Max()); } /* protected override int NodeKey(T node) { int key = base.NodeKey(node); if (this.graphList.Count <= key) { this.graphList.Add(new Node<T>(this, key)); this.levelList.Add(-1); } return key; } */ public class Node<N> : INode<N> where N : IEquatable<N> { public Node(GraphB<N> graph, int index) { this.Graph = graph; this.key = index; } private int key; public N Value { get { return this.Graph.nodesList[this.key]; } } public GraphB<N> Graph { get; private set; } public int Level { get { return this.Graph.levelList[this.key]; } } public IOrderedEnumerable<INode<N>> GetNeighbours(int relativeLevelFrom, int relativeLevelTo) { int levelFrom = this.Level + relativeLevelFrom; int levelTo = this.Level + relativeLevelTo; return new OrderedEnumerable<INode<N>>(() => this.Graph.GetNodesRelatedTo(this.Value, levelFrom, levelTo).OrderBy(n => n.Level)); } // relativeLevel < 0 public IOrderedEnumerable<INode<N>> Precedents { get { return new OrderedEnumerable<INode<N>>(() => this.Graph.GetPrecedents(this.key, false, false).OrderBy(i => this.Graph.levelList[i]).Select(i => this.Graph.graphList[i])); } } // relativeLevel > 0 public IOrderedEnumerable<INode<N>> Descendants { get { return new OrderedEnumerable<INode<N>>(() => this.Graph.GetDependents(this.key, false, false).OrderBy(i => this.Graph.levelList[i]).Select(i => this.Graph.graphList[i])); } } // parents public IOrderedEnumerable<INode<N>> ImmediatePrecedents { get { return new OrderedEnumerable<INode<N>>(() => this.Graph.GetPrecedents(this.key, true, false).OrderBy(i => this.Graph.levelList[i]).Select(i => this.Graph.graphList[i])); } } // children public IOrderedEnumerable<INode<N>> ImmediateDescendants { get { return new OrderedEnumerable<INode<N>>(() => this.Graph.GetDependents(this.key, true, false).OrderBy(i => this.Graph.levelList[i]).Select(i => this.Graph.graphList[i])); } } // relativeLevel == 0 public IOrderedEnumerable<INode<N>> TerminatingPrecedents { get { return new OrderedEnumerable<INode<N>>(() => this.Graph.GetPrecedents(this.key, false, true).OrderBy(i => this.Graph.levelList[i]).Select(i => this.Graph.graphList[i])); } } // relativeLevel == this.Graph.CountLevel-1 public IOrderedEnumerable<INode<N>> TerminatingDescendants { get { return new OrderedEnumerable<INode<N>>(() => this.Graph.GetDependents(this.key, false, true).OrderBy(i => this.Graph.levelList[i]).Select(i => this.Graph.graphList[i])); } } public INode<N> Next { get { if (this.key + 1 >= this.Graph.graphList.Count) return null; else return this.Graph.graphList[this.key + 1]; } } public INode<N> Previous { get { if (this.key - 1 < 0) return null; else return this.Graph.graphList[this.key - 1]; } } public override string ToString() { return String.Format("Node({0},{1},{2},{3})", this.Value, this.Level, this.ImmediatePrecedents.Count(), this.ImmediateDescendants.Count()); } } } }
#if !SILVERLIGHT && !MONOTOUCH && !XBOX && !ANDROIDINDIE using System; using System.IO; using System.Net; using System.Xml; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using ServiceStack.Common.Utils; using ServiceStack.ServiceHost; using ServiceStack.ServiceInterface.ServiceModel; namespace ServiceStack.ServiceClient.Web { /// <summary> /// Adds the singleton instance of <see cref="CookieManagerMessageInspector"/> to an endpoint on the client. /// </summary> /// <remarks> /// Based on http://megakemp.wordpress.com/2009/02/06/managing-shared-cookies-in-wcf/ /// </remarks> public class CookieManagerEndpointBehavior : IEndpointBehavior { public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { return; } /// <summary> /// Adds the singleton of the <see cref="ClientIdentityMessageInspector"/> class to the client endpoint's message inspectors. /// </summary> /// <param name="endpoint">The endpoint that is to be customized.</param> /// <param name="clientRuntime">The client runtime to be customized.</param> public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { var cm = CookieManagerMessageInspector.Instance; cm.Uri = endpoint.ListenUri.AbsoluteUri; clientRuntime.MessageInspectors.Add(cm); } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { return; } public void Validate(ServiceEndpoint endpoint) { return; } } /// <summary> /// Maintains a copy of the cookies contained in the incoming HTTP response received from any service /// and appends it to all outgoing HTTP requests. /// </summary> /// <remarks> /// This class effectively allows to send any received HTTP cookies to different services, /// reproducing the same functionality available in ASMX Web Services proxies with the <see cref="System.Net.CookieContainer"/> class. /// Based on http://megakemp.wordpress.com/2009/02/06/managing-shared-cookies-in-wcf/ /// </remarks> public class CookieManagerMessageInspector : IClientMessageInspector { private static CookieManagerMessageInspector instance; private CookieContainer cookieContainer; public string Uri { get; set; } /// <summary> /// Initializes a new instance of the <see cref="ClientIdentityMessageInspector"/> class. /// </summary> public CookieManagerMessageInspector() { cookieContainer = new CookieContainer(); Uri = "http://tempuri.org"; } public CookieManagerMessageInspector(string uri) { cookieContainer = new CookieContainer(); Uri = uri; } /// <summary> /// Gets the singleton <see cref="ClientIdentityMessageInspector" /> instance. /// </summary> public static CookieManagerMessageInspector Instance { get { if (instance == null) { instance = new CookieManagerMessageInspector(); } return instance; } } /// <summary> /// Inspects a message after a reply message is received but prior to passing it back to the client application. /// </summary> /// <param name="reply">The message to be transformed into types and handed back to the client application.</param> /// <param name="correlationState">Correlation state data.</param> public void AfterReceiveReply(ref Message reply, object correlationState) { var httpResponse = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty; if (httpResponse != null) { string cookie = httpResponse.Headers[HttpResponseHeader.SetCookie]; if (!string.IsNullOrEmpty(cookie)) { cookieContainer.SetCookies(new System.Uri(Uri), cookie); } } } /// <summary> /// Inspects a message before a request message is sent to a service. /// </summary> /// <param name="request">The message to be sent to the service.</param> /// <param name="channel">The client object channel.</param> /// <returns> /// <strong>Null</strong> since no message correlation is used. /// </returns> public object BeforeSendRequest(ref Message request, IClientChannel channel) { HttpRequestMessageProperty httpRequest; // The HTTP request object is made available in the outgoing message only when // the Visual Studio Debugger is attacched to the running process if (!request.Properties.ContainsKey(HttpRequestMessageProperty.Name)) { request.Properties.Add(HttpRequestMessageProperty.Name, new HttpRequestMessageProperty()); } httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]; httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieContainer.GetCookieHeader(new System.Uri(Uri))); return null; } } public abstract class WcfServiceClient : IWcfServiceClient { const string XPATH_SOAP_FAULT = "/s:Fault"; const string XPATH_SOAP_FAULT_REASON = "/s:Fault/s:Reason"; const string NAMESPACE_SOAP = "http://www.w3.org/2003/05/soap-envelope"; const string NAMESPACE_SOAP_ALIAS = "s"; public string Uri { get; set; } public abstract void SetProxy(Uri proxyAddress); protected abstract MessageVersion MessageVersion { get; } protected abstract Binding Binding { get; } /// <summary> /// Specifies if cookies should be stored /// </summary> // CCB Custom public bool StoreCookies { get; set; } public WcfServiceClient() { // CCB Custom this.StoreCookies = true; } private static XmlNamespaceManager GetNamespaceManager(XmlDocument doc) { var nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace(NAMESPACE_SOAP_ALIAS, NAMESPACE_SOAP); return nsmgr; } private static Exception CreateException(Exception e, XmlReader reader) { var doc = new XmlDocument(); doc.Load(reader); var node = doc.SelectSingleNode(XPATH_SOAP_FAULT, GetNamespaceManager(doc)); if (node != null) { string errMsg = null; var nodeReason = doc.SelectSingleNode(XPATH_SOAP_FAULT_REASON, GetNamespaceManager(doc)); if (nodeReason != null) { errMsg = nodeReason.FirstChild.InnerXml; } return new Exception(string.Format("SOAP FAULT '{0}': {1}", errMsg, node.InnerXml), e); } return e; } private ServiceEndpoint SyncReply { get { var contract = new ContractDescription("ServiceStack.ServiceClient.Web.ISyncReply", "http://services.servicestack.net/"); var addr = new EndpointAddress(Uri); var endpoint = new ServiceEndpoint(contract, Binding, addr); return endpoint; } } public Message Send(object request) { return Send(request, request.GetType().Name); } public Message Send(object request, string action) { return Send(Message.CreateMessage(MessageVersion, action, request)); } public Message Send(XmlReader reader, string action) { return Send(Message.CreateMessage(MessageVersion, action, reader)); } public Message Send(Message message) { using (var client = new GenericProxy<ISyncReply>(SyncReply)) { // CCB Custom...add behavior to propagate cookies across SOAP method calls if (StoreCookies) client.ChannelFactory.Endpoint.Behaviors.Add(new CookieManagerEndpointBehavior()); var response = client.Proxy.Send(message); return response; } } public static T GetBody<T>(Message message) { var buffer = message.CreateBufferedCopy(int.MaxValue); try { return buffer.CreateMessage().GetBody<T>(); } catch (Exception ex) { throw CreateException(ex, buffer.CreateMessage().GetReaderAtBodyContents()); } } public T Send<T>(object request) { try { var responseMsg = Send(request); var response = responseMsg.GetBody<T>(); var responseStatus = GetResponseStatus(response); if (responseStatus != null && !string.IsNullOrEmpty(responseStatus.ErrorCode)) { throw new WebServiceException(responseStatus.Message, null) { StatusCode = 500, ResponseDto = response, StatusDescription = responseStatus.Message, }; } return response; } catch (WebServiceException webEx) { throw; } catch (Exception ex) { var webEx = ex as WebException ?? ex.InnerException as WebException; if (webEx == null) { throw new WebServiceException(ex.Message, ex) { StatusCode = 500, }; } var httpEx = webEx.Response as HttpWebResponse; throw new WebServiceException(webEx.Message, webEx) { StatusCode = httpEx != null ? (int)httpEx.StatusCode : 500 }; } } public TResponse Send<TResponse>(IReturn<TResponse> request) { return Send<TResponse>((object)request); } public void Send(IReturnVoid request) { throw new NotImplementedException(); } public ResponseStatus GetResponseStatus(object response) { if (response == null) return null; var hasResponseStatus = response as IHasResponseStatus; if (hasResponseStatus != null) return hasResponseStatus.ResponseStatus; var propertyInfo = response.GetType().GetProperty("ResponseStatus"); if (propertyInfo == null) return null; return ReflectionUtils.GetProperty(response, propertyInfo) as ResponseStatus; } public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, string mimeType) { throw new NotImplementedException(); } public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType) { throw new NotImplementedException(); } public void SendOneWay(object request) { SendOneWay(request, request.GetType().Name); } public void SendOneWay(string relativeOrAbsoluteUrl, object request) { SendOneWay(Message.CreateMessage(MessageVersion, relativeOrAbsoluteUrl, request)); } public void SendOneWay(object request, string action) { SendOneWay(Message.CreateMessage(MessageVersion, action, request)); } public void SendOneWay(XmlReader reader, string action) { SendOneWay(Message.CreateMessage(MessageVersion, action, reader)); } public void SendOneWay(Message message) { using (var client = new GenericProxy<IOneWay>(SyncReply)) { client.Proxy.SendOneWay(message); } } public void SendAsync<TResponse>(object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void SetCredentials(string userName, string password) { throw new NotImplementedException(); } public void GetAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void DeleteAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void PostAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void PostAsync<TResponse>(object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void PutAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void CustomMethodAsync<TResponse>(string httpVerb, IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void CancelAsync() { throw new NotImplementedException(); } public void Dispose() { } public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request) { throw new NotImplementedException(); } public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request) { throw new NotImplementedException(); } } } #endif
using HadoukInput; using InputHelper; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MenuBuddy { /// <summary> /// Base class for screens that contain a menu of options. The user can /// move up and down to select an entry, or cancel to back out of the screen. /// </summary> public class MenuScreen : WidgetScreen, IMenuScreen { #region Properties protected class TabbedItem { public int TabOrder { get; set; } public int TabSubOrder { get; set; } public IScreenItem Widget { get; set; } public override string ToString() { return Widget.ToString(); } } /// <summary> /// The game type, as loaded from the screenmanager.game /// </summary> private GameType _gameType; /// <summary> /// Gets the list of menu entries, so derived classes can add or change the menu contents. /// </summary> private List<TabbedItem> MenuItems { get; set; } = new List<TabbedItem>(); /// <summary> /// Get the currently selected menu entry index, -1 if no entry selected /// </summary> public int SelectedIndex { get; set; } /// <summary> /// Get the currently selected menu entry, null if no menu entry selected /// </summary> public IScreenItem SelectedItem { get { if ((GameType.Controller == _gameType) && (SelectedIndex > -1) && (SelectedIndex < MenuItems.Count)) { return MenuItems[SelectedIndex].Widget; } //no menu entry selected or something is not setup correctly return null; } } #endregion #region Methods /// <summary> /// Constructor. /// </summary> public MenuScreen(string menuTitle = "", ContentManager content = null) : base(menuTitle, content) { CoverOtherScreens = true; CoveredByOtherScreens = true; } public override Task LoadContent() { var game = ScreenManager?.Game as DefaultGame; _gameType = null != game ? game.GameType : GameType.Controller; return base.LoadContent(); } public override void UnloadContent() { base.UnloadContent(); MenuItems = null; } public void AddMenuItem(IScreenItem menuItem, int tabOrder = 0) { //create the tab item var tabItem = new TabbedItem { TabOrder = tabOrder, TabSubOrder = MenuItems.Count, Widget = menuItem }; MenuItems.Add(tabItem); //Sort the list MenuItems.Sort((a, b) => { if (a.TabOrder != b.TabOrder) { return a.TabOrder.CompareTo(b.TabOrder); } else { return a.TabSubOrder.CompareTo(b.TabSubOrder); } }); } #endregion //Methods #region Handle Input public void HandleInput(IInputState input) { var inputState = input as InputState; if (null == inputState) { return; } //Check all the input if (inputState.IsMenuUp(ControllingPlayer)) { // Move to the previous menu entry MenuUp(); } else if (inputState.IsMenuDown(ControllingPlayer)) { // Move to the next menu entry MenuDown(); } //checkl the left/right messages if (inputState.IsMenuLeft(ControllingPlayer)) { //send a left message to the current menu entry MenuLeft(); } else if (inputState.IsMenuRight(ControllingPlayer)) { //send a right message to the current menu entry MenuRight(); } // Accept or cancel the menu? We pass in our ControllingPlayer, which may // either be null (to accept input from any player) or a specific index. // If we pass a null controlling player, the InputState helper returns to // us which player actually provided the input. We pass that through to // OnSelectEntry and OnCancel, so they can tell which player triggered them. if (inputState.IsMenuSelect(ControllingPlayer, out int playerIndex)) { var selectedItem = SelectedItem as IButton; if (null != selectedItem) { selectedItem.Clicked(this, new ClickEventArgs { PlayerIndex = playerIndex }); } } else if (inputState.IsMenuCancel(ControllingPlayer, out playerIndex)) { Cancelled(this, new ClickEventArgs { PlayerIndex = playerIndex }); } var highlightable = SelectedItem as IHighlightable; if (null != highlightable && highlightable.Highlightable) { highlightable.IsHighlighted = IsActive; } } private void MenuUp() { if (MenuItems.Count > 1) { //don't roll over SetSelectedIndex(Math.Max(0, SelectedIndex - 1)); } } private void MenuDown() { if (MenuItems.Count > 1) { //don't roll over SetSelectedIndex(Math.Min(SelectedIndex + 1, MenuItems.Count - 1)); } } public void SetSelectedIndex(int index) { SelectedIndex = index; HighlightSelectedItem(); ResetInputTimer(); } public void SetSelectedItem(IScreenItem item) { SetSelectedIndex(MenuItems.FindIndex(x => x.Widget == item)); } private void MenuLeft() { var menuEntry = SelectedItem as ILeftRightItem; if (null != menuEntry) { //run the sleected evetn menuEntry.OnLeftEntry(); ResetInputTimer(); } } private void MenuRight() { var menuEntry = SelectedItem as ILeftRightItem; if (null != menuEntry) { //run the sleected evetn menuEntry.OnRightEntry(); ResetInputTimer(); } } /// <summary> /// Remove a menu entry from the menu /// </summary> /// <param name="entry"></param> public void RemoveMenuItem(IScreenItem entry) { //try to remove the entry from the list RemoveMenuItem(MenuItems.FirstOrDefault(x => x.Widget == entry)); } /// <summary> /// Remove a menu entry from the menu /// </summary> /// <param name="index">the index of the item to remove</param> public virtual void RemoveMenuItem(int index) { //check if there are enough items if (index < MenuItems.Count()) { RemoveMenuItem(MenuItems[index]); } } private void RemoveMenuItem(TabbedItem item) { //try to remove the entry from the list if (null != item && MenuItems.Remove(item)) { //set the selected item if needed if (SelectedIndex >= MenuItems.Count) { SelectedIndex = MenuItems.Count - 1; } } } private void HighlightSelectedItem() { //set teh highlighted item for (int i = 0; i < MenuItems.Count; i++) { var highlightable = MenuItems[i].Widget as IHighlightable; if (null != highlightable) { var position = i == SelectedIndex ? SelectedItem.Position.ToVector2() : Vector2.Zero; highlightable.CheckHighlight(new HighlightEventArgs(position, ScreenManager.DefaultGame.InputHelper)); } } } public virtual void Cancelled(object obj, ClickEventArgs e) { ExitScreen(); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.Comm { using System; using System.Diagnostics; using System.Linq; using System.Reflection; /// <summary> /// Interface representing a message of an unknown payload type. /// </summary> /// <remarks>A message can contain either a payload or an error.</remarks> public interface IMessage { /// <summary> /// Gets the payload as a <see cref="IBonded"/> value. /// </summary> /// <exception cref="InvalidOperationException"> /// Thrown when the message contains an error and not a payload. /// </exception> IBonded RawPayload { get; } /// <summary> /// Gets the error, if any. /// </summary> /// <remarks> /// If the message has a payload and no error, <c>null</c> is returned. /// </remarks> IBonded<Error> Error { get; } /// <summary> /// Gets a value indicating whether the message contains an error. /// </summary> /// <remarks> /// If a message does not contain an error, it contains a payload. /// </remarks> bool IsError { get; } /// <summary> /// Converts this message to a /// <see cref="IMessage{T}">IMessage&lt;U&gt;</see>. /// </summary> /// <typeparam name="U">The type of the message payload.</typeparam> /// <returns> /// An instance of <see cref="IMessage{T}">IMessage&lt;U&gt;</see>. If /// the conversion fails, <c>null</c> is returned. /// </returns> IMessage<U> Convert<U>(); } /// <summary> /// Interface representing a message of specific payload type. /// </summary> /// <typeparam name="T">The type of the message payload.</typeparam> /// <remarks>A message can contain either a payload or an error.</remarks> public interface IMessage<out T> : IMessage { /// <summary> /// Gets the payload as a <see cref="IBonded{T}">IBonded&lt;T&gt;</see> /// value. /// </summary> /// <exception cref="InvalidOperationException"> /// Thrown when the message contains an error and not a payload. /// </exception> IBonded<T> Payload { get; } } /// <summary> /// A message of an unknown payload type. /// </summary> public class Message : IMessage { private IBonded payload; private IBonded<Error> error; /// <summary> /// Initializes a Message with the given payload. /// </summary> /// <param name="payload">The payload for the message.</param> public Message(IBonded payload) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } this.payload = payload; error = null; } // To create an error Message, use Message.FromError<TPayload>() or Message.FromError(). // // This ctor is internal so that a non-error Message<Error> can be created. If this // were public, then new Message<Error>(SomeError) would resolve to this ctor, creating an // Error message, instead of to the generic ctor. We need new Message<Error>(SomeError) to // resolve to the generic ctor to create a non-error Message. internal Message(IBonded<Error> error) { if (error == null) { throw new ArgumentNullException(nameof(error)); } payload = null; this.error = error; } /// <summary> /// Creates a message from the given payload. /// </summary> /// <param name="payload">The payload for the message.</param> /// <returns>A payload message of unknown payload type.</returns> public static IMessage FromPayload(IBonded payload) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } return new Message(payload); } /// <summary> /// Creates a message from the given payload. /// </summary> /// <typeparam name="TPayload"> /// The type of the message payload. /// </typeparam> /// <param name="payload">The payload for the message.</param> /// <returns>A payload message of the given payload type.</returns> public static IMessage<TPayload> FromPayload<TPayload>(TPayload payload) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } return FromPayload(MakeIBonded(payload)); } /// <summary> /// Creates a message from the given payload. /// </summary> /// <typeparam name="TPayload"> /// The type of the message payload. /// </typeparam> /// <param name="payload">The payload for the message.</param> /// <returns>A payload message of the given payload type.</returns> public static IMessage<TPayload> FromPayload<TPayload>(IBonded<TPayload> payload) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } return new Message<TPayload>(payload); } /// <summary> /// Creates an error message from the given error. /// </summary> /// <typeparam name="TPayload"> /// The type of the message payload /// </typeparam> /// <param name="err">The error for the message.</param> /// <returns>An error message of the given payload type.</returns> public static IMessage<TPayload> FromError<TPayload>(Error err) { if (err == null) { throw new ArgumentNullException(nameof(err)); } if (err.error_code == (int)ErrorCode.OK) { throw new ArgumentException("Error must have a non-zero error code.", nameof(err)); } return FromError<TPayload>(MakeIBonded(err)); } /// <summary> /// Creates an error message from the given error. /// </summary> /// <typeparam name="TPayload"> /// The type of the message payload. /// </typeparam> /// <param name="err">The error for the message.</param> /// <returns>An error message of the given payload type.</returns> public static IMessage<TPayload> FromError<TPayload>(IBonded<Error> err) { if (err == null) { throw new ArgumentNullException(nameof(err)); } return new Message<TPayload>(err); } /// <summary> /// Creates an error message from the given error. /// </summary> /// <param name="err">The error for the message.</param> /// <returns>An error message of unknown payload type.</returns> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="err"/> has a zero /// <see cref="Comm.Error.error_code"/>. /// </exception> public static IMessage FromError(Error err) { if (err == null) { throw new ArgumentNullException(nameof(err)); } if (err.error_code == (int)ErrorCode.OK) { throw new ArgumentException("Error must have a non-zero error code.", nameof(err)); } return FromError(MakeIBonded(err)); } /// <summary> /// Creates an error message from the given error. /// </summary> /// <param name="err">The error for the message.</param> /// <returns>An error message of unknown payload type.</returns> public static IMessage FromError(IBonded<Error> err) { if (err == null) { throw new ArgumentNullException(nameof(err)); } // can't check that err has a non-zero error code without deserializaing, so we skip that return new Message(err); } internal static IBonded<TActual> MakeIBonded<TActual>(TActual payload) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } Type ibondedType = typeof (Bonded<>).MakeGenericType(payload.GetType()); return (IBonded<TActual>) Activator.CreateInstance(ibondedType, payload); } public IBonded RawPayload { get { if (IsError) { throw new InvalidOperationException("The Payload of this message cannot be accessed, as this message contains an Error."); } Debug.Assert(payload != null); return payload; } } public IBonded<Error> Error { get { Debug.Assert((payload == null) ^ (error == null)); return error; } } public bool IsError { get { Debug.Assert((payload == null) ^ (error == null)); return error != null; } } public IMessage<U> Convert<U>() { if (IsError) { return FromError<U>(error); } else { return FromPayload(payload.Convert<U>()); } } } /// <summary> /// A message of known type. /// </summary> /// <typeparam name="TPayload">The type of the message payload.</typeparam> public class Message<TPayload> : Message, IMessage<TPayload> { /// <summary> /// Creates a payload message from the given payload. /// </summary> /// <param name="payload">The message payload.</param> public Message(TPayload payload) : base(Message.MakeIBonded(payload)) { } /// <summary> /// Creates a payload message from the given payload. /// </summary> /// <param name="payload">The message payload.</param> public Message(IBonded<TPayload> payload) : base(payload) { } internal Message(IBonded<Error> error) : base(error) { } public IBonded<TPayload> Payload { get { return RawPayload.Convert<TPayload>(); } } } }
using UnityEngine; using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; namespace GameDataEditor { [Flags] public enum BasicFieldType { Undefined = 0, Bool = 1, Int = 2, Float = 4, String = 8, Vector2 = 16, Vector3 = 32, Vector4 = 64, Color = 128, GameObject = 256, Texture2D = 512, Material = 1024, AudioClip = 2048 } public partial class GDEDataManager { private static bool isInitialized = false; #region Data Collections private static Dictionary<string, object> dataDictionary = null; private static Dictionary<string, List<string>> dataKeysBySchema = null; public static Dictionary<string, object> DataDictionary { get { return dataDictionary; } } #endregion #region Properties private static string _dataFilePath; public static string DataFilePath { private set { _dataFilePath = value; } get { return _dataFilePath; } } #endregion #region Init Methods /// <summary> /// Loads the specified data file /// </summary> /// <param name="filePath">Data file path.</param> /// <param name="encrypted">Indicates whether data file is encrypted</param> /// <returns>True if initialized, false otherwise</returns> public static bool Init(string filePath, bool encrypted = false) { bool result = true; if (isInitialized) return result; try { DataFilePath = filePath; TextAsset dataAsset = Resources.Load(DataFilePath) as TextAsset; Init(dataAsset, encrypted); isInitialized = true; } catch (Exception ex) { Debug.LogError(ex); result = false; } return result; } /// <summary> /// Loads GDE data from the specified TextAsset /// </summary> /// <param name="dataAsset">TextAsset that contains GDE data</param> public static bool Init(TextAsset dataAsset, bool encrypted = false) { bool result = true; if (isInitialized) return result; else if (dataAsset == null) { Debug.LogError(GDMConstants.ErrorTextAssetNull); return false; } try { string dataContent = string.Empty; if (encrypted) dataContent = DecryptGDEData(dataAsset.bytes); else dataContent = dataAsset.text; InitFromText(dataContent); isInitialized = true; } catch(Exception ex) { Debug.LogError(ex); result = false; } return result; } /// <summary> /// Loads GDE data from a string /// </summary> /// <param name="dataString">String that contains GDE data</param> public static bool InitFromText(string dataString) { bool result = true; if (isInitialized) return result; try { dataDictionary = Json.Deserialize(dataString) as Dictionary<string, object>; BuildDataKeysBySchemaList(); isInitialized = true; } catch(Exception ex) { Debug.LogError(ex); result = false; } return result; } public static string DecryptGDEData(byte[] encryptedContent) { GDECrypto gdeCrypto = null; TextAsset gdeCryptoResource = (TextAsset)Resources.Load(GDMConstants.MetaDataFileName, typeof(TextAsset)); byte[] bytes = Convert.FromBase64String(gdeCryptoResource.text); Resources.UnloadAsset(gdeCryptoResource); using (var stream = new MemoryStream(bytes)) { BinaryFormatter bin = new BinaryFormatter(); gdeCrypto = (GDECrypto)bin.Deserialize(stream); } string content = string.Empty; if (gdeCrypto != null) content = gdeCrypto.Decrypt(encryptedContent); return content; } /// <summary> /// Builds the data keys by schema list for lookups by schema. /// </summary> private static void BuildDataKeysBySchemaList() { dataKeysBySchema = new Dictionary<string, List<string>>(); foreach(KeyValuePair<string, object> pair in dataDictionary) { if (pair.Key.StartsWith(GDMConstants.SchemaPrefix)) continue; // Get the schema for the current data set string schema; Dictionary<string, object> currentDataSet = pair.Value as Dictionary<string, object>; currentDataSet.TryGetString(GDMConstants.SchemaKey, out schema); // Add it to the list of data keys by type List<string> dataKeyList; if (dataKeysBySchema.TryGetValue(schema, out dataKeyList)) { dataKeyList.Add(pair.Key); } else { dataKeyList = new List<string>(); dataKeyList.Add(pair.Key); dataKeysBySchema.Add(schema, dataKeyList); } } } #endregion #region Data Access Methods /// <summary> /// Get the data associated with the specified key in a Dictionary<string, object> /// </summary> /// <param name="key">Key</param> /// <param name="data">Data</param> public static bool Get(string key, out Dictionary<string, object> data) { if (dataDictionary == null) { data = null; return false; } bool result = true; object temp; result = dataDictionary.TryGetValue(key, out temp); data = temp as Dictionary<string, object>; return result; } /// <summary> /// Returns a subset of the data containing only data sets by the given schema /// </summary> /// <returns><c>true</c>, if the given schema exists <c>false</c> otherwise.</returns> /// <param name="type">Schema.</param> /// <param name="data">Subset of the Data Set list containing entries with the specified schema.</param> public static bool GetAllDataBySchema(string schema, out Dictionary<string, object> data) { if (dataDictionary == null) { data = null; return false; } List<string> dataKeys; bool result = true; data = new Dictionary<string, object>(); if (dataKeysBySchema.TryGetValue(schema, out dataKeys)) { foreach(string dataKey in dataKeys) { Dictionary<string, object> currentDataSet; if (Get(dataKey, out currentDataSet)) data.Add(dataKey.Clone().ToString(), currentDataSet.DeepCopy()); } } else result = false; return result; } /// <summary> /// Gets all data keys by schema. /// </summary> /// <returns><c>true</c>, if the given schema exists <c>false</c> otherwise.</returns> /// <param name="schema">Schema.</param> /// <param name="dataKeys">Data Key List.</param> public static bool GetAllDataKeysBySchema(string schema, out List<string> dataKeys) { if (dataDictionary == null) { dataKeys = null; return false; } return dataKeysBySchema.TryGetValue(schema, out dataKeys); } public static void ResetToDefault(string itemName, string fieldName) { PlayerPrefs.DeleteKey(itemName + "_" + fieldName); } #endregion #region Get Saved Data Methods (Basic Types) public static string GetString(string key, string defaultVal) { string retVal = defaultVal; try { retVal = PlayerPrefs.GetString(key, retVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<string> GetStringList(string key, List<string> defaultVal) { List<string> retVal = defaultVal; try { retVal = GDEPPX.GetStringList(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<List<string>> GetStringTwoDList(string key, List<List<string>> defaultVal) { List<List<string>> retVal = defaultVal; try { retVal = GDEPPX.Get2DStringList(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static int GetInt(string key, int defaultVal) { int retVal = defaultVal; try { retVal = PlayerPrefs.GetInt(key, retVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<int> GetIntList(string key, List<int> defaultVal) { List<int> retVal = defaultVal; try { retVal = GDEPPX.GetIntList(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<List<int>> GetIntTwoDList(string key, List<List<int>> defaultVal) { List<List<int>> retVal = defaultVal; try { retVal = GDEPPX.Get2DIntList(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static float GetFloat(string key, float defaultVal) { float retVal = defaultVal; try { retVal = PlayerPrefs.GetFloat(key, retVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<float> GetFloatList(string key, List<float> defaultVal) { List<float> retVal = defaultVal; try { retVal = GDEPPX.GetFloatList(key, retVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<List<float>> GetFloatTwoDList(string key, List<List<float>> defaultVal) { List<List<float>> retVal = defaultVal; try { retVal = GDEPPX.Get2DFloatList(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static bool GetBool(string key, bool defaultVal) { bool retVal = defaultVal; try { retVal = GDEPPX.GetBool(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<bool> GetBoolList(string key, List<bool> defaultVal) { List<bool> retVal = defaultVal; try { retVal = GDEPPX.GetBoolList(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<List<bool>> GetBoolTwoDList(string key, List<List<bool>> defaultVal) { List<List<bool>> retVal = defaultVal; try { retVal = GDEPPX.Get2DBoolList(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static Color32 GetColor(string key, Color32 defaultVal) { Color32 retVal = defaultVal; try { retVal = GDEPPX.GetColor(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<Color> GetColorList(string key, List<Color> defaultVal) { List<Color> retVal = defaultVal; try { retVal = GDEPPX.GetColorList(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<List<Color>> GetColorTwoDList(string key, List<List<Color>> defaultVal) { List<List<Color>> retVal = defaultVal; try { retVal = GDEPPX.Get2DColorList(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static Vector2 GetVector2(string key, Vector2 defaultVal) { Vector2 retVal = defaultVal; try { retVal = GDEPPX.GetVector2(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<Vector2> GetVector2List(string key, List<Vector2> defaultVal) { List<Vector2> retVal = defaultVal; try { retVal = GDEPPX.GetVector2List(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<List<Vector2>> GetVector2TwoDList(string key, List<List<Vector2>> defaultVal) { List<List<Vector2>> retVal = defaultVal; try { retVal = GDEPPX.Get2DVector2List(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static Vector3 GetVector3(string key, Vector3 defaultVal) { Vector3 retVal = defaultVal; try { retVal = GDEPPX.GetVector3(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<Vector3> GetVector3List(string key, List<Vector3> defaultVal) { List<Vector3> retVal = defaultVal; try { retVal = GDEPPX.GetVector3List(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<List<Vector3>> GetVector3TwoDList(string key, List<List<Vector3>> defaultVal) { List<List<Vector3>> retVal = defaultVal; try { retVal = GDEPPX.Get2DVector3List(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static Vector4 GetVector4(string key, Vector4 defaultVal) { Vector4 retVal = defaultVal; try { retVal = GDEPPX.GetVector4(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<Vector4> GetVector4List(string key, List<Vector4> defaultVal) { List<Vector4> retVal = defaultVal; try { retVal = GDEPPX.GetVector4List(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<List<Vector4>> GetVector4TwoDList(string key, List<List<Vector4>> defaultVal) { List<List<Vector4>> retVal = defaultVal; try { retVal = GDEPPX.Get2DVector4List(key, defaultVal); } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static GameObject GetGameObject(string key, GameObject defaultVal) { return defaultVal; } public static List<GameObject> GetGameObjectList(string key, List<GameObject> defaultVal) { return defaultVal; } public static List<List<GameObject>> GetGameObjectTwoDList(string key, List<List<GameObject>> defaultVal) { return defaultVal; } public static Texture2D GetTexture2D(string key, Texture2D defaultVal) { return defaultVal; } public static List<Texture2D> GetTexture2DList(string key, List<Texture2D> defaultVal) { return defaultVal; } public static List<List<Texture2D>> GetTexture2DTwoDList(string key, List<List<Texture2D>> defaultVal) { return defaultVal; } public static Material GetMaterial(string key, Material defaultVal) { return defaultVal; } public static List<Material> GetMaterialList(string key, List<Material> defaultVal) { return defaultVal; } public static List<List<Material>> GetMaterialTwoDList(string key, List<List<Material>> defaultVal) { return defaultVal; } public static AudioClip GetAudioClip(string key, AudioClip defaultVal) { return defaultVal; } public static List<AudioClip> GetAudioClipList(string key, List<AudioClip> defaultVal) { return defaultVal; } public static List<List<AudioClip>> GetAudioClipTwoDList(string key, List<List<AudioClip>> defaultVal) { return defaultVal; } #endregion #region Get Saved Data Methods (Custom Types) public static T GetCustom<T>(string key, T defaultVal) where T : IGDEData, new() { T retVal = defaultVal; try { string defaultKey = (defaultVal != null)?defaultVal.Key:string.Empty; string customKey = GDEDataManager.GetString(key, defaultKey); if (customKey != defaultKey) { // First load defaults for this custom item GDEDataManager.DataDictionary.TryGetCustom(customKey, out retVal); // Then load any overrides from playerprefs retVal.LoadFromSavedData(customKey); } } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<T> GetCustomList<T>(string key, List<T> defaultVal) where T : IGDEData, new() { List<T> retVal = defaultVal; try { if (PlayerPrefs.HasKey(key)) { retVal = new List<T>(); List<string> customDataKeys = GDEDataManager.GetStringList(key, null); if (customDataKeys != null) { foreach(string customDataKey in customDataKeys) { T temp; if (GDEDataManager.DataDictionary.TryGetCustom(customDataKey, out temp)) retVal.Add(temp); } } } } catch(Exception ex) { Debug.LogException(ex); } return retVal; } public static List<List<T>> GetCustomTwoDList<T>(string key, List<List<T>> defaultVal) where T : IGDEData, new() { List<List<T>> retVal = defaultVal; try { if (PlayerPrefs.HasKey(key)) { retVal = new List<List<T>>(); List<List<string>> customDataKeys = GDEDataManager.GetStringTwoDList(key, null); if (customDataKeys != null) { foreach(var subListKeys in customDataKeys) { List<T> subList = new List<T>(); foreach(var customDataKey in subListKeys) { T temp; if (GDEDataManager.DataDictionary.TryGetCustom(customDataKey, out temp)) subList.Add(temp); } retVal.Add(subList); } } } } catch(Exception ex) { Debug.LogException(ex); } return retVal; } #endregion #region Save Data Methods (Basic Types) public static void SetString(string key, string val) { try { PlayerPrefs.SetString(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetStringList(string key, List<string> val) { try { GDEPPX.SetStringList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetStringTwoDList(string key, List<List<string>> val) { try { GDEPPX.Set2DStringList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetInt(string key, int val) { try { PlayerPrefs.SetInt(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetIntList(string key, List<int> val) { try { GDEPPX.SetIntList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetIntTwoDList(string key, List<List<int>> val) { try { GDEPPX.Set2DIntList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetFloat(string key, float val) { try { PlayerPrefs.SetFloat(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetFloatList(string key, List<float> val) { try { GDEPPX.SetFloatList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetFloatTwoDList(string key, List<List<float>> val) { try { GDEPPX.Set2DFloatList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetBool(string key, bool val) { try { GDEPPX.SetBool(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetBoolList(string key, List<bool> val) { try { GDEPPX.SetBoolList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetBoolTwoDList(string key, List<List<bool>> val) { try { GDEPPX.Set2DBoolList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetColor(string key, Color32 val) { try { GDEPPX.SetColor(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetColorList(string key, List<Color> val) { try { GDEPPX.SetColorList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetColorTwoDList(string key, List<List<Color>> val) { try { GDEPPX.Set2DColorList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetVector2(string key, Vector2 val) { try { GDEPPX.SetVector2(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetVector2List(string key, List<Vector2> val) { try { GDEPPX.SetVector2List(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetVector2TwoDList(string key, List<List<Vector2>> val) { try { GDEPPX.Set2DVector2List(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetVector3(string key, Vector3 val) { try { GDEPPX.SetVector3(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetVector3List(string key, List<Vector3> val) { try { GDEPPX.SetVector3List(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetVector3TwoDList(string key, List<List<Vector3>> val) { try { GDEPPX.Set2DVector3List(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetVector4(string key, Vector4 val) { try { GDEPPX.SetVector4(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetVector4List(string key, List<Vector4> val) { try { GDEPPX.SetVector4List(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetVector4TwoDList(string key, List<List<Vector4>> val) { try { GDEPPX.Set2DVector4List(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetGameObject(string key, GameObject val) { try { GDEPPX.SetGameObject(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetGameObjectList(string key, List<GameObject> val) { try { GDEPPX.SetGameObjectList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetGameObjectTwoDList(string key, List<List<GameObject>> val) { try { GDEPPX.Set2DGameObjectList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetTexture2D(string key, Texture2D val) { try { GDEPPX.SetTexture2D(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetTexture2DList(string key, List<Texture2D> val) { try { GDEPPX.SetTexture2DList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetTexture2DTwoDList(string key, List<List<Texture2D>> val) { try { GDEPPX.Set2DTexture2DList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetMaterial(string key, Material val) { try { GDEPPX.SetMaterial(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetMaterialList(string key, List<Material> val) { try { GDEPPX.SetMaterialList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetMaterialTwoDList(string key, List<List<Material>> val) { try { GDEPPX.Set2DMaterialList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetAudioClip(string key, AudioClip val) { try { GDEPPX.SetAudioClip(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetAudioClipList(string key, List<AudioClip> val) { try { GDEPPX.SetAudioClipList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } public static void SetAudioClipTwoDList(string key, List<List<AudioClip>> val) { try { GDEPPX.Set2DAudioClipList(key, val); } catch(Exception ex) { Debug.LogException(ex); } } #endregion #region Save Data Methods (Custom Types) public static void SetCustom<T>(string key, T val) where T : IGDEData { GDEDataManager.SetString(key, val.Key); } public static void SetCustomList<T>(string key, List<T> val) where T : IGDEData { List<string> customKeys = new List<string>(); val.ForEach(x => customKeys.Add(x.Key)); GDEDataManager.SetStringList(key, customKeys); } public static void SetCustomTwoDList<T>(string key, List<List<T>> val) where T : IGDEData { List<List<string>> customKeys = new List<List<string>>(); foreach(List<T> subList in val) { List<string> subListKeys = new List<string>(); subList.ForEach(x => subListKeys.Add(x.Key)); customKeys.Add(subListKeys); } GDEDataManager.SetStringTwoDList(key, customKeys); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType { public partial class MoveTypeTests : CSharpMoveTypeTestsBase { [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_OnMatchingFileName() { var code = @"[||]class test1 { }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_Nested_OnMatchingFileName_Simple() { var code = @"class outer { [||]class test1 { } }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMatchingFileName_CaseSensitive() { var code = @"[||]class Test1 { }"; await TestActionCountAsync(code, count: 2); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans1() { var code = @"[|clas|]s Class1 { } class Class2 { }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans2() { var code = @"[||]class Class1 { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14008, "https://github.com/dotnet/roslyn/issues/14008")] public async Task TestMoveToNewFileWithFolders() { var code = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document Folders=""A\B""> [||]class Class1 { } class Class2 { } </Document> </Project> </Workspace>"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, destinationDocumentContainers: ImmutableArray.Create("A", "B")); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans3() { var code = @"[|class Class1|] { } class Class2 { }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans4() { var code = @"class Class1[||] { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithNoContainerNamespace() { var code = @"[||]class Class1 { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithUsingsAndNoContainerNamespace() { var code = @"// Banner Text using System; [||]class Class1 { } class Class2 { }"; var codeAfterMove = @"// Banner Text using System; class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithMembers() { var code = @"// Banner Text using System; [||]class Class1 { void Print(int x) { Console.WriteLine(x); } } class Class2 { }"; var codeAfterMove = @"// Banner Text class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @" using System; class Class1 { void Print(int x) { Console.WriteLine(x); } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithMembers2() { var code = @"// Banner Text using System; [||]class Class1 { void Print(int x) { Console.WriteLine(x); } } class Class2 { void Print(int x) { Console.WriteLine(x); } }"; var codeAfterMove = @"// Banner Text using System; class Class2 { void Print(int x) { Console.WriteLine(x); } }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @" using System; class Class1 { void Print(int x) { Console.WriteLine(x); } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAnInterface() { var code = @"[||]interface IMoveType { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "IMoveType.cs"; var destinationDocumentText = @"interface IMoveType { }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAStruct() { var code = @"[||]struct MyStruct { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "MyStruct.cs"; var destinationDocumentText = @"struct MyStruct { }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAnEnum() { var code = @"[||]enum MyEnum { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "MyEnum.cs"; var destinationDocumentText = @"enum MyEnum { }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithContainerNamespace() { var code = @"namespace N1 { [||]class Class1 { } class Class2 { } }"; var codeAfterMove = @"namespace N1 { class Class2 { } }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"namespace N1 { class Class1 { } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_Simple() { var code = @"namespace N1 { class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypePreserveModifiers() { var code = @"namespace N1 { abstract class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { abstract partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { abstract partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14004, "https://github.com/dotnet/roslyn/issues/14004")] public async Task MoveNestedTypeToNewFile_Attributes1() { var code = @"namespace N1 { [Outer] class Class1 { [Inner] [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { [Outer] partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { [Inner] class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14484, "https://github.com/dotnet/roslyn/issues/14484")] public async Task MoveNestedTypeToNewFile_Comments1() { var code = @"namespace N1 { /// Outer doc comment. class Class1 { /// Inner doc comment [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { /// Outer doc comment. partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { /// Inner doc comment class Class2 { } } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, ignoreTrivia: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_Simple_DottedName() { var code = @"namespace N1 { class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { } }"; var expectedDocumentName = "Class1.Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText, index: 1); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_ParentHasOtherMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { } public void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_HasOtherTopLevelMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { } public void Method1() { } } internal class Class3 { private void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } internal class Class3 { private void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_HasMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { private string _field1; public void InnerMethod() { } } public void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { private string _field1; public void InnerMethod() { } } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(13969, "https://github.com/dotnet/roslyn/issues/13969")] public async Task MoveTypeInFileWithComplexHierarchy() { var code = @"namespace OuterN1.N1 { namespace InnerN2.N2 { class OuterClass1 { class InnerClass2 { } } } namespace InnerN3.N3 { class OuterClass2 { [||]class InnerClass2 { class InnerClass3 { } } class InnerClass4 { } } class OuterClass3 { } } } namespace OuterN2.N2 { namespace InnerN3.N3 { class OuterClass5 { class InnerClass6 { } } } } "; var codeAfterMove = @"namespace OuterN1.N1 { namespace InnerN2.N2 { class OuterClass1 { class InnerClass2 { } } } namespace InnerN3.N3 { partial class OuterClass2 { class InnerClass4 { } } class OuterClass3 { } } } namespace OuterN2.N2 { namespace InnerN3.N3 { class OuterClass5 { class InnerClass6 { } } } }"; var expectedDocumentName = "InnerClass2.cs"; var destinationDocumentText = @" namespace OuterN1.N1 { namespace InnerN3.N3 { partial class OuterClass2 { class InnerClass2 { class InnerClass3 { } } } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeUsings1() { var code = @" // Only used by inner type. using System; // Unused by both types. using System.Collections; class Outer { [||]class Inner { DateTime d; } }"; var codeAfterMove = @" // Unused by both types. using System.Collections; partial class Outer { }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" // Only used by inner type. using System; partial class Outer { class Inner { DateTime d; } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(16283, "https://github.com/dotnet/roslyn/issues/16283")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingTrivia1() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, ignoreTrivia: false); } [WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestInsertFinalNewLine() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, ignoreTrivia: false, onAfterWorkspaceCreated: w => { w.Options = w.Options.WithChangedOption(FormattingOptions.InsertFinalNewLine, true); }); } [WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestInsertFinalNewLine2() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, ignoreTrivia: false, onAfterWorkspaceCreated: w => { w.Options = w.Options.WithChangedOption(FormattingOptions.InsertFinalNewLine, false); }); } [WorkItem(16282, "https://github.com/dotnet/roslyn/issues/16282")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeRemoveOuterInheritanceTypes() { var code = @" class Outer : IComparable { [||]class Inner : IWhatever { DateTime d; } }"; var codeAfterMove = @" partial class Outer : IComparable { }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" partial class Outer { class Inner : IWhatever { DateTime d; } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithDirectives1() { var code = @"using System; namespace N { class Program { static void Main() { } } } #if true public class [||]Inner { } #endif"; var codeAfterMove = @"using System; namespace N { class Program { static void Main() { } } } #if true #endif"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @"#if true public class Inner { } #endif"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, ignoreTrivia: false); } [WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithDirectives2() { var code = @"using System; namespace N { class Program { static void Main() { } #if true public class [||]Inner { } #endif } }"; var codeAfterMove = @"using System; namespace N { partial class Program { static void Main() { } #if true #endif } }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @"namespace N { partial class Program { #if true public class Inner { } #endif } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, ignoreTrivia: false); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf.WellKnownTypes { /// <summary>Holder for reflection information generated from google/protobuf/any.proto</summary> public static partial class AnyReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/any.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AnyReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYi", "JgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQm8KE2Nv", "bS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAFaJWdpdGh1Yi5jb20vZ29s", "YW5nL3Byb3RvYnVmL3B0eXBlcy9hbnmiAgNHUEKqAh5Hb29nbGUuUHJvdG9i", "dWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Any), global::Google.Protobuf.WellKnownTypes.Any.Parser, new[]{ "TypeUrl", "Value" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// `Any` contains an arbitrary serialized protocol buffer message along with a /// URL that describes the type of the serialized message. /// /// Protobuf library provides support to pack/unpack Any values in the form /// of utility functions or additional generated methods of the Any type. /// /// Example 1: Pack and unpack a message in C++. /// /// Foo foo = ...; /// Any any; /// any.PackFrom(foo); /// ... /// if (any.UnpackTo(&amp;foo)) { /// ... /// } /// /// Example 2: Pack and unpack a message in Java. /// /// Foo foo = ...; /// Any any = Any.pack(foo); /// ... /// if (any.is(Foo.class)) { /// foo = any.unpack(Foo.class); /// } /// /// Example 3: Pack and unpack a message in Python. /// /// foo = Foo(...) /// any = Any() /// any.Pack(foo) /// ... /// if any.Is(Foo.DESCRIPTOR): /// any.Unpack(foo) /// ... /// /// The pack methods provided by protobuf library will by default use /// 'type.googleapis.com/full.type.name' as the type URL and the unpack /// methods only use the fully qualified type name after the last '/' /// in the type URL, for example "foo.bar.com/x/y.z" will yield type /// name "y.z". /// /// JSON /// ==== /// The JSON representation of an `Any` value uses the regular /// representation of the deserialized, embedded message, with an /// additional field `@type` which contains the type URL. Example: /// /// package google.profile; /// message Person { /// string first_name = 1; /// string last_name = 2; /// } /// /// { /// "@type": "type.googleapis.com/google.profile.Person", /// "firstName": &lt;string>, /// "lastName": &lt;string> /// } /// /// If the embedded message type is well-known and has a custom JSON /// representation, that representation will be embedded adding a field /// `value` which holds the custom JSON in addition to the `@type` /// field. Example (for message [google.protobuf.Duration][]): /// /// { /// "@type": "type.googleapis.com/google.protobuf.Duration", /// "value": "1.212s" /// } /// </summary> public sealed partial class Any : pb::IMessage<Any> { private static readonly pb::MessageParser<Any> _parser = new pb::MessageParser<Any>(() => new Any()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Any> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Any() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Any(Any other) : this() { typeUrl_ = other.typeUrl_; value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Any Clone() { return new Any(this); } /// <summary>Field number for the "type_url" field.</summary> public const int TypeUrlFieldNumber = 1; private string typeUrl_ = ""; /// <summary> /// A URL/resource name whose content describes the type of the /// serialized protocol buffer message. /// /// For URLs which use the scheme `http`, `https`, or no scheme, the /// following restrictions and interpretations apply: /// /// * If no scheme is provided, `https` is assumed. /// * The last segment of the URL's path must represent the fully /// qualified name of the type (as in `path/google.protobuf.Duration`). /// The name should be in a canonical form (e.g., leading "." is /// not accepted). /// * An HTTP GET on the URL must yield a [google.protobuf.Type][] /// value in binary format, or produce an error. /// * Applications are allowed to cache lookup results based on the /// URL, or have them precompiled into a binary to avoid any /// lookup. Therefore, binary compatibility needs to be preserved /// on changes to types. (Use versioned type names to manage /// breaking changes.) /// /// Schemes other than `http`, `https` (or the empty scheme) might be /// used with implementation specific semantics. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string TypeUrl { get { return typeUrl_; } set { typeUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 2; private pb::ByteString value_ = pb::ByteString.Empty; /// <summary> /// Must be a valid serialized protocol buffer of the above specified type. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString Value { get { return value_; } set { value_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Any); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Any other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (TypeUrl != other.TypeUrl) return false; if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (TypeUrl.Length != 0) hash ^= TypeUrl.GetHashCode(); if (Value.Length != 0) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (TypeUrl.Length != 0) { output.WriteRawTag(10); output.WriteString(TypeUrl); } if (Value.Length != 0) { output.WriteRawTag(18); output.WriteBytes(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (TypeUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TypeUrl); } if (Value.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Any other) { if (other == null) { return; } if (other.TypeUrl.Length != 0) { TypeUrl = other.TypeUrl; } if (other.Value.Length != 0) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { TypeUrl = input.ReadString(); break; } case 18: { Value = input.ReadBytes(); break; } } } } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Runtime; using System.Security.Authentication.ExtendedProtection; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Security.Tokens; using System.Globalization; namespace System.ServiceModel.Security { /* * See * http://xws/gxa/main/specs/security/security_profiles/SecurityProfiles.doc * for details on security protocols * Concrete implementations are required to me thread safe after * Open() is called; * instances of concrete protocol factories are scoped to a * channel/listener factory; * Each channel/listener factory must have a * SecurityProtocolFactory set on it before open/first use; the * factory instance cannot be changed once the factory is opened * or listening; * security protocol instances are scoped to a channel and will be * created by the Create calls on protocol factories; * security protocol instances are required to be thread-safe. * for typical subclasses, factory wide state and immutable * settings are expected to be on the ProtocolFactory itself while * channel-wide state is maintained internally in each security * protocol instance; * the security protocol instance set on a channel cannot be * changed; however, the protocol instance may change internal * state; this covers RM's SCT renego case; by keeping state * change internal to protocol instances, we get better * coordination with concurrent message security on channels; * the primary pivot in creating a security protocol instance is * initiator (client) vs. responder (server), NOT sender vs * receiver * Create calls for input and reply channels will contain the * listener-wide state (if any) created by the corresponding call * on the factory; */ // Whether we need to add support for targetting different SOAP roles is tracked by 19144 internal abstract class SecurityProtocolFactory : ISecurityCommunicationObject { internal const bool defaultAddTimestamp = true; internal const bool defaultDeriveKeys = true; internal const bool defaultDetectReplays = true; internal const string defaultMaxClockSkewString = "00:05:00"; internal const string defaultReplayWindowString = "00:05:00"; internal static readonly TimeSpan defaultMaxClockSkew = TimeSpan.Parse(defaultMaxClockSkewString, CultureInfo.InvariantCulture); internal static readonly TimeSpan defaultReplayWindow = TimeSpan.Parse(defaultReplayWindowString, CultureInfo.InvariantCulture); internal const int defaultMaxCachedNonces = 900000; internal const string defaultTimestampValidityDurationString = "00:05:00"; internal static readonly TimeSpan defaultTimestampValidityDuration = TimeSpan.Parse(defaultTimestampValidityDurationString, CultureInfo.InvariantCulture); internal const SecurityHeaderLayout defaultSecurityHeaderLayout = SecurityHeaderLayout.Strict; private static ReadOnlyCollection<SupportingTokenAuthenticatorSpecification> s_emptyTokenAuthenticators; private bool _actAsInitiator; private bool _isDuplexReply; private bool _addTimestamp = defaultAddTimestamp; private bool _detectReplays = defaultDetectReplays; private bool _expectIncomingMessages; private bool _expectOutgoingMessages; private SecurityAlgorithmSuite _incomingAlgorithmSuite = SecurityAlgorithmSuite.Default; // per receiver protocol factory lists private ICollection<SupportingTokenAuthenticatorSpecification> _channelSupportingTokenAuthenticatorSpecification; private Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>> _scopedSupportingTokenAuthenticatorSpecification; private Dictionary<string, MergedSupportingTokenAuthenticatorSpecification> _mergedSupportingTokenAuthenticatorsMap; private int _maxCachedNonces = defaultMaxCachedNonces; private TimeSpan _maxClockSkew = defaultMaxClockSkew; private NonceCache _nonceCache = null; private SecurityAlgorithmSuite _outgoingAlgorithmSuite = SecurityAlgorithmSuite.Default; private TimeSpan _replayWindow = defaultReplayWindow; private SecurityStandardsManager _standardsManager = SecurityStandardsManager.DefaultInstance; private SecurityTokenManager _securityTokenManager; private SecurityBindingElement _securityBindingElement; private string _requestReplyErrorPropertyName; private NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken> _derivedKeyTokenAuthenticator; private TimeSpan _timestampValidityDuration = defaultTimestampValidityDuration; private AuditLogLocation _auditLogLocation; private bool _suppressAuditFailure; private SecurityHeaderLayout _securityHeaderLayout; private AuditLevel _serviceAuthorizationAuditLevel; private AuditLevel _messageAuthenticationAuditLevel; private bool _expectKeyDerivation; private bool _expectChannelBasicTokens; private bool _expectChannelSignedTokens; private bool _expectChannelEndorsingTokens; private bool _expectSupportingTokens; private Uri _listenUri; private MessageSecurityVersion _messageSecurityVersion; private WrapperSecurityCommunicationObject _communicationObject; private Uri _privacyNoticeUri; private int _privacyNoticeVersion; private ExtendedProtectionPolicy _extendedProtectionPolicy; private BufferManager _streamBufferManager = null; protected SecurityProtocolFactory() { _channelSupportingTokenAuthenticatorSpecification = new Collection<SupportingTokenAuthenticatorSpecification>(); _scopedSupportingTokenAuthenticatorSpecification = new Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>>(); _communicationObject = new WrapperSecurityCommunicationObject(this); } internal SecurityProtocolFactory(SecurityProtocolFactory factory) : this() { if (factory == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("factory"); } _actAsInitiator = factory._actAsInitiator; _addTimestamp = factory._addTimestamp; _detectReplays = factory._detectReplays; _incomingAlgorithmSuite = factory._incomingAlgorithmSuite; _maxCachedNonces = factory._maxCachedNonces; _maxClockSkew = factory._maxClockSkew; _outgoingAlgorithmSuite = factory._outgoingAlgorithmSuite; _replayWindow = factory._replayWindow; _channelSupportingTokenAuthenticatorSpecification = new Collection<SupportingTokenAuthenticatorSpecification>(new List<SupportingTokenAuthenticatorSpecification>(factory._channelSupportingTokenAuthenticatorSpecification)); _scopedSupportingTokenAuthenticatorSpecification = new Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>>(factory._scopedSupportingTokenAuthenticatorSpecification); _standardsManager = factory._standardsManager; _timestampValidityDuration = factory._timestampValidityDuration; _auditLogLocation = factory._auditLogLocation; _suppressAuditFailure = factory._suppressAuditFailure; _serviceAuthorizationAuditLevel = factory._serviceAuthorizationAuditLevel; _messageAuthenticationAuditLevel = factory._messageAuthenticationAuditLevel; if (factory._securityBindingElement != null) { _securityBindingElement = (SecurityBindingElement)factory._securityBindingElement.Clone(); } _securityTokenManager = factory._securityTokenManager; _privacyNoticeUri = factory._privacyNoticeUri; _privacyNoticeVersion = factory._privacyNoticeVersion; _extendedProtectionPolicy = factory._extendedProtectionPolicy; _nonceCache = factory._nonceCache; } protected WrapperSecurityCommunicationObject CommunicationObject { get { return _communicationObject; } } // The ActAsInitiator value is set automatically on Open and // remains unchanged thereafter. ActAsInitiator is true for // the initiator of the message exchange, such as the sender // of a datagram, sender of a request and sender of either leg // of a duplex exchange. public bool ActAsInitiator { get { return _actAsInitiator; } } public BufferManager StreamBufferManager { get { if (_streamBufferManager == null) { _streamBufferManager = BufferManager.CreateBufferManager(0, int.MaxValue); } return _streamBufferManager; } set { _streamBufferManager = value; } } internal bool IsDuplexReply { get { return _isDuplexReply; } set { _isDuplexReply = value; } } public bool AddTimestamp { get { return _addTimestamp; } set { ThrowIfImmutable(); _addTimestamp = value; } } public AuditLogLocation AuditLogLocation { get { return _auditLogLocation; } set { ThrowIfImmutable(); AuditLogLocationHelper.Validate(value); _auditLogLocation = value; } } public bool SuppressAuditFailure { get { return _suppressAuditFailure; } set { ThrowIfImmutable(); _suppressAuditFailure = value; } } public AuditLevel ServiceAuthorizationAuditLevel { get { return _serviceAuthorizationAuditLevel; } set { ThrowIfImmutable(); AuditLevelHelper.Validate(value); _serviceAuthorizationAuditLevel = value; } } public AuditLevel MessageAuthenticationAuditLevel { get { return _messageAuthenticationAuditLevel; } set { ThrowIfImmutable(); AuditLevelHelper.Validate(value); _messageAuthenticationAuditLevel = value; } } public bool DetectReplays { get { return _detectReplays; } set { ThrowIfImmutable(); _detectReplays = value; } } public Uri PrivacyNoticeUri { get { return _privacyNoticeUri; } set { ThrowIfImmutable(); _privacyNoticeUri = value; } } public int PrivacyNoticeVersion { get { return _privacyNoticeVersion; } set { ThrowIfImmutable(); _privacyNoticeVersion = value; } } private static ReadOnlyCollection<SupportingTokenAuthenticatorSpecification> EmptyTokenAuthenticators { get { if (s_emptyTokenAuthenticators == null) { s_emptyTokenAuthenticators = new ReadOnlyCollection<SupportingTokenAuthenticatorSpecification>(new SupportingTokenAuthenticatorSpecification[0]); } return s_emptyTokenAuthenticators; } } internal NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken> DerivedKeyTokenAuthenticator { get { return _derivedKeyTokenAuthenticator; } } internal bool ExpectIncomingMessages { get { return _expectIncomingMessages; } } internal bool ExpectOutgoingMessages { get { return _expectOutgoingMessages; } } internal bool ExpectKeyDerivation { get { return _expectKeyDerivation; } set { _expectKeyDerivation = value; } } internal bool ExpectSupportingTokens { get { return _expectSupportingTokens; } set { _expectSupportingTokens = value; } } public SecurityAlgorithmSuite IncomingAlgorithmSuite { get { return _incomingAlgorithmSuite; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _incomingAlgorithmSuite = value; } } protected bool IsReadOnly { get { return this.CommunicationObject.State != CommunicationState.Created; } } public int MaxCachedNonces { get { return _maxCachedNonces; } set { ThrowIfImmutable(); if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } _maxCachedNonces = value; } } public TimeSpan MaxClockSkew { get { return _maxClockSkew; } set { ThrowIfImmutable(); if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } _maxClockSkew = value; } } public NonceCache NonceCache { get { return _nonceCache; } set { ThrowIfImmutable(); _nonceCache = value; } } public SecurityAlgorithmSuite OutgoingAlgorithmSuite { get { return _outgoingAlgorithmSuite; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _outgoingAlgorithmSuite = value; } } public TimeSpan ReplayWindow { get { return _replayWindow; } set { ThrowIfImmutable(); if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.TimeSpanMustbeGreaterThanTimeSpanZero)); } _replayWindow = value; } } public ICollection<SupportingTokenAuthenticatorSpecification> ChannelSupportingTokenAuthenticatorSpecification { get { return _channelSupportingTokenAuthenticatorSpecification; } } public Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>> ScopedSupportingTokenAuthenticatorSpecification { get { return _scopedSupportingTokenAuthenticatorSpecification; } } public SecurityBindingElement SecurityBindingElement { get { return _securityBindingElement; } set { ThrowIfImmutable(); if (value != null) { value = (SecurityBindingElement)value.Clone(); } _securityBindingElement = value; } } public SecurityTokenManager SecurityTokenManager { get { return _securityTokenManager; } set { ThrowIfImmutable(); _securityTokenManager = value; } } public virtual bool SupportsDuplex { get { return false; } } public SecurityHeaderLayout SecurityHeaderLayout { get { return _securityHeaderLayout; } set { ThrowIfImmutable(); _securityHeaderLayout = value; } } public virtual bool SupportsReplayDetection { get { return true; } } public virtual bool SupportsRequestReply { get { return true; } } public SecurityStandardsManager StandardsManager { get { return _standardsManager; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _standardsManager = value; } } public TimeSpan TimestampValidityDuration { get { return _timestampValidityDuration; } set { ThrowIfImmutable(); if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.TimeSpanMustbeGreaterThanTimeSpanZero)); } _timestampValidityDuration = value; } } public Uri ListenUri { get { return _listenUri; } set { ThrowIfImmutable(); _listenUri = value; } } internal MessageSecurityVersion MessageSecurityVersion { get { return _messageSecurityVersion; } } // ISecurityCommunicationObject members public TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } public TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } public IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(this.OnClose, timeout, callback, state); } public IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(this.OnOpen, timeout, callback, state); } public void OnClosed() { } public void OnClosing() { } public void OnEndClose(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnEndOpen(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnFaulted() { } public void OnOpened() { } public void OnOpening() { } public virtual void OnAbort() { if (!_actAsInitiator) { foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.AbortTokenAuthenticatorIfRequired(spec.TokenAuthenticator); } foreach (string action in _scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> supportingAuthenticators = _scopedSupportingTokenAuthenticatorSpecification[action]; foreach (SupportingTokenAuthenticatorSpecification spec in supportingAuthenticators) { SecurityUtils.AbortTokenAuthenticatorIfRequired(spec.TokenAuthenticator); } } } } public virtual void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (!_actAsInitiator) { foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.CloseTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); } foreach (string action in _scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> supportingAuthenticators = _scopedSupportingTokenAuthenticatorSpecification[action]; foreach (SupportingTokenAuthenticatorSpecification spec in supportingAuthenticators) { SecurityUtils.CloseTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); } } } } public virtual object CreateListenerSecurityState() { return null; } public SecurityProtocol CreateSecurityProtocol(EndpointAddress target, Uri via, object listenerSecurityState, bool isReturnLegSecurityRequired, TimeSpan timeout) { ThrowIfNotOpen(); SecurityProtocol securityProtocol = OnCreateSecurityProtocol(target, via, listenerSecurityState, timeout); if (securityProtocol == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.ProtocolFactoryCouldNotCreateProtocol)); } return securityProtocol; } public virtual EndpointIdentity GetIdentityOfSelf() { return null; } public virtual T GetProperty<T>() { if (typeof(T) == typeof(Collection<ISecurityContextSecurityTokenCache>)) { ThrowIfNotOpen(); Collection<ISecurityContextSecurityTokenCache> result = new Collection<ISecurityContextSecurityTokenCache>(); if (_channelSupportingTokenAuthenticatorSpecification != null) { foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { if (spec.TokenAuthenticator is ISecurityContextSecurityTokenCacheProvider) { result.Add(((ISecurityContextSecurityTokenCacheProvider)spec.TokenAuthenticator).TokenCache); } } } return (T)(object)(result); } else { return default(T); } } protected abstract SecurityProtocol OnCreateSecurityProtocol(EndpointAddress target, Uri via, object listenerSecurityState, TimeSpan timeout); private void VerifyTypeUniqueness(ICollection<SupportingTokenAuthenticatorSpecification> supportingTokenAuthenticators) { // its ok to go brute force here since we are dealing with a small number of authenticators foreach (SupportingTokenAuthenticatorSpecification spec in supportingTokenAuthenticators) { Type authenticatorType = spec.TokenAuthenticator.GetType(); int numSkipped = 0; foreach (SupportingTokenAuthenticatorSpecification spec2 in supportingTokenAuthenticators) { Type spec2AuthenticatorType = spec2.TokenAuthenticator.GetType(); if (object.ReferenceEquals(spec, spec2)) { if (numSkipped > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MultipleSupportingAuthenticatorsOfSameType, spec.TokenParameters.GetType()))); } ++numSkipped; continue; } else if (authenticatorType.IsAssignableFrom(spec2AuthenticatorType) || spec2AuthenticatorType.IsAssignableFrom(authenticatorType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MultipleSupportingAuthenticatorsOfSameType, spec.TokenParameters.GetType()))); } } } } internal IList<SupportingTokenAuthenticatorSpecification> GetSupportingTokenAuthenticators(string action, out bool expectSignedTokens, out bool expectBasicTokens, out bool expectEndorsingTokens) { if (_mergedSupportingTokenAuthenticatorsMap != null && _mergedSupportingTokenAuthenticatorsMap.Count > 0) { if (action != null && _mergedSupportingTokenAuthenticatorsMap.ContainsKey(action)) { MergedSupportingTokenAuthenticatorSpecification mergedSpec = _mergedSupportingTokenAuthenticatorsMap[action]; expectSignedTokens = mergedSpec.ExpectSignedTokens; expectBasicTokens = mergedSpec.ExpectBasicTokens; expectEndorsingTokens = mergedSpec.ExpectEndorsingTokens; return mergedSpec.SupportingTokenAuthenticators; } else if (_mergedSupportingTokenAuthenticatorsMap.ContainsKey(MessageHeaders.WildcardAction)) { MergedSupportingTokenAuthenticatorSpecification mergedSpec = _mergedSupportingTokenAuthenticatorsMap[MessageHeaders.WildcardAction]; expectSignedTokens = mergedSpec.ExpectSignedTokens; expectBasicTokens = mergedSpec.ExpectBasicTokens; expectEndorsingTokens = mergedSpec.ExpectEndorsingTokens; return mergedSpec.SupportingTokenAuthenticators; } } expectSignedTokens = _expectChannelSignedTokens; expectBasicTokens = _expectChannelBasicTokens; expectEndorsingTokens = _expectChannelEndorsingTokens; // in case the channelSupportingTokenAuthenticators is empty return null so that its Count does not get accessed. return (Object.ReferenceEquals(_channelSupportingTokenAuthenticatorSpecification, EmptyTokenAuthenticators)) ? null : (IList<SupportingTokenAuthenticatorSpecification>)_channelSupportingTokenAuthenticatorSpecification; } private void MergeSupportingTokenAuthenticators(TimeSpan timeout) { if (_scopedSupportingTokenAuthenticatorSpecification.Count == 0) { _mergedSupportingTokenAuthenticatorsMap = null; } else { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); _expectSupportingTokens = true; _mergedSupportingTokenAuthenticatorsMap = new Dictionary<string, MergedSupportingTokenAuthenticatorSpecification>(); foreach (string action in _scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> scopedAuthenticators = _scopedSupportingTokenAuthenticatorSpecification[action]; if (scopedAuthenticators == null || scopedAuthenticators.Count == 0) { continue; } Collection<SupportingTokenAuthenticatorSpecification> mergedAuthenticators = new Collection<SupportingTokenAuthenticatorSpecification>(); bool expectSignedTokens = _expectChannelSignedTokens; bool expectBasicTokens = _expectChannelBasicTokens; bool expectEndorsingTokens = _expectChannelEndorsingTokens; foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { mergedAuthenticators.Add(spec); } foreach (SupportingTokenAuthenticatorSpecification spec in scopedAuthenticators) { SecurityUtils.OpenTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); mergedAuthenticators.Add(spec); if (spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing) { if (spec.TokenParameters.RequireDerivedKeys && !spec.TokenParameters.HasAsymmetricKey) { _expectKeyDerivation = true; } } SecurityTokenAttachmentMode mode = spec.SecurityTokenAttachmentMode; if (mode == SecurityTokenAttachmentMode.SignedEncrypted || mode == SecurityTokenAttachmentMode.Signed || mode == SecurityTokenAttachmentMode.SignedEndorsing) { expectSignedTokens = true; if (mode == SecurityTokenAttachmentMode.SignedEncrypted) { expectBasicTokens = true; } } if (mode == SecurityTokenAttachmentMode.Endorsing || mode == SecurityTokenAttachmentMode.SignedEndorsing) { expectEndorsingTokens = true; } } VerifyTypeUniqueness(mergedAuthenticators); MergedSupportingTokenAuthenticatorSpecification mergedSpec = new MergedSupportingTokenAuthenticatorSpecification(); mergedSpec.SupportingTokenAuthenticators = mergedAuthenticators; mergedSpec.ExpectBasicTokens = expectBasicTokens; mergedSpec.ExpectEndorsingTokens = expectEndorsingTokens; mergedSpec.ExpectSignedTokens = expectSignedTokens; _mergedSupportingTokenAuthenticatorsMap.Add(action, mergedSpec); } } } protected RecipientServiceModelSecurityTokenRequirement CreateRecipientSecurityTokenRequirement() { RecipientServiceModelSecurityTokenRequirement requirement = new RecipientServiceModelSecurityTokenRequirement(); requirement.SecurityBindingElement = _securityBindingElement; requirement.SecurityAlgorithmSuite = this.IncomingAlgorithmSuite; requirement.ListenUri = _listenUri; requirement.MessageSecurityVersion = this.MessageSecurityVersion.SecurityTokenVersion; requirement.Properties[ServiceModelSecurityTokenRequirement.ExtendedProtectionPolicy] = _extendedProtectionPolicy; return requirement; } private RecipientServiceModelSecurityTokenRequirement CreateRecipientSecurityTokenRequirement(SecurityTokenParameters parameters, SecurityTokenAttachmentMode attachmentMode) { RecipientServiceModelSecurityTokenRequirement requirement = CreateRecipientSecurityTokenRequirement(); requirement.KeyUsage = SecurityKeyUsage.Signature; requirement.Properties[ServiceModelSecurityTokenRequirement.MessageDirectionProperty] = MessageDirection.Input; requirement.Properties[ServiceModelSecurityTokenRequirement.SupportingTokenAttachmentModeProperty] = attachmentMode; requirement.Properties[ServiceModelSecurityTokenRequirement.ExtendedProtectionPolicy] = _extendedProtectionPolicy; return requirement; } private void AddSupportingTokenAuthenticators(SupportingTokenParameters supportingTokenParameters, bool isOptional, IList<SupportingTokenAuthenticatorSpecification> authenticatorSpecList) { for (int i = 0; i < supportingTokenParameters.Endorsing.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.Endorsing[i], SecurityTokenAttachmentMode.Endorsing); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.Endorsing, supportingTokenParameters.Endorsing[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.SignedEndorsing.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.SignedEndorsing[i], SecurityTokenAttachmentMode.SignedEndorsing); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.SignedEndorsing, supportingTokenParameters.SignedEndorsing[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.SignedEncrypted.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.SignedEncrypted[i], SecurityTokenAttachmentMode.SignedEncrypted); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.SignedEncrypted, supportingTokenParameters.SignedEncrypted[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.Signed.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.Signed[i], SecurityTokenAttachmentMode.Signed); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.Signed, supportingTokenParameters.Signed[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } } public virtual void OnOpen(TimeSpan timeout) { if (this.SecurityBindingElement == null) { this.OnPropertySettingsError("SecurityBindingElement", true); } if (this.SecurityTokenManager == null) { this.OnPropertySettingsError("SecurityTokenManager", true); } _messageSecurityVersion = _standardsManager.MessageSecurityVersion; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); _expectOutgoingMessages = this.ActAsInitiator || this.SupportsRequestReply; _expectIncomingMessages = !this.ActAsInitiator || this.SupportsRequestReply; if (!_actAsInitiator) { AddSupportingTokenAuthenticators(_securityBindingElement.EndpointSupportingTokenParameters, false, (IList<SupportingTokenAuthenticatorSpecification>)_channelSupportingTokenAuthenticatorSpecification); // validate the token authenticator types and create a merged map if needed. if (!_channelSupportingTokenAuthenticatorSpecification.IsReadOnly) { if (_channelSupportingTokenAuthenticatorSpecification.Count == 0) { _channelSupportingTokenAuthenticatorSpecification = EmptyTokenAuthenticators; } else { _expectSupportingTokens = true; foreach (SupportingTokenAuthenticatorSpecification tokenAuthenticatorSpec in _channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.OpenTokenAuthenticatorIfRequired(tokenAuthenticatorSpec.TokenAuthenticator, timeoutHelper.RemainingTime()); if (tokenAuthenticatorSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || tokenAuthenticatorSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing) { if (tokenAuthenticatorSpec.TokenParameters.RequireDerivedKeys && !tokenAuthenticatorSpec.TokenParameters.HasAsymmetricKey) { _expectKeyDerivation = true; } } SecurityTokenAttachmentMode mode = tokenAuthenticatorSpec.SecurityTokenAttachmentMode; if (mode == SecurityTokenAttachmentMode.SignedEncrypted || mode == SecurityTokenAttachmentMode.Signed || mode == SecurityTokenAttachmentMode.SignedEndorsing) { _expectChannelSignedTokens = true; if (mode == SecurityTokenAttachmentMode.SignedEncrypted) { _expectChannelBasicTokens = true; } } if (mode == SecurityTokenAttachmentMode.Endorsing || mode == SecurityTokenAttachmentMode.SignedEndorsing) { _expectChannelEndorsingTokens = true; } } _channelSupportingTokenAuthenticatorSpecification = new ReadOnlyCollection<SupportingTokenAuthenticatorSpecification>((Collection<SupportingTokenAuthenticatorSpecification>)_channelSupportingTokenAuthenticatorSpecification); } } VerifyTypeUniqueness(_channelSupportingTokenAuthenticatorSpecification); MergeSupportingTokenAuthenticators(timeoutHelper.RemainingTime()); } if (this.DetectReplays) { if (!this.SupportsReplayDetection) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("DetectReplays", SR.Format(SR.SecurityProtocolCannotDoReplayDetection, this)); } if (this.MaxClockSkew == TimeSpan.MaxValue || this.ReplayWindow == TimeSpan.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.NoncesCachedInfinitely)); } // If DetectReplays is true and nonceCache is null then use the default InMemoryNonceCache. if (_nonceCache == null) { // The nonce needs to be cached for replayWindow + 2*clockSkew to eliminate replays _nonceCache = new InMemoryNonceCache(this.ReplayWindow + this.MaxClockSkew + this.MaxClockSkew, this.MaxCachedNonces); } } _derivedKeyTokenAuthenticator = new NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken>(); } public void Open(bool actAsInitiator, TimeSpan timeout) { _actAsInitiator = actAsInitiator; _communicationObject.Open(timeout); } public IAsyncResult BeginOpen(bool actAsInitiator, TimeSpan timeout, AsyncCallback callback, object state) { _actAsInitiator = actAsInitiator; return this.CommunicationObject.BeginOpen(timeout, callback, state); } public void EndOpen(IAsyncResult result) { this.CommunicationObject.EndOpen(result); } public void Close(bool aborted, TimeSpan timeout) { if (aborted) { this.CommunicationObject.Abort(); } else { this.CommunicationObject.Close(timeout); } } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return this.CommunicationObject.BeginClose(timeout, callback, state); } public void EndClose(IAsyncResult result) { this.CommunicationObject.EndClose(result); } internal void Open(string propertyName, bool requiredForForwardDirection, SecurityTokenAuthenticator authenticator, TimeSpan timeout) { if (authenticator != null) { SecurityUtils.OpenTokenAuthenticatorIfRequired(authenticator, timeout); } else { OnPropertySettingsError(propertyName, requiredForForwardDirection); } } internal void Open(string propertyName, bool requiredForForwardDirection, SecurityTokenProvider provider, TimeSpan timeout) { if (provider != null) { SecurityUtils.OpenTokenProviderIfRequired(provider, timeout); } else { OnPropertySettingsError(propertyName, requiredForForwardDirection); } } internal void OnPropertySettingsError(string propertyName, bool requiredForForwardDirection) { if (requiredForForwardDirection) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException( SR.Format(SR.PropertySettingErrorOnProtocolFactory, propertyName, this), propertyName)); } else if (_requestReplyErrorPropertyName == null) { _requestReplyErrorPropertyName = propertyName; } } private void ThrowIfReturnDirectionSecurityNotSupported() { if (_requestReplyErrorPropertyName != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException( SR.Format(SR.PropertySettingErrorOnProtocolFactory, _requestReplyErrorPropertyName, this), _requestReplyErrorPropertyName)); } } internal void ThrowIfImmutable() { _communicationObject.ThrowIfDisposedOrImmutable(); } private void ThrowIfNotOpen() { _communicationObject.ThrowIfNotOpened(); } } internal struct MergedSupportingTokenAuthenticatorSpecification { public Collection<SupportingTokenAuthenticatorSpecification> SupportingTokenAuthenticators; public bool ExpectSignedTokens; public bool ExpectEndorsingTokens; public bool ExpectBasicTokens; } }
using System; using System.Windows.Input; using Avalonia.Input; using Avalonia.Media.Imaging; using Avalonia.Utilities; namespace Avalonia.Controls { public class NativeMenuItem : NativeMenuItemBase, INativeMenuItemExporterEventsImplBridge { private string _header; private KeyGesture _gesture; private bool _isEnabled = true; private ICommand _command; private bool _isChecked = false; private NativeMenuItemToggleType _toggleType; private IBitmap _icon; private NativeMenu _menu; static NativeMenuItem() { MenuProperty.Changed.Subscribe(args => { var item = (NativeMenuItem)args.Sender; var value = args.NewValue.GetValueOrDefault(); if (value.Parent != null && value.Parent != item) throw new InvalidOperationException("NativeMenu already has a parent"); value.Parent = item; }); } class CanExecuteChangedSubscriber : IWeakSubscriber<EventArgs> { private readonly NativeMenuItem _parent; public CanExecuteChangedSubscriber(NativeMenuItem parent) { _parent = parent; } public void OnEvent(object sender, EventArgs e) { _parent.CanExecuteChanged(); } } private readonly CanExecuteChangedSubscriber _canExecuteChangedSubscriber; public NativeMenuItem() { _canExecuteChangedSubscriber = new CanExecuteChangedSubscriber(this); } public NativeMenuItem(string header) : this() { Header = header; } public static readonly DirectProperty<NativeMenuItem, NativeMenu> MenuProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, NativeMenu>(nameof(Menu), o => o.Menu, (o, v) => o.Menu = v); public NativeMenu Menu { get => _menu; set { if (value.Parent != null && value.Parent != this) throw new InvalidOperationException("NativeMenu already has a parent"); SetAndRaise(MenuProperty, ref _menu, value); } } public static readonly DirectProperty<NativeMenuItem, IBitmap> IconProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, IBitmap>(nameof(Icon), o => o.Icon, (o, v) => o.Icon = v); public IBitmap Icon { get => _icon; set => SetAndRaise(IconProperty, ref _icon, value); } public static readonly DirectProperty<NativeMenuItem, string> HeaderProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, string>(nameof(Header), o => o.Header, (o, v) => o.Header = v); public string Header { get => _header; set => SetAndRaise(HeaderProperty, ref _header, value); } public static readonly DirectProperty<NativeMenuItem, KeyGesture> GestureProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, KeyGesture>(nameof(Gesture), o => o.Gesture, (o, v) => o.Gesture = v); public KeyGesture Gesture { get => _gesture; set => SetAndRaise(GestureProperty, ref _gesture, value); } public static readonly DirectProperty<NativeMenuItem, bool> IsCheckedProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, bool>( nameof(IsChecked), o => o.IsChecked, (o, v) => o.IsChecked = v); public bool IsChecked { get => _isChecked; set => SetAndRaise(IsCheckedProperty, ref _isChecked, value); } public static readonly DirectProperty<NativeMenuItem, NativeMenuItemToggleType> ToggleTypeProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, NativeMenuItemToggleType>( nameof(ToggleType), o => o.ToggleType, (o, v) => o.ToggleType = v); public NativeMenuItemToggleType ToggleType { get => _toggleType; set => SetAndRaise(ToggleTypeProperty, ref _toggleType, value); } public static readonly DirectProperty<NativeMenuItem, ICommand> CommandProperty = Button.CommandProperty.AddOwner<NativeMenuItem>( menuItem => menuItem.Command, (menuItem, command) => menuItem.Command = command, enableDataValidation: true); /// <summary> /// Defines the <see cref="CommandParameter"/> property. /// </summary> public static readonly StyledProperty<object> CommandParameterProperty = Button.CommandParameterProperty.AddOwner<MenuItem>(); public static readonly DirectProperty<NativeMenuItem, bool> IsEnabledProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, bool>(nameof(IsEnabled), o => o.IsEnabled, (o, v) => o.IsEnabled = v, true); public bool IsEnabled { get => _isEnabled; set => SetAndRaise(IsEnabledProperty, ref _isEnabled, value); } void CanExecuteChanged() { IsEnabled = _command?.CanExecute(null) ?? true; } public bool HasClickHandlers => Clicked != null; public ICommand Command { get => _command; set { if (_command != null) WeakSubscriptionManager.Unsubscribe(_command, nameof(ICommand.CanExecuteChanged), _canExecuteChangedSubscriber); SetAndRaise(CommandProperty, ref _command, value); if (_command != null) WeakSubscriptionManager.Subscribe(_command, nameof(ICommand.CanExecuteChanged), _canExecuteChangedSubscriber); CanExecuteChanged(); } } /// <summary> /// Gets or sets the parameter to pass to the <see cref="Command"/> property of a /// <see cref="NativeMenuItem"/>. /// </summary> public object CommandParameter { get { return GetValue(CommandParameterProperty); } set { SetValue(CommandParameterProperty, value); } } public event EventHandler Clicked; void INativeMenuItemExporterEventsImplBridge.RaiseClicked() { Clicked?.Invoke(this, new EventArgs()); if (Command?.CanExecute(CommandParameter) == true) { Command.Execute(CommandParameter); } } } public enum NativeMenuItemToggleType { None, CheckBox, Radio } }
/* * 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 Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.Framework; using OpenSim.Region.CoreModules.Framework.EntityTransfer; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; using OpenSim.Region.CoreModules.World.Permissions; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; using System.Collections.Generic; using System.Threading; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Teleport tests in a standalone OpenSim /// </summary> [TestFixture] public class ScenePresenceTeleportTests : OpenSimTestCase { [TestFixtureSetUp] public void FixtureInit() { // Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread. Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest; } [TestFixtureTearDown] public void TearDown() { // We must set this back afterwards, otherwise later tests will fail since they're expecting multiple // threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression // tests really shouldn't). Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod; } [Test] public void TestSameRegion() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); EntityTransferModule etm = new EntityTransferModule(); IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); // Not strictly necessary since FriendsModule assumes it is the default (!) config.Configs["Modules"].Set("EntityTransferModule", etm.Name); TestScene scene = new SceneHelpers().SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); SceneHelpers.SetupSceneModules(scene, config, etm); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x1)); sp.AbsolutePosition = new Vector3(30, 31, 32); scene.RequestTeleportLocation( sp.ControllingClient, scene.RegionInfo.RegionHandle, teleportPosition, teleportLookAt, (uint)TeleportFlags.ViaLocation); Assert.That(sp.AbsolutePosition, Is.EqualTo(teleportPosition)); Assert.That(scene.GetRootAgentCount(), Is.EqualTo(1)); Assert.That(scene.GetChildAgentCount(), Is.EqualTo(0)); // Lookat is sent to the client only - sp.Lookat does not yield the same thing (calculation from camera // position instead). // Assert.That(sp.Lookat, Is.EqualTo(teleportLookAt)); } [Test] public void TestSameSimulatorIsolatedRegionsV1() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID userId = TestHelpers.ParseTail(0x1); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); IConfig entityTransferConfig = config.AddConfig("EntityTransfer"); // In order to run a single threaded regression test we do not want the entity transfer module waiting // for a callback from the destination scene before removing its avatar data. entityTransferConfig.Set("wait_for_callback", false); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1002, 1000); SceneHelpers.SetupSceneModules(sceneA, config, etmA); SceneHelpers.SetupSceneModules(sceneB, config, etmB); SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); // FIXME: Hack - this is here temporarily to revert back to older entity transfer behaviour lscm.ServiceVersion = "SIMULATION/0.1"; Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); ScenePresence sp = SceneHelpers.AddScenePresence(sceneA, userId); sp.AbsolutePosition = new Vector3(30, 31, 32); List<TestClient> destinationTestClients = new List<TestClient>(); EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate( (TestClient)sp.ControllingClient, destinationTestClients); sceneA.RequestTeleportLocation( sp.ControllingClient, sceneB.RegionInfo.RegionHandle, teleportPosition, teleportLookAt, (uint)TeleportFlags.ViaLocation); // SetupInformClientOfNeighbour() will have handled the callback into the target scene to setup the child // agent. This call will now complete the movement of the user into the destination and upgrade the agent // from child to root. destinationTestClients[0].CompleteMovement(); Assert.That(sceneA.GetScenePresence(userId), Is.Null); ScenePresence sceneBSp = sceneB.GetScenePresence(userId); Assert.That(sceneBSp, Is.Not.Null); Assert.That(sceneBSp.Scene.RegionInfo.RegionName, Is.EqualTo(sceneB.RegionInfo.RegionName)); Assert.That(sceneBSp.AbsolutePosition, Is.EqualTo(teleportPosition)); Assert.That(sceneA.GetRootAgentCount(), Is.EqualTo(0)); Assert.That(sceneA.GetChildAgentCount(), Is.EqualTo(0)); Assert.That(sceneB.GetRootAgentCount(), Is.EqualTo(1)); Assert.That(sceneB.GetChildAgentCount(), Is.EqualTo(0)); // TODO: Add assertions to check correct circuit details in both scenes. // Lookat is sent to the client only - sp.Lookat does not yield the same thing (calculation from camera // position instead). // Assert.That(sp.Lookat, Is.EqualTo(teleportLookAt)); } [Test] public void TestSameSimulatorIsolatedRegionsV2() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID userId = TestHelpers.ParseTail(0x1); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1002, 1000); SceneHelpers.SetupSceneModules(sceneA, config, etmA); SceneHelpers.SetupSceneModules(sceneB, config, etmB); SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); ScenePresence sp = SceneHelpers.AddScenePresence(sceneA, userId); sp.AbsolutePosition = new Vector3(30, 31, 32); List<TestClient> destinationTestClients = new List<TestClient>(); EntityTransferHelpers.SetupSendRegionTeleportTriggersDestinationClientCreateAndCompleteMovement( (TestClient)sp.ControllingClient, destinationTestClients); sceneA.RequestTeleportLocation( sp.ControllingClient, sceneB.RegionInfo.RegionHandle, teleportPosition, teleportLookAt, (uint)TeleportFlags.ViaLocation); Assert.That(sceneA.GetScenePresence(userId), Is.Null); ScenePresence sceneBSp = sceneB.GetScenePresence(userId); Assert.That(sceneBSp, Is.Not.Null); Assert.That(sceneBSp.Scene.RegionInfo.RegionName, Is.EqualTo(sceneB.RegionInfo.RegionName)); Assert.That(sceneBSp.AbsolutePosition, Is.EqualTo(teleportPosition)); Assert.That(sceneA.GetRootAgentCount(), Is.EqualTo(0)); Assert.That(sceneA.GetChildAgentCount(), Is.EqualTo(0)); Assert.That(sceneB.GetRootAgentCount(), Is.EqualTo(1)); Assert.That(sceneB.GetChildAgentCount(), Is.EqualTo(0)); // TODO: Add assertions to check correct circuit details in both scenes. // Lookat is sent to the client only - sp.Lookat does not yield the same thing (calculation from camera // position instead). // Assert.That(sp.Lookat, Is.EqualTo(teleportLookAt)); } /// <summary> /// Test teleport procedures when the target simulator returns false when queried about access. /// </summary> [Test] public void TestSameSimulatorIsolatedRegions_DeniedOnQueryAccess() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID userId = TestHelpers.ParseTail(0x1); Vector3 preTeleportPosition = new Vector3(30, 31, 32); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.Configs["Modules"].Set("EntityTransferModule", etmA.Name); config.Configs["Modules"].Set("SimulationServices", lscm.Name); config.AddConfig("EntityTransfer"); // In order to run a single threaded regression test we do not want the entity transfer module waiting // for a callback from the destination scene before removing its avatar data. config.Configs["EntityTransfer"].Set("wait_for_callback", false); config.AddConfig("Startup"); config.Configs["Startup"].Set("serverside_object_permissions", true); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1002, 1000); SceneHelpers.SetupSceneModules(sceneA, config, etmA); // We need to set up the permisions module on scene B so that our later use of agent limit to deny // QueryAccess won't succeed anyway because administrators are always allowed in and the default // IsAdministrator if no permissions module is present is true. SceneHelpers.SetupSceneModules(sceneB, config, new object[] { new PermissionsModule(), etmB }); // Shared scene modules SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); ScenePresence sp = SceneHelpers.AddScenePresence(sceneA, userId); sp.AbsolutePosition = preTeleportPosition; // Make sceneB return false on query access sceneB.RegionInfo.RegionSettings.AgentLimit = 0; sceneA.RequestTeleportLocation( sp.ControllingClient, sceneB.RegionInfo.RegionHandle, teleportPosition, teleportLookAt, (uint)TeleportFlags.ViaLocation); // ((TestClient)sp.ControllingClient).CompleteTeleportClientSide(); Assert.That(sceneB.GetScenePresence(userId), Is.Null); ScenePresence sceneASp = sceneA.GetScenePresence(userId); Assert.That(sceneASp, Is.Not.Null); Assert.That(sceneASp.Scene.RegionInfo.RegionName, Is.EqualTo(sceneA.RegionInfo.RegionName)); Assert.That(sceneASp.AbsolutePosition, Is.EqualTo(preTeleportPosition)); Assert.That(sceneA.GetRootAgentCount(), Is.EqualTo(1)); Assert.That(sceneA.GetChildAgentCount(), Is.EqualTo(0)); Assert.That(sceneB.GetRootAgentCount(), Is.EqualTo(0)); Assert.That(sceneB.GetChildAgentCount(), Is.EqualTo(0)); // TODO: Add assertions to check correct circuit details in both scenes. // Lookat is sent to the client only - sp.Lookat does not yield the same thing (calculation from camera // position instead). // Assert.That(sp.Lookat, Is.EqualTo(teleportLookAt)); // TestHelpers.DisableLogging(); } /// <summary> /// Test teleport procedures when the target simulator create agent step is refused. /// </summary> [Test] public void TestSameSimulatorIsolatedRegions_DeniedOnCreateAgent() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID userId = TestHelpers.ParseTail(0x1); Vector3 preTeleportPosition = new Vector3(30, 31, 32); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.Configs["Modules"].Set("EntityTransferModule", etmA.Name); config.Configs["Modules"].Set("SimulationServices", lscm.Name); config.AddConfig("EntityTransfer"); // In order to run a single threaded regression test we do not want the entity transfer module waiting // for a callback from the destination scene before removing its avatar data. config.Configs["EntityTransfer"].Set("wait_for_callback", false); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1002, 1000); SceneHelpers.SetupSceneModules(sceneA, config, etmA); SceneHelpers.SetupSceneModules(sceneB, config, etmB); // Shared scene modules SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); ScenePresence sp = SceneHelpers.AddScenePresence(sceneA, userId); sp.AbsolutePosition = preTeleportPosition; // Make sceneB refuse CreateAgent sceneB.LoginsEnabled = false; sceneA.RequestTeleportLocation( sp.ControllingClient, sceneB.RegionInfo.RegionHandle, teleportPosition, teleportLookAt, (uint)TeleportFlags.ViaLocation); // ((TestClient)sp.ControllingClient).CompleteTeleportClientSide(); Assert.That(sceneB.GetScenePresence(userId), Is.Null); ScenePresence sceneASp = sceneA.GetScenePresence(userId); Assert.That(sceneASp, Is.Not.Null); Assert.That(sceneASp.Scene.RegionInfo.RegionName, Is.EqualTo(sceneA.RegionInfo.RegionName)); Assert.That(sceneASp.AbsolutePosition, Is.EqualTo(preTeleportPosition)); Assert.That(sceneA.GetRootAgentCount(), Is.EqualTo(1)); Assert.That(sceneA.GetChildAgentCount(), Is.EqualTo(0)); Assert.That(sceneB.GetRootAgentCount(), Is.EqualTo(0)); Assert.That(sceneB.GetChildAgentCount(), Is.EqualTo(0)); // TODO: Add assertions to check correct circuit details in both scenes. // Lookat is sent to the client only - sp.Lookat does not yield the same thing (calculation from camera // position instead). // Assert.That(sp.Lookat, Is.EqualTo(teleportLookAt)); // TestHelpers.DisableLogging(); } /// <summary> /// Test teleport when the destination region does not process (or does not receive) the connection attempt /// from the viewer. /// </summary> /// <remarks> /// This could be quite a common case where the source region can connect to a remove destination region /// (for CreateAgent) but the viewer cannot reach the destination region due to network issues. /// </remarks> [Test] public void TestSameSimulatorIsolatedRegions_DestinationDidNotProcessViewerConnection() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID userId = TestHelpers.ParseTail(0x1); Vector3 preTeleportPosition = new Vector3(30, 31, 32); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.Configs["Modules"].Set("EntityTransferModule", etmA.Name); config.Configs["Modules"].Set("SimulationServices", lscm.Name); config.AddConfig("EntityTransfer"); // In order to run a single threaded regression test we do not want the entity transfer module waiting // for a callback from the destination scene before removing its avatar data. config.Configs["EntityTransfer"].Set("wait_for_callback", false); // config.AddConfig("Startup"); // config.Configs["Startup"].Set("serverside_object_permissions", true); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1002, 1000); SceneHelpers.SetupSceneModules(sceneA, config, etmA); // We need to set up the permisions module on scene B so that our later use of agent limit to deny // QueryAccess won't succeed anyway because administrators are always allowed in and the default // IsAdministrator if no permissions module is present is true. SceneHelpers.SetupSceneModules(sceneB, config, new object[] { new PermissionsModule(), etmB }); // Shared scene modules SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); ScenePresence sp = SceneHelpers.AddScenePresence(sceneA, userId); sp.AbsolutePosition = preTeleportPosition; sceneA.RequestTeleportLocation( sp.ControllingClient, sceneB.RegionInfo.RegionHandle, teleportPosition, teleportLookAt, (uint)TeleportFlags.ViaLocation); // FIXME: Not setting up InformClientOfNeighbour on the TestClient means that it does not initiate // communication with the destination region. But this is a very non-obvious way of doing it - really we // should be forced to expicitly set this up. Assert.That(sceneB.GetScenePresence(userId), Is.Null); ScenePresence sceneASp = sceneA.GetScenePresence(userId); Assert.That(sceneASp, Is.Not.Null); Assert.That(sceneASp.Scene.RegionInfo.RegionName, Is.EqualTo(sceneA.RegionInfo.RegionName)); Assert.That(sceneASp.AbsolutePosition, Is.EqualTo(preTeleportPosition)); Assert.That(sceneA.GetRootAgentCount(), Is.EqualTo(1)); Assert.That(sceneA.GetChildAgentCount(), Is.EqualTo(0)); Assert.That(sceneB.GetRootAgentCount(), Is.EqualTo(0)); Assert.That(sceneB.GetChildAgentCount(), Is.EqualTo(0)); // TODO: Add assertions to check correct circuit details in both scenes. // Lookat is sent to the client only - sp.Lookat does not yield the same thing (calculation from camera // position instead). // Assert.That(sp.Lookat, Is.EqualTo(teleportLookAt)); // TestHelpers.DisableLogging(); } [Test] public void TestSameSimulatorNeighbouringRegionsV1() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID userId = TestHelpers.ParseTail(0x1); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); IConfig entityTransferConfig = config.AddConfig("EntityTransfer"); // In order to run a single threaded regression test we do not want the entity transfer module waiting // for a callback from the destination scene before removing its avatar data. entityTransferConfig.Set("wait_for_callback", false); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000); SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA); SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB); // FIXME: Hack - this is here temporarily to revert back to older entity transfer behaviour lscm.ServiceVersion = "SIMULATION/0.1"; Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); AgentCircuitData acd = SceneHelpers.GenerateAgentData(userId); TestClient tc = new TestClient(acd, sceneA); List<TestClient> destinationTestClients = new List<TestClient>(); EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients); ScenePresence beforeSceneASp = SceneHelpers.AddScenePresence(sceneA, tc, acd); beforeSceneASp.AbsolutePosition = new Vector3(30, 31, 32); Assert.That(beforeSceneASp, Is.Not.Null); Assert.That(beforeSceneASp.IsChildAgent, Is.False); ScenePresence beforeSceneBSp = sceneB.GetScenePresence(userId); Assert.That(beforeSceneBSp, Is.Not.Null); Assert.That(beforeSceneBSp.IsChildAgent, Is.True); // In this case, we will not receieve a second InformClientOfNeighbour since the viewer already knows // about the neighbour region it is teleporting to. sceneA.RequestTeleportLocation( beforeSceneASp.ControllingClient, sceneB.RegionInfo.RegionHandle, teleportPosition, teleportLookAt, (uint)TeleportFlags.ViaLocation); destinationTestClients[0].CompleteMovement(); ScenePresence afterSceneASp = sceneA.GetScenePresence(userId); Assert.That(afterSceneASp, Is.Not.Null); Assert.That(afterSceneASp.IsChildAgent, Is.True); ScenePresence afterSceneBSp = sceneB.GetScenePresence(userId); Assert.That(afterSceneBSp, Is.Not.Null); Assert.That(afterSceneBSp.IsChildAgent, Is.False); Assert.That(afterSceneBSp.Scene.RegionInfo.RegionName, Is.EqualTo(sceneB.RegionInfo.RegionName)); Assert.That(afterSceneBSp.AbsolutePosition, Is.EqualTo(teleportPosition)); Assert.That(sceneA.GetRootAgentCount(), Is.EqualTo(0)); Assert.That(sceneA.GetChildAgentCount(), Is.EqualTo(1)); Assert.That(sceneB.GetRootAgentCount(), Is.EqualTo(1)); Assert.That(sceneB.GetChildAgentCount(), Is.EqualTo(0)); // TODO: Add assertions to check correct circuit details in both scenes. // Lookat is sent to the client only - sp.Lookat does not yield the same thing (calculation from camera // position instead). // Assert.That(sp.Lookat, Is.EqualTo(teleportLookAt)); // TestHelpers.DisableLogging(); } [Test] public void TestSameSimulatorNeighbouringRegionsV2() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID userId = TestHelpers.ParseTail(0x1); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000); SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA); SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); AgentCircuitData acd = SceneHelpers.GenerateAgentData(userId); TestClient tc = new TestClient(acd, sceneA); List<TestClient> destinationTestClients = new List<TestClient>(); EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients); ScenePresence beforeSceneASp = SceneHelpers.AddScenePresence(sceneA, tc, acd); beforeSceneASp.AbsolutePosition = new Vector3(30, 31, 32); Assert.That(beforeSceneASp, Is.Not.Null); Assert.That(beforeSceneASp.IsChildAgent, Is.False); ScenePresence beforeSceneBSp = sceneB.GetScenePresence(userId); Assert.That(beforeSceneBSp, Is.Not.Null); Assert.That(beforeSceneBSp.IsChildAgent, Is.True); // Here, we need to make clientA's receipt of SendRegionTeleport trigger clientB's CompleteMovement(). This // is to operate the teleport V2 mechanism where the EntityTransferModule will first request the client to // CompleteMovement to the region and then call UpdateAgent to the destination region to confirm the receipt // Both these operations will occur on different threads and will wait for each other. // We have to do this via ThreadPool directly since FireAndForget has been switched to sync for the V1 // test protocol, where we are trying to avoid unpredictable async operations in regression tests. tc.OnTestClientSendRegionTeleport += (regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL) => ThreadPool.UnsafeQueueUserWorkItem(o => destinationTestClients[0].CompleteMovement(), null); sceneA.RequestTeleportLocation( beforeSceneASp.ControllingClient, sceneB.RegionInfo.RegionHandle, teleportPosition, teleportLookAt, (uint)TeleportFlags.ViaLocation); ScenePresence afterSceneASp = sceneA.GetScenePresence(userId); Assert.That(afterSceneASp, Is.Not.Null); Assert.That(afterSceneASp.IsChildAgent, Is.True); ScenePresence afterSceneBSp = sceneB.GetScenePresence(userId); Assert.That(afterSceneBSp, Is.Not.Null); Assert.That(afterSceneBSp.IsChildAgent, Is.False); Assert.That(afterSceneBSp.Scene.RegionInfo.RegionName, Is.EqualTo(sceneB.RegionInfo.RegionName)); Assert.That(afterSceneBSp.AbsolutePosition, Is.EqualTo(teleportPosition)); Assert.That(sceneA.GetRootAgentCount(), Is.EqualTo(0)); Assert.That(sceneA.GetChildAgentCount(), Is.EqualTo(1)); Assert.That(sceneB.GetRootAgentCount(), Is.EqualTo(1)); Assert.That(sceneB.GetChildAgentCount(), Is.EqualTo(0)); // TODO: Add assertions to check correct circuit details in both scenes. // Lookat is sent to the client only - sp.Lookat does not yield the same thing (calculation from camera // position instead). // Assert.That(sp.Lookat, Is.EqualTo(teleportLookAt)); // TestHelpers.DisableLogging(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using Xunit; namespace System.Threading.Tasks.Tests { public class AsyncValueTaskMethodBuilderTests { [Fact] public void Create_ReturnsDefaultInstance() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); Assert.Equal(default(AsyncValueTaskMethodBuilder<int>), b); // implementation detail being verified } [Fact] public void SetResult_BeforeAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); b.SetResult(42); ValueTask<int> vt = b.Task; Assert.True(vt.IsCompletedSuccessfully); Assert.False(WrapsTask(vt)); Assert.Equal(42, vt.Result); } [Fact] public void SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); ValueTask<int> vt = b.Task; b.SetResult(42); Assert.True(vt.IsCompletedSuccessfully); Assert.True(WrapsTask(vt)); Assert.Equal(42, vt.Result); } [Fact] public void SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var e = new FormatException(); b.SetException(e); ValueTask<int> vt = b.Task; Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var e = new FormatException(); ValueTask<int> vt = b.Task; b.SetException(e); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var e = new OperationCanceledException(); ValueTask<int> vt = b.Task; b.SetException(e); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Theory] [InlineData(false)] [InlineData(true)] public async Task AwaitOnCompleted_InvokesStateMachineMethods(bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var ignored = b.Task; var callbackCompleted = new TaskCompletionSource<bool>(); IAsyncStateMachine foundSm = null; var dsm = new DelegateStateMachine { MoveNextDelegate = () => callbackCompleted.SetResult(true), SetStateMachineDelegate = sm => foundSm = sm }; TaskAwaiter t = Task.CompletedTask.GetAwaiter(); if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } await callbackCompleted.Task; Assert.Equal(dsm, foundSm); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(42); Assert.True(WrapsTask(b.Task)); Assert.Equal(42, b.Task.Result); } [Fact] public void SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); Assert.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); b.SetStateMachine(new DelegateStateMachine()); } [Fact] public void Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(42); ValueTask<int> vt = b.Task; Assert.False(WrapsTask(vt)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task UsedWithAsyncMethod_CompletesSuccessfully(int yields) { Assert.Equal(42, await ValueTaskReturningAsyncMethod(42)); ValueTask<int> vt = ValueTaskReturningAsyncMethod(84); Assert.Equal(yields > 0, WrapsTask(vt)); Assert.Equal(84, await vt); async ValueTask<int> ValueTaskReturningAsyncMethod(int result) { for (int i = 0; i < yields; i++) await Task.Yield(); return result; } } /// <summary>Gets whether the ValueTask has a non-null Task.</summary> private static bool WrapsTask<T>(ValueTask<T> vt) => ReferenceEquals(vt.AsTask(), vt.AsTask()); private struct DelegateStateMachine : IAsyncStateMachine { internal Action MoveNextDelegate; public void MoveNext() => MoveNextDelegate?.Invoke(); internal Action<IAsyncStateMachine> SetStateMachineDelegate; public void SetStateMachine(IAsyncStateMachine stateMachine) => SetStateMachineDelegate?.Invoke(stateMachine); } } }