context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// System.Array.SetValue(system.object,Int32[]) /// </summary> public class ArrayIndexOf1 { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Test a two dimension array "); try { string[,] s1 = new string[2, 3]; string s_value = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); s1.SetValue(s_value, 1, 0); if (s1[1, 0] != s_value) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Test a three dimension array "); try { int[, ,] s1 = new int[9, 7, 5]; int i_value = TestLibrary.Generator.GetInt32(-55); s1.SetValue(i_value, 8, 6, 4); if (s1[8, 6, 4] != i_value) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Test a multiple dimension array "); try { string[, , , , , ,] s1 = new string[7, 7, 7, 7, 7, 7, 7]; int[] i_index = new int[7] { 2, 3, 4, 6, 4, 5, 0 }; string s_value = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); s1.SetValue(s_value, i_index); if (s1[2, 3, 4, 6, 4, 5, 0] != s_value) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Test a multiple dimension array with customized type TypeA "); try { TypeA[, , , ,] s1 = new TypeA[9, 9, 9, 9, 9]; int[] i_index = new int[5] { 2, 3, 4, 6, 8 }; string value = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TypeA typea = new TypeA(value); s1.SetValue(typea, i_index); if (s1[2, 3, 4, 6, 8].a != value) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1:The second argument indices is null reference "); try { int[, ,] s1 = new int[9, 7, 5]; int i_value = TestLibrary.Generator.GetInt32(-55); int[] i_index = null; s1.SetValue(i_value, i_index); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2:The number of dimensions in the current Array is not equal to the number of elements in indices "); try { int[, ,] s1 = new int[9, 7, 5]; int i_value = TestLibrary.Generator.GetInt32(-55); int[] i_index = new int[4] { 1, 3, 2, 7 }; s1.SetValue(i_value, i_index); TestLibrary.TestFramework.LogError("103", "The ArgumentException was not thrown as expected"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: Value cannot be cast to the element type of the current Array"); try { int[, ,] s1 = new int[9, 7, 5]; string i_value = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); int[] i_index = new int[3] { 1, 3, 4 }; s1.SetValue(i_value, i_index); TestLibrary.TestFramework.LogError("105", "The InvalidCastException was not thrown as expected"); retVal = false; } catch (InvalidCastException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: indices is outside the range of array"); try { int[, ,] s1 = new int[9, 7, 5]; int i_value = TestLibrary.Generator.GetInt32(-55); int[] i_index = new int[3] { 9, 3, 4 }; s1.SetValue(i_value, i_index); TestLibrary.TestFramework.LogError("105", "The IndexOutOfRangeException was not thrown as expected"); retVal = false; } catch (IndexOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArrayIndexOf1 test = new ArrayIndexOf1(); TestLibrary.TestFramework.BeginTestCase("ArrayIndexOf1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } } class TypeA { public TypeA(string a) { this.a_value = a; } private string a_value; public string a { get { return this.a_value; } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Cassandra.Connections; using Cassandra.MetadataHelpers; using Cassandra.Requests; using Cassandra.Tasks; namespace Cassandra { /// <summary> /// Keeps metadata on the connected cluster, including known nodes and schema /// definitions. /// </summary> public class Metadata : IDisposable { private const string SelectSchemaVersionPeers = "SELECT schema_version FROM system.peers"; private const string SelectSchemaVersionLocal = "SELECT schema_version FROM system.local"; private static readonly Logger Logger = new Logger(typeof(ControlConnection)); private volatile TokenMap _tokenMap; private volatile ConcurrentDictionary<string, KeyspaceMetadata> _keyspaces = new ConcurrentDictionary<string, KeyspaceMetadata>(); private volatile SchemaParser _schemaParser; private readonly int _queryAbortTimeout; public event HostsEventHandler HostsEvent; public event SchemaChangedEventHandler SchemaChangedEvent; /// <summary> /// Returns the name of currently connected cluster. /// </summary> /// <returns>the Cassandra name of currently connected cluster.</returns> public String ClusterName { get; internal set; } /// <summary> /// Gets the configuration associated with this instance. /// </summary> internal Configuration Configuration { get; private set; } /// <summary> /// Control connection to be used to execute the queries to retrieve the metadata /// </summary> internal IControlConnection ControlConnection { get; set; } internal SchemaParser SchemaParser { get { return _schemaParser; } } internal string Partitioner { get; set; } internal Hosts Hosts { get; private set; } internal IReadOnlyDictionary<string, IEnumerable<IPEndPoint>> ResolvedContactPoints { get; private set; } = new Dictionary<string, IEnumerable<IPEndPoint>>(); internal IReadOnlyTokenMap TokenToReplicasMap => _tokenMap; internal Metadata(Configuration configuration) { _queryAbortTimeout = configuration.DefaultRequestOptions.QueryAbortTimeout; Configuration = configuration; Hosts = new Hosts(); Hosts.Down += OnHostDown; Hosts.Up += OnHostUp; } internal Metadata(Configuration configuration, SchemaParser schemaParser) : this(configuration) { _schemaParser = schemaParser; } public void Dispose() { ShutDown(); } internal void SetResolvedContactPoints(IReadOnlyDictionary<string, IEnumerable<IPEndPoint>> resolvedContactPoints) { ResolvedContactPoints = resolvedContactPoints; } public Host GetHost(IPEndPoint address) { if (Hosts.TryGet(address, out var host)) return host; return null; } internal Host AddHost(IPEndPoint address) { return Hosts.Add(address); } internal void RemoveHost(IPEndPoint address) { Hosts.RemoveIfExists(address); } internal void FireSchemaChangedEvent(SchemaChangedEventArgs.Kind what, string keyspace, string table, object sender = null) { if (SchemaChangedEvent != null) { SchemaChangedEvent(sender ?? this, new SchemaChangedEventArgs { Keyspace = keyspace, What = what, Table = table }); } } private void OnHostDown(Host h) { if (HostsEvent != null) { HostsEvent(this, new HostsEventArgs { Address = h.Address, What = HostsEventArgs.Kind.Down }); } } private void OnHostUp(Host h) { if (HostsEvent != null) { HostsEvent(h, new HostsEventArgs { Address = h.Address, What = HostsEventArgs.Kind.Up }); } } /// <summary> /// Returns all known hosts of this cluster. /// </summary> /// <returns>collection of all known hosts of this cluster.</returns> public ICollection<Host> AllHosts() { return Hosts.ToCollection(); } public IEnumerable<IPEndPoint> AllReplicas() { return Hosts.AllEndPointsToCollection(); } // for tests internal KeyValuePair<string, KeyspaceMetadata>[] KeyspacesSnapshot => _keyspaces.ToArray(); internal async Task RebuildTokenMapAsync(bool retry, bool fetchKeyspaces) { IEnumerable<KeyspaceMetadata> ksList = null; if (fetchKeyspaces) { Metadata.Logger.Info("Retrieving keyspaces metadata"); ksList = await _schemaParser.GetKeyspacesAsync(retry).ConfigureAwait(false); } ConcurrentDictionary<string, KeyspaceMetadata> keyspaces; if (ksList != null) { Metadata.Logger.Info("Updating keyspaces metadata"); var ksMap = ksList.Select(ks => new KeyValuePair<string, KeyspaceMetadata>(ks.Name, ks)); keyspaces = new ConcurrentDictionary<string, KeyspaceMetadata>(ksMap); } else { keyspaces = _keyspaces; } Metadata.Logger.Info("Rebuilding token map"); if (Partitioner == null) { throw new DriverInternalError("Partitioner can not be null"); } var tokenMap = TokenMap.Build(Partitioner, Hosts.ToCollection(), keyspaces.Values); _keyspaces = keyspaces; _tokenMap = tokenMap; } /// <summary> /// this method should be called by the event debouncer /// </summary> internal bool RemoveKeyspaceFromTokenMap(string name) { Metadata.Logger.Verbose("Removing keyspace metadata: " + name); var dropped = _keyspaces.TryRemove(name, out _); _tokenMap?.RemoveKeyspace(name); return dropped; } internal async Task<KeyspaceMetadata> UpdateTokenMapForKeyspace(string name) { var keyspaceMetadata = await _schemaParser.GetKeyspaceAsync(name).ConfigureAwait(false); var dropped = false; var updated = false; if (_tokenMap == null) { await RebuildTokenMapAsync(false, false).ConfigureAwait(false); } if (keyspaceMetadata == null) { Metadata.Logger.Verbose("Removing keyspace metadata: " + name); dropped = _keyspaces.TryRemove(name, out _); _tokenMap?.RemoveKeyspace(name); } else { Metadata.Logger.Verbose("Updating keyspace metadata: " + name); _keyspaces.AddOrUpdate(keyspaceMetadata.Name, keyspaceMetadata, (k, v) => { updated = true; return keyspaceMetadata; }); Metadata.Logger.Info("Rebuilding token map for keyspace {0}", keyspaceMetadata.Name); if (Partitioner == null) { throw new DriverInternalError("Partitioner can not be null"); } _tokenMap.UpdateKeyspace(keyspaceMetadata); } if (Configuration.MetadataSyncOptions.MetadataSyncEnabled) { if (dropped) { FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Dropped, name, null, this); } else if (updated) { FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Updated, name, null, this); } else { FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Created, name, null, this); } } return keyspaceMetadata; } /// <summary> /// Get the replicas for a given partition key and keyspace /// </summary> public ICollection<Host> GetReplicas(string keyspaceName, byte[] partitionKey) { if (_tokenMap == null) { Metadata.Logger.Warning("Metadata.GetReplicas was called but there was no token map."); return new Host[0]; } return _tokenMap.GetReplicas(keyspaceName, _tokenMap.Factory.Hash(partitionKey)); } public ICollection<Host> GetReplicas(byte[] partitionKey) { return GetReplicas(null, partitionKey); } /// <summary> /// Returns metadata of specified keyspace. /// </summary> /// <param name="keyspace"> the name of the keyspace for which metadata should be /// returned. </param> /// <returns>the metadata of the requested keyspace or <c>null</c> if /// <c>* keyspace</c> is not a known keyspace.</returns> public KeyspaceMetadata GetKeyspace(string keyspace) { if (Configuration.MetadataSyncOptions.MetadataSyncEnabled) { //Use local cache _keyspaces.TryGetValue(keyspace, out var ksInfo); return ksInfo; } return TaskHelper.WaitToComplete(SchemaParser.GetKeyspaceAsync(keyspace), _queryAbortTimeout); } /// <summary> /// Returns a collection of all defined keyspaces names. /// </summary> /// <returns>a collection of all defined keyspaces names.</returns> public ICollection<string> GetKeyspaces() { if (Configuration.MetadataSyncOptions.MetadataSyncEnabled) { //Use local cache return _keyspaces.Keys; } return TaskHelper.WaitToComplete(SchemaParser.GetKeyspacesNamesAsync(), _queryAbortTimeout); } /// <summary> /// Returns names of all tables which are defined within specified keyspace. /// </summary> /// <param name="keyspace">the name of the keyspace for which all tables metadata should be /// returned.</param> /// <returns>an ICollection of the metadata for the tables defined in this /// keyspace.</returns> public ICollection<string> GetTables(string keyspace) { if (Configuration.MetadataSyncOptions.MetadataSyncEnabled) { return !_keyspaces.TryGetValue(keyspace, out var ksMetadata) ? new string[0] : ksMetadata.GetTablesNames(); } return TaskHelper.WaitToComplete(SchemaParser.GetTableNamesAsync(keyspace), _queryAbortTimeout); } /// <summary> /// Returns TableMetadata for specified table in specified keyspace. /// </summary> /// <param name="keyspace">name of the keyspace within specified table is defined.</param> /// <param name="tableName">name of table for which metadata should be returned.</param> /// <returns>a TableMetadata for the specified table in the specified keyspace.</returns> public TableMetadata GetTable(string keyspace, string tableName) { return TaskHelper.WaitToComplete(GetTableAsync(keyspace, tableName), _queryAbortTimeout * 2); } internal Task<TableMetadata> GetTableAsync(string keyspace, string tableName) { if (Configuration.MetadataSyncOptions.MetadataSyncEnabled) { return !_keyspaces.TryGetValue(keyspace, out var ksMetadata) ? Task.FromResult<TableMetadata>(null) : ksMetadata.GetTableMetadataAsync(tableName); } return SchemaParser.GetTableAsync(keyspace, tableName); } /// <summary> /// Returns the view metadata for the provided view name in the keyspace. /// </summary> /// <param name="keyspace">name of the keyspace within specified view is defined.</param> /// <param name="name">name of view.</param> /// <returns>a MaterializedViewMetadata for the view in the specified keyspace.</returns> public MaterializedViewMetadata GetMaterializedView(string keyspace, string name) { if (Configuration.MetadataSyncOptions.MetadataSyncEnabled) { return !_keyspaces.TryGetValue(keyspace, out var ksMetadata) ? null : ksMetadata.GetMaterializedViewMetadata(name); } return TaskHelper.WaitToComplete(SchemaParser.GetViewAsync(keyspace, name), _queryAbortTimeout * 2); } /// <summary> /// Gets the definition associated with a User Defined Type from Cassandra /// </summary> public UdtColumnInfo GetUdtDefinition(string keyspace, string typeName) { return TaskHelper.WaitToComplete(GetUdtDefinitionAsync(keyspace, typeName), _queryAbortTimeout); } /// <summary> /// Gets the definition associated with a User Defined Type from Cassandra /// </summary> public Task<UdtColumnInfo> GetUdtDefinitionAsync(string keyspace, string typeName) { if (Configuration.MetadataSyncOptions.MetadataSyncEnabled) { return !_keyspaces.TryGetValue(keyspace, out var ksMetadata) ? Task.FromResult<UdtColumnInfo>(null) : ksMetadata.GetUdtDefinitionAsync(typeName); } return SchemaParser.GetUdtDefinitionAsync(keyspace, typeName); } /// <summary> /// Gets the definition associated with a User Defined Function from Cassandra /// </summary> /// <returns>The function metadata or null if not found.</returns> public FunctionMetadata GetFunction(string keyspace, string name, string[] signature) { if (Configuration.MetadataSyncOptions.MetadataSyncEnabled) { return !_keyspaces.TryGetValue(keyspace, out var ksMetadata) ? null : ksMetadata.GetFunction(name, signature); } var signatureString = SchemaParser.ComputeFunctionSignatureString(signature); return TaskHelper.WaitToComplete(SchemaParser.GetFunctionAsync(keyspace, name, signatureString), _queryAbortTimeout); } /// <summary> /// Gets the definition associated with a aggregate from Cassandra /// </summary> /// <returns>The aggregate metadata or null if not found.</returns> public AggregateMetadata GetAggregate(string keyspace, string name, string[] signature) { if (Configuration.MetadataSyncOptions.MetadataSyncEnabled) { return !_keyspaces.TryGetValue(keyspace, out var ksMetadata) ? null : ksMetadata.GetAggregate(name, signature); } var signatureString = SchemaParser.ComputeFunctionSignatureString(signature); return TaskHelper.WaitToComplete(SchemaParser.GetAggregateAsync(keyspace, name, signatureString), _queryAbortTimeout); } /// <summary> /// Gets the query trace. /// </summary> /// <param name="trace">The query trace that contains the id, which properties are going to be populated.</param> /// <returns></returns> internal Task<QueryTrace> GetQueryTraceAsync(QueryTrace trace) { return _schemaParser.GetQueryTraceAsync(trace, Configuration.Timer); } /// <summary> /// Updates the keyspace and token information /// </summary> public bool RefreshSchema(string keyspace = null, string table = null) { return TaskHelper.WaitToComplete(RefreshSchemaAsync(keyspace, table), Configuration.DefaultRequestOptions.QueryAbortTimeout * 2); } /// <summary> /// Updates the keyspace and token information /// </summary> public async Task<bool> RefreshSchemaAsync(string keyspace = null, string table = null) { if (keyspace == null) { await ControlConnection.ScheduleAllKeyspacesRefreshAsync(true).ConfigureAwait(false); return true; } await ControlConnection.ScheduleKeyspaceRefreshAsync(keyspace, true).ConfigureAwait(false); _keyspaces.TryGetValue(keyspace, out var ks); if (ks == null) { return false; } if (table != null) { ks.ClearTableMetadata(table); } return true; } public void ShutDown(int timeoutMs = Timeout.Infinite) { //it is really not required to be called, left as it is part of the public API //dereference the control connection ControlConnection = null; } /// <summary> /// this method should be called by the event debouncer /// </summary> internal bool RemoveKeyspace(string name) { var existed = RemoveKeyspaceFromTokenMap(name); if (!existed) { return false; } FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Dropped, name, null, this); return true; } /// <summary> /// this method should be called by the event debouncer /// </summary> internal Task<KeyspaceMetadata> RefreshSingleKeyspace(string name) { return UpdateTokenMapForKeyspace(name); } internal void ClearTable(string keyspaceName, string tableName) { if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata)) { ksMetadata.ClearTableMetadata(tableName); } } internal void ClearView(string keyspaceName, string name) { if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata)) { ksMetadata.ClearViewMetadata(name); } } internal void ClearFunction(string keyspaceName, string functionName, string[] signature) { if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata)) { ksMetadata.ClearFunction(functionName, signature); } } internal void ClearAggregate(string keyspaceName, string aggregateName, string[] signature) { if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata)) { ksMetadata.ClearAggregate(aggregateName, signature); } } /// <summary> /// Initiates a schema agreement check. /// <para/> /// Schema changes need to be propagated to all nodes in the cluster. /// Once they have settled on a common version, we say that they are in agreement. /// <para/> /// This method does not perform retries so /// <see cref="ProtocolOptions.MaxSchemaAgreementWaitSeconds"/> does not apply. /// </summary> /// <returns>True if schema agreement was successful and false if it was not successful.</returns> public async Task<bool> CheckSchemaAgreementAsync() { if (Hosts.Count == 1) { // If there is just one node, the schema is up to date in all nodes :) return true; } try { var queries = new[] { ControlConnection.QueryAsync(SelectSchemaVersionLocal), ControlConnection.QueryAsync(SelectSchemaVersionPeers) }; await Task.WhenAll(queries).ConfigureAwait(false); return CheckSchemaVersionResults(queries[0].Result, queries[1].Result); } catch (Exception ex) { Logger.Error("Error while checking schema agreement.", ex); } return false; } /// <summary> /// Checks if there is only one schema version between the provided query results. /// </summary> /// <param name="localVersionQuery"> /// Results obtained from a query to <code>system.local</code> table. /// Must contain the <code>schema_version</code> column. /// </param> /// <param name="peerVersionsQuery"> /// Results obtained from a query to <code>system.peers</code> table. /// Must contain the <code>schema_version</code> column. /// </param> /// <returns><code>True</code> if there is a schema agreement (only 1 schema version). <code>False</code> otherwise.</returns> private static bool CheckSchemaVersionResults( IEnumerable<Row> localVersionQuery, IEnumerable<Row> peerVersionsQuery) { return new HashSet<Guid>( peerVersionsQuery .Concat(localVersionQuery) .Select(r => r.GetValue<Guid>("schema_version"))).Count == 1; } /// <summary> /// Waits until that the schema version in all nodes is the same or the waiting time passed. /// This method blocks the calling thread. /// </summary> internal bool WaitForSchemaAgreement(IConnection connection) { if (Hosts.Count == 1) { //If there is just one node, the schema is up to date in all nodes :) return true; } var start = DateTime.Now; var waitSeconds = Configuration.ProtocolOptions.MaxSchemaAgreementWaitSeconds; Metadata.Logger.Info("Waiting for schema agreement"); try { var totalVersions = 0; while (DateTime.Now.Subtract(start).TotalSeconds < waitSeconds) { var schemaVersionLocalQuery = new QueryRequest(ControlConnection.ProtocolVersion, Metadata.SelectSchemaVersionLocal, false, QueryProtocolOptions.Default); var schemaVersionPeersQuery = new QueryRequest(ControlConnection.ProtocolVersion, Metadata.SelectSchemaVersionPeers, false, QueryProtocolOptions.Default); var queries = new[] { connection.Send(schemaVersionLocalQuery), connection.Send(schemaVersionPeersQuery) }; // ReSharper disable once CoVariantArrayConversion Task.WaitAll(queries, Configuration.DefaultRequestOptions.QueryAbortTimeout); if (Metadata.CheckSchemaVersionResults( Connections.ControlConnection.GetRowSet(queries[0].Result), Connections.ControlConnection.GetRowSet(queries[1].Result))) { return true; } Thread.Sleep(500); } Metadata.Logger.Info($"Waited for schema agreement, still {totalVersions} schema versions in the cluster."); } catch (Exception ex) { //Exceptions are not fatal Metadata.Logger.Error("There was an exception while trying to retrieve schema versions", ex); } return false; } /// <summary> /// Sets the Cassandra version in order to identify how to parse the metadata information /// </summary> /// <param name="version"></param> internal void SetCassandraVersion(Version version) { _schemaParser = SchemaParser.GetInstance(version, this, GetUdtDefinitionAsync, _schemaParser); } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Box = OpenSim.Framework.Geom.Box; using System.Collections.Generic; using System.Linq; using System.Threading; using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.CoreModules.Agent.SceneView { /// <summary> /// A Culling Module for ScenePresences. /// </summary> /// <remarks> /// Cull updates for ScenePresences. This does simple Draw Distance culling but could be expanded to work /// off of other scene parameters as well; /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class SceneViewModule : ISceneViewModule, INonSharedRegionModule { #region Declares private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public bool UseCulling { get; set; } #endregion #region ISharedRegionModule Members public SceneViewModule() { UseCulling = false; } public string Name { get { return "SceneViewModule"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { IConfig config = source.Configs["SceneView"]; if (config != null) { UseCulling = config.GetBoolean("UseCulling", true); } else { UseCulling = true; } m_log.DebugFormat("[SCENE VIEW]: INITIALIZED MODULE, CULLING is {0}", (UseCulling ? "ENABLED" : "DISABLED")); } public void Close() { } public void AddRegion(Scene scene) { scene.RegisterModuleInterface<ISceneViewModule>(this); } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { } #endregion #region ICullerModule Members /// <summary> /// Create a scene view for the given presence /// </summary> /// <param name="presence"></param> /// <returns></returns> public ISceneView CreateSceneView(ScenePresence presence) { return new SceneView(presence, UseCulling); } #endregion } public class SceneView : ISceneView { #region Declares private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int _MINIMUM_DRAW_DISTANCE = 32; private ScenePresence m_presence; private int m_perfMonMS; private int m_timeBeforeChildAgentUpdate; private OpenSim.Region.Framework.Scenes.Types.UpdateQueue m_partsUpdateQueue = new OpenSim.Region.Framework.Scenes.Types.UpdateQueue(); private Dictionary<uint, ScenePartUpdate> m_updateTimes = new Dictionary<uint, ScenePartUpdate>(); private List<UUID> m_presencesInView = new List<UUID>(); private bool[,] m_TerrainCulling = new bool[16, 16]; public bool UseCulling { get; set; } public float DistanceBeforeCullingRequired { get; set; } public bool NeedsFullSceneUpdate { get; set; } public bool HasFinishedInitialUpdate { get; set; } #endregion #region Constructor public SceneView(ScenePresence presence, bool useCulling) { UseCulling = useCulling; NeedsFullSceneUpdate = true; HasFinishedInitialUpdate = false; m_presence = presence; //Update every 1/4th a draw distance DistanceBeforeCullingRequired = _MINIMUM_DRAW_DISTANCE / 8; } #endregion #region Culler Methods /// <summary> /// Checks to see whether any prims, avatars, or terrain have come into view since the last culling check /// </summary> public void CheckForDistantEntitiesToShow() { if (UseCulling == false) return; //With 25K objects, this method takes around 10ms if the client has seen none of the objects in the sim if (m_presence.DrawDistance <= 0) return; if (m_presence.IsInTransit) return; // disable prim updates during a crossing, but leave them queued for after transition if (m_presence.Closed) { //Don't check if we are closed, and clear the update queues ClearAllTracking(); return; } Util.FireAndForget((o) => { CheckForDistantTerrainToShow(); CheckForDistantPrimsToShow(); CheckForDistantAvatarsToShow(); HasFinishedInitialUpdate = true; }); } #endregion #region Avatar Culling /// <summary> /// Checks to see whether any new avatars have come into view since the last time culling checks were done /// </summary> private void CheckForDistantAvatarsToShow() { List<ScenePresence> SPs; lock (m_presence.Scene.SyncRoot) { if (!m_presence.IsChildAgent || m_presence.Scene.m_seeIntoRegionFromNeighbor) SPs = m_presence.Scene.GetScenePresences(); else return; } Vector3 clientAbsPosition = m_presence.AbsolutePosition; foreach (ScenePresence presence in SPs) { if (m_presence.Closed) { ClearAllTracking(); return; } if (presence.UUID != m_presence.UUID) { if (ShowEntityToClient(clientAbsPosition, presence) || ShowEntityToClient(m_presence.CameraPosition, presence)) { if (!m_presencesInView.Contains(presence.UUID)) { //Send the update both ways SendPresenceToUs(presence); presence.SceneView.SendPresenceToUs(m_presence); } else { //Check to see whether any attachments have changed for both users CheckWhetherAttachmentsHaveChanged(presence); if (!m_presence.IsChildAgent) presence.SceneView.CheckWhetherAttachmentsHaveChanged(m_presence); } } } } } public void CheckWhetherAttachmentsHaveChanged(ScenePresence presence) { foreach (SceneObjectGroup grp in presence.GetAttachments()) { if (CheckWhetherAttachmentShouldBeSent(grp)) SendGroupUpdate(grp); } } public void ClearFromScene(ScenePresence presence) { m_presencesInView.Remove(presence.UUID); } public void ClearScene() { m_presencesInView.Clear(); } /// <summary> /// Tests to see whether the given avatar can be seen by the client at the given position /// </summary> /// <param name="clientAbsPosition">Position to check from</param> /// <param name="presence">The avatar to check</param> /// <returns></returns> public bool ShowEntityToClient(Vector3 clientAbsPosition, ScenePresence presence) { if (UseCulling == false) return true; Vector3 avpos; if (!presence.HasSafePosition(out avpos)) return false; float drawDistance = m_presence.DrawDistance; if (m_presence.DrawDistance < _MINIMUM_DRAW_DISTANCE) drawDistance = _MINIMUM_DRAW_DISTANCE; //Smallest distance we will check return Vector3.DistanceSquared(clientAbsPosition, avpos) <= drawDistance * drawDistance; } #region Avatar Update Sending methods public void SendAvatarTerseUpdate(ScenePresence scenePresence) { //if (!ShowEntityToClient(m_presence.AbsolutePosition, scenePresence)) // return;//When they move around, they will trigger more updates, so when they get into the other avatar's DD, they will update Vector3 vPos = Vector3.Zero; Quaternion vRot = Quaternion.Identity; uint vParentID = 0; m_perfMonMS = Environment.TickCount; scenePresence.RecalcVisualPosition(out vPos, out vRot, out vParentID); // vParentID is not used in terse updates. o.O PhysicsActor physActor = scenePresence.PhysicsActor; Vector3 vel = scenePresence.Velocity; Vector3 accel = (physActor != null) ? physActor.Acceleration : Vector3.Zero; // m_log.InfoFormat("[SCENE PRESENCE]: SendTerseUpdateToClient sit at {0} vel {1} rot {2} ", pos.ToString(),vel.ToString(), rot.ToString()); m_presence.ControllingClient.SendAvatarTerseUpdate(scenePresence.Scene.RegionInfo.RegionHandle, (ushort)(scenePresence.Scene.TimeDilation * ushort.MaxValue), scenePresence.LocalId, vPos, vel, accel, vRot, scenePresence.UUID, physActor != null ? physActor.CollisionPlane : Vector4.UnitW); m_presence.Scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS); m_presence.Scene.StatsReporter.AddAgentUpdates(1); } /// <summary> /// Tell other client about this avatar (The client previously didn't know or had outdated details about this avatar) /// </summary> /// <param name="remoteAvatar"></param> public void SendFullUpdateToOtherClient(ScenePresence otherClient) { if (m_presence.IsChildAgent) return;//Never send data from a child client // 2 stage check is needed. if (otherClient == null) return; if (otherClient.ControllingClient == null) return; if (m_presence.Appearance.Texture == null) return; //if (ShowEntityToClient(otherClient.AbsolutePosition, m_presence)) m_presence.SendAvatarData(otherClient.ControllingClient, false); } /// <summary> /// Tell *ALL* agents about this agent /// </summary> public void SendInitialFullUpdateToAllClients() { m_perfMonMS = Environment.TickCount; List<ScenePresence> avatars = m_presence.Scene.GetScenePresences(); Vector3 clientAbsPosition = m_presence.AbsolutePosition; foreach (ScenePresence avatar in avatars) { // don't notify self of self (confuses the viewer). if (avatar.UUID == m_presence.UUID) continue; // okay, send the other avatar to our client // if (ShowEntityToClient(clientAbsPosition, avatar)) SendPresenceToUs(avatar); // also show our avatar to the others, including those in other child regions if (avatar.IsDeleted || avatar.IsInTransit) continue; // if (ShowEntityToClient(avatar.AbsolutePosition, m_presence)) avatar.SceneView.SendPresenceToUs(m_presence); } m_presence.Scene.StatsReporter.AddAgentUpdates(avatars.Count); m_presence.Scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS); } /// <summary> /// Tell our client about other client's avatar (includes appearance and full object update) /// </summary> /// <param name="m_presence"></param> public void SendPresenceToUs(ScenePresence avatar) { if (m_presence.IsBot) return; if (avatar.IsChildAgent) return; if (!avatar.IsFullyInRegion) return; // don't send to them yet, they aren't ready if (avatar.IsDeleted) return; // don't send them, they're on their way outta here // Witnessed an exception internal to the .Add method with the list resizing. The avatar.UUID was // already in the list inside the .Add call, so it should be safe to ignore here (already added). try { if (!m_presencesInView.Contains(avatar.UUID)) m_presencesInView.Add(avatar.UUID); } catch(Exception) { m_log.InfoFormat("[SCENEVIEW]: Exception adding presence, probably race with it already added. Ignoring."); } avatar.SceneView.SendFullUpdateToOtherClient(m_presence); avatar.SendAppearanceToOtherAgent(m_presence); avatar.SendAnimPackToClient(m_presence.ControllingClient); avatar.SendFullUpdateForAttachments(m_presence); } /// <summary> /// Sends a full update for our client to all clients in the scene /// </summary> public void SendFullUpdateToAllClients() { m_perfMonMS = Environment.TickCount; // only send update from root agents to other clients; children are only "listening posts" List<ScenePresence> avatars = m_presence.Scene.GetAvatars(); foreach (ScenePresence avatar in avatars) { if (avatar.IsDeleted) continue; if (avatar.IsInTransit) continue; SendFullUpdateToOtherClient(avatar); } m_presence.Scene.StatsReporter.AddAgentUpdates(avatars.Count); m_presence.Scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS); // Thread.Sleep(100); m_presence.SendAnimPack(); } #endregion #endregion #region Prim Culling /// <summary> /// Checks to see whether any new prims have come into view since the last time culling checks were done /// </summary> private void CheckForDistantPrimsToShow() { List<EntityBase> SOGs; lock (m_presence.Scene.SyncRoot) { if (!m_presence.IsChildAgent || m_presence.Scene.m_seeIntoRegionFromNeighbor) SOGs = m_presence.Scene.Entities.GetAllByType<SceneObjectGroup>(); else return; } Vector3 clientAbsPosition = m_presence.AbsolutePosition; List<KeyValuePair<double, SceneObjectGroup>> grps = new List<KeyValuePair<double, SceneObjectGroup>>(); foreach (EntityBase sog in SOGs) { SceneObjectGroup e = (SceneObjectGroup)sog; if (m_presence.Closed) { ClearAllTracking(); return; } if ((e).IsAttachment) { if(CheckWhetherAttachmentShouldBeSent(e)) grps.Add(new KeyValuePair<double, SceneObjectGroup>(0, e)); continue; } if ((e).IsAttachedHUD && (e).OwnerID != m_presence.UUID) continue;//Don't ever send HUD attachments to non-owners SceneObjectPart[] sogParts = null; bool needsParts = false; lock (m_updateTimes) { if (m_updateTimes.ContainsKey(e.LocalId)) { needsParts = true; } } if (needsParts) sogParts = e.GetParts(); lock (m_updateTimes) { if (m_updateTimes.ContainsKey(e.LocalId)) { bool hasBeenUpdated = false; if (sogParts == null) sogParts = e.GetParts(); foreach (SceneObjectPart part in sogParts) { if (!m_updateTimes.ContainsKey(part.LocalId)) { //Threading issue? Shouldn't happen unless this method is called // while a group is being sent, but hasn't sent all prims yet // so... let's ignore the prim that is missing for now, and if // any other parts change, it'll re-send it all hasBeenUpdated = true; break; } ScenePartUpdate update = m_updateTimes[part.LocalId]; if (update.LastFullUpdateTimeRequested == update.LastFullUpdateTime && update.LastTerseUpdateTime == update.LastTerseUpdateTimeRequested) continue;//Only if we haven't sent them this prim before and it hasn't changed //It's changed, check again hasBeenUpdated = true; break; } if (!hasBeenUpdated) continue;//Only if we haven't sent them this prim before and it hasn't changed } } double distance; if (!ShowEntityToClient(clientAbsPosition, e, out distance) && !ShowEntityToClient(m_presence.CameraPosition, e, out distance)) continue; grps.Add(new KeyValuePair<double, SceneObjectGroup>(distance, e)); } KeyValuePair<double, SceneObjectGroup>[] arry = grps.ToArray(); C5.Sorting.IntroSort<KeyValuePair<double, SceneObjectGroup>>(arry, 0, arry.Length, new DoubleComparer()); //Sort by distance here, so that we send the closest updates first foreach (KeyValuePair<double, SceneObjectGroup> kvp in arry) { if (m_presence.Closed) { ClearAllTracking(); return; } SendGroupUpdate(kvp.Value); } } private bool CheckWhetherAttachmentShouldBeSent(SceneObjectGroup e) { bool hasBeenUpdated = false; SceneObjectPart[] attParts = e.GetParts(); lock (m_updateTimes) { foreach (SceneObjectPart part in attParts) { if (!m_updateTimes.ContainsKey(part.LocalId)) { //Threading issue? Shouldn't happen unless this method is called // while a group is being sent, but hasn't sent all prims yet // so... let's ignore the prim that is missing for now, and if // any other parts change, it'll re-send it all hasBeenUpdated = true; continue; } ScenePartUpdate update = m_updateTimes[part.LocalId]; if (update.LastFullUpdateTimeRequested == update.LastFullUpdateTime && update.LastTerseUpdateTime == update.LastTerseUpdateTimeRequested) continue;//Only if we haven't sent them this prim before and it hasn't changed //It's changed, check again hasBeenUpdated = true; break; } } return hasBeenUpdated; } private class DoubleComparer : IComparer<KeyValuePair<double, SceneObjectGroup>> { public int Compare(KeyValuePair<double, SceneObjectGroup> x, KeyValuePair<double, SceneObjectGroup> y) { //ensure objects with avatars on them are shown first followed by everything else if (x.Value.HasSittingAvatars && !y.Value.HasSittingAvatars) { return -1; } return x.Key.CompareTo(y.Key); } } /// <summary> /// Tests to see whether the given group can be seen by the client at the given position /// </summary> /// <param name="clientAbsPosition">Position to check from</param> /// <param name="group">Object to check</param> /// <param name="distance">The distance to the group</param> /// <returns></returns> public bool ShowEntityToClient(Vector3 clientAbsPosition, SceneObjectGroup group, out double distance) { distance = 0; if (UseCulling == false) return true; if (m_presence.DrawDistance <= 0) return (true); if (group.IsAttachedHUD) { if (group.OwnerID != m_presence.UUID) return false; // Never show attached HUDs return true; } if (group.IsAttachment) return true; if (group.HasSittingAvatars) return true;//Send objects that avatars are sitting on var box = group.BoundingBox(); float drawDistance = m_presence.DrawDistance; if (m_presence.DrawDistance < _MINIMUM_DRAW_DISTANCE) drawDistance = _MINIMUM_DRAW_DISTANCE; //Smallest distance we will check if ((distance = Vector3.DistanceSquared(clientAbsPosition, group.AbsolutePosition)) <= drawDistance * drawDistance) return (true); //If the basic check fails, we then want to check whether the object is large enough that we would // want to start doing more agressive checks if (box.Size.X >= DistanceBeforeCullingRequired || box.Size.Y >= DistanceBeforeCullingRequired || box.Size.Z >= DistanceBeforeCullingRequired) { //Any side of the box is larger than the distance that // we check for, run tests on the bounding box to see // whether it is actually needed to be sent box = group.BoundingBox(); float closestX; float closestY; float closestZ; float boxLeft = box.Center.X - box.Extent.X; float boxRight = box.Center.X + box.Extent.X; float boxFront = box.Center.Y - box.Extent.Y; float boxRear = box.Center.Y + box.Extent.Y; float boxBottom = box.Center.Z - box.Extent.Z; float boxTop = box.Center.Z + box.Extent.Z; if (clientAbsPosition.X < boxLeft) { closestX = boxLeft; } else if (clientAbsPosition.X > boxRight) { closestX = boxRight; } else { closestX = clientAbsPosition.X; } if (clientAbsPosition.Y < boxFront) { closestY = boxFront; } else if (clientAbsPosition.Y > boxRear) { closestY = boxRear; } else { closestY = clientAbsPosition.Y; } if (clientAbsPosition.Z < boxBottom) { closestZ = boxBottom; } else if (clientAbsPosition.Z > boxTop) { closestZ = boxTop; } else { closestZ = clientAbsPosition.Z; } if (Vector3.DistanceSquared(clientAbsPosition, new Vector3(closestX, closestY, closestZ)) <= drawDistance * drawDistance) return (true); } return false; } #endregion #region Prim Update Sending /// <summary> /// Send updates to the client about prims which have been placed on the update queue. We don't /// necessarily send updates for all the parts on the queue, e.g. if an updates with a more recent /// timestamp has already been sent. /// /// SHOULD ONLY BE CALLED WITHIN THE SCENE LOOP /// </summary> public void SendPrimUpdates() { if (m_presence.Closed) { ClearAllTracking(); return; } if (m_presence.IsInTransit) return; // disable prim updates during a crossing, but leave them queued for after transition if (!m_presence.IsChildAgent && !m_presence.IsFullyInRegion) return; m_perfMonMS = Environment.TickCount; if (((UseCulling == false) || (m_presence.DrawDistance != 0)) && NeedsFullSceneUpdate) { NeedsFullSceneUpdate = false; if (UseCulling == false)//Send the entire heightmap m_presence.ControllingClient.SendLayerData(m_presence.Scene.Heightmap.GetFloatsSerialised()); if (UseCulling == true && !m_presence.IsChildAgent) m_timeBeforeChildAgentUpdate = Environment.TickCount; CheckForDistantEntitiesToShow(); } if (m_timeBeforeChildAgentUpdate != 0 && (Environment.TickCount - m_timeBeforeChildAgentUpdate) >= 5000) { m_log.Debug("[SCENE VIEW]: Sending child agent update to update all child regions about fully established user"); //Send out an initial child agent update so that the child region can add their objects accordingly now that we are all set up m_presence.SendChildAgentUpdate(); //Don't ever send another child update from here again m_timeBeforeChildAgentUpdate = 0; } // Before pulling the AbsPosition, since this isn't locked, make sure it's a good position. Vector3 clientAbsPosition = Vector3.Zero; if (!m_presence.HasSafePosition(out clientAbsPosition)) return; // this one has gone into late transit or something, or the prim it's on has. int queueCount = m_partsUpdateQueue.Count; int time = Environment.TickCount; SceneObjectGroup lastSog = null; bool condition1 = false; SceneObjectPart[] lastParentGroupParts = null; while (m_partsUpdateQueue.Count > 0 && HasFinishedInitialUpdate) { if (m_presence.Closed) { ClearAllTracking(); return; } SceneObjectPart part = m_partsUpdateQueue.Dequeue(); if (part.ParentGroup == null || part.ParentGroup.IsDeleted) continue; double distance; // Cull part updates based on the position of the SOP. if ((lastSog == part.ParentGroup && condition1) || (lastSog != part.ParentGroup && UseCulling && !ShowEntityToClient(clientAbsPosition, part.ParentGroup, out distance) && !ShowEntityToClient(m_presence.CameraPosition, part.ParentGroup, out distance))) { condition1 = true; lock (m_updateTimes) { ScenePartUpdate newUpdate; if (!m_updateTimes.TryGetValue(part.LocalId, out newUpdate)) newUpdate = new ScenePartUpdate(); //Update this, so that we know to resend it later once it comes back into view newUpdate.LastFullUpdateTimeRequested = part.FullUpdateCounter; newUpdate.LastTerseUpdateTimeRequested = part.TerseUpdateCounter; m_updateTimes[part.LocalId] = newUpdate; } lastSog = part.ParentGroup; continue; } else { condition1 = false; } SceneObjectPart[] parentGroupParts = null; bool needsParentGroupParts = false; lock (m_updateTimes) { if (m_updateTimes.ContainsKey(part.ParentGroup.LocalId)) { needsParentGroupParts = true; } } if (!needsParentGroupParts) { lastParentGroupParts = null; } else if (needsParentGroupParts && lastSog == part.ParentGroup && lastParentGroupParts != null) { parentGroupParts = lastParentGroupParts; } else { parentGroupParts = part.ParentGroup.GetParts(); lastParentGroupParts = parentGroupParts; } lock (m_updateTimes) { bool hasBeenUpdated = false; if (m_updateTimes.ContainsKey(part.ParentGroup.LocalId)) { if (parentGroupParts == null) { if (lastSog == part.ParentGroup && lastParentGroupParts != null) { parentGroupParts = lastParentGroupParts; } else { parentGroupParts = part.ParentGroup.GetParts(); lastParentGroupParts = parentGroupParts; } } foreach (SceneObjectPart p in parentGroupParts) { ScenePartUpdate update; if (!m_updateTimes.TryGetValue(p.LocalId, out update)) { //Threading issue? Shouldn't happen unless this method is called // while a group is being sent, but hasn't sent all prims yet // so... let's ignore the prim that is missing for now, and if // any other parts change, it'll re-send it all hasBeenUpdated = true; break; } if (update.LastFullUpdateTimeRequested == update.LastFullUpdateTime && update.LastTerseUpdateTime == update.LastTerseUpdateTimeRequested) { continue;//Only if we haven't sent them this prim before and it hasn't changed } //It's changed, check again hasBeenUpdated = true; break; } } else { hasBeenUpdated = true; } if (hasBeenUpdated) { SendGroupUpdate(part.ParentGroup); lastSog = part.ParentGroup; continue; } } lastSog = part.ParentGroup; SendPartUpdate(part); } /*if (queueCount > 0) { m_log.DebugFormat("Update queue flush of {0} objects took {1}", queueCount, Environment.TickCount - time); }*/ //ControllingClient.FlushPrimUpdates(); m_presence.Scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS); } public void SendGroupUpdate(SceneObjectGroup sceneObjectGroup) { SendPartUpdate(sceneObjectGroup.RootPart); foreach (SceneObjectPart part in sceneObjectGroup.GetParts()) { if (!part.IsRootPart()) SendPartUpdate(part); } } public void SendPartUpdate(SceneObjectPart part) { ScenePartUpdate update = null; int partFullUpdateCounter = part.FullUpdateCounter; int partTerseUpdateCounter = part.TerseUpdateCounter; bool sendFullUpdate = false, sendFullInitialUpdate = false, sendTerseUpdate = false; lock(m_updateTimes) { if (m_updateTimes.TryGetValue(part.LocalId, out update)) { if ((update.LastFullUpdateTime != partFullUpdateCounter) || part.ParentGroup.IsAttachment) { // m_log.DebugFormat( // "[SCENE PRESENCE]: Fully updating prim {0}, {1} - part timestamp {2}", // part.Name, part.UUID, part.TimeStampFull); update.LastFullUpdateTime = partFullUpdateCounter; update.LastFullUpdateTimeRequested = partFullUpdateCounter; //also cancel any pending terses since the full covers it update.LastTerseUpdateTime = partTerseUpdateCounter; update.LastTerseUpdateTimeRequested = partTerseUpdateCounter; sendFullUpdate = true; } else if (update.LastTerseUpdateTime != partTerseUpdateCounter) { // m_log.DebugFormat( // "[SCENE PRESENCE]: Tersely updating prim {0}, {1} - part timestamp {2}", // part.Name, part.UUID, part.TimeStampTerse); update.LastTerseUpdateTime = partTerseUpdateCounter; update.LastTerseUpdateTimeRequested = partTerseUpdateCounter; sendTerseUpdate = true; } } else { //never been sent to client before so do full update ScenePartUpdate newUpdate = new ScenePartUpdate(); newUpdate.FullID = part.UUID; newUpdate.LastFullUpdateTime = partFullUpdateCounter; newUpdate.LastFullUpdateTimeRequested = partFullUpdateCounter; m_updateTimes.Add(part.LocalId, newUpdate); sendFullInitialUpdate = true; } } if (sendFullUpdate) { part.SendFullUpdate(m_presence.ControllingClient, m_presence.GenerateClientFlags(part.UUID)); } else if (sendTerseUpdate) { part.SendTerseUpdateToClient(m_presence.ControllingClient); } else if (sendFullInitialUpdate) { // Attachment handling // if (part.ParentGroup.IsAttachment) { if (part != part.ParentGroup.RootPart) return; part.ParentGroup.SendFullUpdateToClient(m_presence.ControllingClient); return; } part.SendFullUpdate(m_presence.ControllingClient, m_presence.GenerateClientFlags(part.UUID)); } } /// <summary> /// Add the part to the queue of parts for which we need to send an update to the client /// /// THIS METHOD SHOULD ONLY BE CALLED FROM WITHIN THE SCENE LOOP!! /// </summary> /// <param name="part"></param> public void QueuePartForUpdate(SceneObjectPart part) { if (m_presence.IsBot) return; // m_log.WarnFormat("[ScenePresence]: {0} Queuing update for {1} {2} {3}", part.ParentGroup.Scene.RegionInfo.RegionName, part.UUID.ToString(), part.LocalId.ToString(), part.ParentGroup.Name); m_partsUpdateQueue.Enqueue(part); } /// <summary> /// Clears all data we have about the region /// /// SHOULD ONLY BE CALLED FROM CHILDREN OF THE SCENE LOOP!! /// </summary> private void ClearAllTracking() { if (m_partsUpdateQueue.Count > 0) m_partsUpdateQueue.Clear(); lock (m_updateTimes) { if (m_updateTimes.Count > 0) m_updateTimes.Clear(); } if (m_presencesInView.Count > 0) m_presencesInView.Clear(); m_TerrainCulling = new bool[16, 16]; } /// <summary> /// Sends kill packets if the given object is within the draw distance of the avatar /// </summary> /// <param name="grp"></param> /// <param name="localIds"></param> public void SendKillObjects(SceneObjectGroup grp, List<uint> localIds) { //Only send the kill object packet if we have seen this object lock (m_updateTimes) { if (m_updateTimes.ContainsKey(grp.LocalId)) m_presence.ControllingClient.SendKillObjects(m_presence.Scene.RegionInfo.RegionHandle, localIds.ToArray()); } } #endregion #region Terrain Patch Sending /// <summary> /// Informs the SceneView that the given patch has been modified and must be resent /// </summary> /// <param name="serialised"></param> /// <param name="x"></param> /// <param name="y"></param> public void TerrainPatchUpdated(float[] serialised, int x, int y) { //Check to make sure that we only send it if we can see it or culling is disabled if ((UseCulling == false) || ShowTerrainPatchToClient(x, y)) m_presence.ControllingClient.SendLayerData(x, y, serialised); else if (UseCulling == true) m_TerrainCulling[x, y] = false;//Resend it next time it comes back into draw distance } /// <summary> /// Checks to see whether any new terrain has come into view since the last time culling checks were done /// </summary> private void CheckForDistantTerrainToShow() { const int FUDGE_FACTOR = 2; //Use a fudge factor, as we can see slightly farther than the draw distance const int MAX_PATCH = 16; int startX = Math.Min((((int)(m_presence.AbsolutePosition.X - m_presence.DrawDistance)) / Constants.TerrainPatchSize) - FUDGE_FACTOR, (((int)(m_presence.CameraPosition.X - m_presence.DrawDistance)) / Constants.TerrainPatchSize) - FUDGE_FACTOR); int startY = Math.Min((((int)(m_presence.AbsolutePosition.Y - m_presence.DrawDistance)) / Constants.TerrainPatchSize) - FUDGE_FACTOR, (((int)(m_presence.CameraPosition.Y - m_presence.DrawDistance)) / Constants.TerrainPatchSize) - FUDGE_FACTOR); int endX = Math.Max((((int)(m_presence.AbsolutePosition.X + m_presence.DrawDistance)) / Constants.TerrainPatchSize) + FUDGE_FACTOR, (((int)(m_presence.CameraPosition.X + m_presence.DrawDistance)) / Constants.TerrainPatchSize) + FUDGE_FACTOR); int endY = Math.Max((((int)(m_presence.AbsolutePosition.Y + m_presence.DrawDistance)) / Constants.TerrainPatchSize) + FUDGE_FACTOR, (((int)(m_presence.CameraPosition.Y + m_presence.DrawDistance)) / Constants.TerrainPatchSize) + FUDGE_FACTOR); float[] serializedMap = m_presence.Scene.Heightmap.GetFloatsSerialised(); if (startX < 0) startX = 0; if (startY < 0) startY = 0; if (endX > MAX_PATCH) endX = MAX_PATCH; if (endY > MAX_PATCH) endY = MAX_PATCH; for (int x = startX; x < endX; x++) { for (int y = startY; y < endY; y++) { //Need to make sure we don't send the same ones over and over if (!m_TerrainCulling[x, y]) { if (ShowTerrainPatchToClient(x, y)) { //They can see it, send it to them m_TerrainCulling[x, y] = true; m_presence.ControllingClient.SendLayerData(x, y, serializedMap); } } } } } /// <summary> /// Check to see whether a specific terrain patch is in view /// </summary> /// <param name="x">Terrain patch X</param> /// <param name="y">Terrain patch Y</param> /// <returns></returns> private bool ShowTerrainPatchToClient(int x, int y) { Vector3 clientAbsPosition = m_presence.AbsolutePosition; clientAbsPosition.Z = 0;//Force to the ground, we only want the 2D distance bool success = Util.DistanceLessThan( clientAbsPosition, new Vector3(x * Constants.TerrainPatchSize, y * Constants.TerrainPatchSize, 0), m_presence.DrawDistance + (16*2)); if (!success) { Vector3 clientCamPos = m_presence.CameraPosition; clientCamPos.Z = 0;//Force to the ground, we only want the 2D distance success = Util.DistanceLessThan( clientCamPos, new Vector3(x * Constants.TerrainPatchSize, y * Constants.TerrainPatchSize, 0), m_presence.DrawDistance + (16 * 2)); } return success; } #endregion #region Private classes public class ScenePartUpdate { public UUID FullID; public int LastFullUpdateTime; public int LastFullUpdateTimeRequested; public int LastTerseUpdateTime; public int LastTerseUpdateTimeRequested; public ScenePartUpdate() { FullID = UUID.Zero; LastFullUpdateTime = 0; LastFullUpdateTimeRequested = 0; LastTerseUpdateTime = 0; LastTerseUpdateTimeRequested = 0; } } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class FreeAI : MonoBehaviour { //THE CHARACTER COLLISION LAYER FOR TARGETS public Transform AICharacter; public int CharacterCollisionLayer=15; //ENABLES MELEE COMBAT public bool EnableCombat=true; //THE TARGET WHICH HE FOLLOWS AND ATTACKS public Transform Target; //THE VECTOR OF THE TARGET private Vector3 CurrentTarget; //TARGET VISIBIL BOOL private bool TargetVisible; private bool MoveToTarget; //SPEED WHICH THE AI TURNS public float turnspeed=5; //SPEED WHICH AI RUNS public float runspeed=4; public float Damage=10; public float AttackSpeed=1; public float AttackRange=5; //WHEN THE DAMAGE HAS BEEN DEALT private bool damdealt; //ANIMATIONS public AnimationClip RunAnimation; public AnimationClip IdleAnimation; public AnimationClip AttackAnimation; public AnimationClip DeathAnimation; private bool stop; private bool Swing; public bool IsDead; private bool DeadPlayed; private float Atimer; private bool startfollow; //PATHFINDING STUFF public bool EnableFollowNodePathFinding; public bool DebugShowPath; public float DistanceNodeChange=1.5f; public List<Vector3> Follownodes; private int curf; // Use this for initialization void Start () { if(AICharacter){} else AICharacter=transform; } // Update is called once per frame void Update () { if(IsDead){ if(DeathAnimation){ if(DeadPlayed){} else AICharacter.GetComponent<Animation>().CrossFade( DeathAnimation.name, 0.1f); DeadPlayed=true; } } else{ //COMBAT BEHAVE if(Target){ float Tdist=Vector3.Distance(Target.position, transform.position); if(Tdist<=AttackRange){ if(TargetVisible)stop=true; } else stop=false; //RAYCAST VISION SYSTEM RaycastHit hit = new RaycastHit(); LayerMask lay=CharacterCollisionLayer; Vector3 pdir = (Target.transform.position - transform.position).normalized; float playerdirection = Vector3.Dot(pdir, transform.forward); if(Physics.Linecast(transform.position, Target.position, out hit, lay)){ TargetVisible=false; } else{ if(playerdirection > 0){ startfollow=true; TargetVisible=true; } //TargetVisible=false; } } //IF THE TARGET IS VISIBLE if(TargetVisible){ CurrentTarget=Target.position; MoveToTarget=true; } //MOVES/RUNS TO TARGET if(MoveToTarget){ if(stop){} else{ transform.position += transform.forward * +runspeed * Time.deltaTime; } if(RunAnimation){ if(stop){ //COMBAT! if(EnableCombat){ Health hp=(Health)Target.transform.GetComponent("Health"); if(hp.CurrentHealth>0){ Atimer+=Time.deltaTime; AICharacter.GetComponent<Animation>()[AttackAnimation.name].speed = AICharacter.GetComponent<Animation>()[AttackAnimation.name].length / AttackSpeed; AICharacter.GetComponent<Animation>().CrossFade( AttackAnimation.name, 0.12f); if(damdealt){} else{ if(Atimer>=AttackSpeed*0.35&Atimer<=AttackSpeed*0.45){ //LETS DO SOME DAMAGE! if(hp){ hp.CurrentHealth=hp.CurrentHealth-Damage; damdealt=true; } } } if(Atimer>=AttackSpeed){ damdealt=false; Atimer=0; } } else AICharacter.GetComponent<Animation>().CrossFade( IdleAnimation.name, 0.12f); } else AICharacter.GetComponent<Animation>().CrossFade( IdleAnimation.name, 0.12f); } else{ Atimer=0; AICharacter.GetComponent<Animation>().CrossFade( RunAnimation.name, 0.12f); } } } else{ if(IdleAnimation){ AICharacter.GetComponent<Animation>().CrossFade( IdleAnimation.name, 0.12f); } } //FOLLOW PATHFINDING if(TargetVisible){} else{ if(EnableFollowNodePathFinding&startfollow){ if(Follownodes.Count<=0)Follownodes.Add(CurrentTarget); RaycastHit hit = new RaycastHit(); LayerMask lay=CharacterCollisionLayer; if(Physics.Linecast(Follownodes[Follownodes.Count-1], Target.position, out hit, lay)){ Follownodes.Add(Target.position); } float dist=Vector3.Distance(transform.position, Follownodes[0]); if(dist<DistanceNodeChange){ Follownodes.Remove(Follownodes[0]); } } } } if(TargetVisible&Follownodes.Count>0){ Follownodes.Clear(); } if(DebugShowPath){ if(Follownodes.Count>0){ int listsize=Follownodes.Count; Debug.DrawLine(Follownodes[0], transform.position, Color.green); for (int i = 0; i < listsize; i++) if(i<Follownodes.Count-1){ { Debug.DrawLine(Follownodes[i], Follownodes[i+1], Color.green); } } } //POINT AT TARGET if(MoveToTarget){ if(Follownodes.Count>0){ transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Follownodes[0] - transform.position), turnspeed * Time.deltaTime); } else{ transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(CurrentTarget - transform.position), turnspeed * Time.deltaTime); } } transform.eulerAngles = new Vector3(0,transform.eulerAngles.y,0); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Globalization { // Modern Persian calendar is a solar observation based calendar. Each new year begins on the day when the vernal equinox occurs before noon. // The epoch is the date of the vernal equinox prior to the epoch of the Islamic calendar (March 19, 622 Julian or March 22, 622 Gregorian) // There is no Persian year 0. Ordinary years have 365 days. Leap years have 366 days with the last month (Esfand) gaining the extra day. /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 0622/03/22 9999/12/31 ** Persian 0001/01/01 9378/10/13 */ public class PersianCalendar : Calendar { public static readonly int PersianEra = 1; internal static long PersianEpoch = new DateTime(622, 3, 22).Ticks / GregorianCalendar.TicksPerDay; private const int ApproximateHalfYear = 180; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; internal const int MonthsPerYear = 12; internal static int[] DaysToMonth = { 0, 31, 62, 93, 124, 155, 186, 216, 246, 276, 306, 336, 366 }; internal const int MaxCalendarYear = 9378; internal const int MaxCalendarMonth = 10; internal const int MaxCalendarDay = 13; // Persian calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 3, day: 22) // This is the minimal Gregorian date that we support in the PersianCalendar. internal static DateTime minDate = new DateTime(622, 3, 22); internal static DateTime maxDate = DateTime.MaxValue; public override DateTime MinSupportedDateTime { get { return (minDate); } } public override DateTime MaxSupportedDateTime { get { return (maxDate); } } public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } // Construct an instance of Persian calendar. public PersianCalendar() { } internal override CalendarId BaseCalendarID { get { return CalendarId.GREGORIAN; } } internal override CalendarId ID { get { return CalendarId.PERSIAN; } } /*=================================GetAbsoluteDatePersian========================== **Action: Gets the Absolute date for the given Persian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: **Arguments: **Exceptions: ============================================================================*/ private long GetAbsoluteDatePersian(int year, int month, int day) { if (year >= 1 && year <= MaxCalendarYear && month >= 1 && month <= 12) { int ordinalDay = DaysInPreviousMonths(month) + day - 1; // day is one based, make 0 based since this will be the number of days we add to beginning of year below int approximateDaysFromEpochForYearStart = (int)(CalendricalCalculationsHelper.MeanTropicalYearInDays * (year - 1)); long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(PersianEpoch + approximateDaysFromEpochForYearStart + ApproximateHalfYear); yearStart += ordinalDay; return yearStart; } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } internal static void CheckTicksRange(long ticks) { if (ticks < minDate.Ticks || ticks > maxDate.Ticks) { throw new ArgumentOutOfRangeException( "time", String.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, minDate, maxDate)); } } internal static void CheckEraRange(int era) { if (era != CurrentEra && era != PersianEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } } internal static void CheckYearRange(int year, int era) { CheckEraRange(era); if (year < 1 || year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxCalendarYear)); } } internal static void CheckYearMonthRange(int year, int month, int era) { CheckYearRange(year, era); if (year == MaxCalendarYear) { if (month > MaxCalendarMonth) { throw new ArgumentOutOfRangeException( nameof(month), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxCalendarMonth)); } } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month); } } private static int MonthFromOrdinalDay(int ordinalDay) { Debug.Assert(ordinalDay <= 366); int index = 0; while (ordinalDay > DaysToMonth[index]) index++; return index; } private static int DaysInPreviousMonths(int month) { Debug.Assert(1 <= month && month <= 12); --month; // months are one based but for calculations use 0 based return DaysToMonth[month]; } /*=================================GetDatePart========================== **Action: Returns a given date part of this <i>DateTime</i>. This method is used ** to compute the year, day-of-year, month, or day part. **Returns: **Arguments: **Exceptions: ArgumentException if part is incorrect. ============================================================================*/ internal int GetDatePart(long ticks, int part) { long NumDays; // The calculation buffer in number of days. CheckTicksRange(ticks); // // Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D. // 1/1/0001 is absolute date 1. // NumDays = ticks / GregorianCalendar.TicksPerDay + 1; // // Calculate the appromixate Persian Year. // long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays); int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1; Debug.Assert(y >= 1); if (part == DatePartYear) { return y; } // // Calculate the Persian Month. // int ordinalDay = (int)(NumDays - CalendricalCalculationsHelper.GetNumberOfDays(this.ToDateTime(y, 1, 1, 0, 0, 0, 0, 1))); if (part == DatePartDayOfYear) { return ordinalDay; } int m = MonthFromOrdinalDay(ordinalDay); Debug.Assert(ordinalDay >= 1); Debug.Assert(m >= 1 && m <= 12); if (part == DatePartMonth) { return m; } int d = ordinalDay - DaysInPreviousMonths(m); Debug.Assert(1 <= d); Debug.Assert(d <= 31); // // Calculate the Persian Day. // if (part == DatePartDay) { return (d); } // Incorrect part value. throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, 120000)); } // Get the date in Persian calendar. int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int days = GetDaysInMonth(y, m); if (d > days) { d = days; } long ticks = GetAbsoluteDatePersian(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); if ((month == MaxCalendarMonth) && (year == MaxCalendarYear)) { return MaxCalendarDay; } int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1]; if ((month == MonthsPerYear) && !IsLeapYear(year)) { Debug.Assert(daysInMonth == 30); --daysInMonth; } return daysInMonth; } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { CheckYearRange(year, era); if (year == MaxCalendarYear) { return DaysToMonth[MaxCalendarMonth - 1] + MaxCalendarDay; } // Common years have 365 days. Leap years have 366 days. return (IsLeapYear(year, CurrentEra) ? 366 : 365); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { CheckTicksRange(time.Ticks); return (PersianEra); } public override int[] Eras { get { return (new int[] { PersianEra }); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { CheckYearRange(year, era); if (year == MaxCalendarYear) { return MaxCalendarMonth; } return (12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and MaxCalendarYear. // public override int GetYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartYear)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { // The year/month/era value checking is done in GetDaysInMonth(). int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( nameof(day), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, month)); } return (IsLeapYear(year, era) && month == 12 && day == 30); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { CheckYearRange(year, era); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { CheckYearRange(year, era); if (year == MaxCalendarYear) { return false; } return (GetAbsoluteDatePersian(year + 1, 1, 1) - GetAbsoluteDatePersian(year, 1, 1)) == 366; } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { // The year/month/era checking is done in GetDaysInMonth(). int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( nameof(day), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, month)); } long lDate = GetAbsoluteDatePersian(year, month, day); if (lDate >= 0) { return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond))); } else { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1410; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > MaxCalendarYear) { throw new ArgumentOutOfRangeException( nameof(value), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, MaxCalendarYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } if (year < 100) { return (base.ToFourDigitYear(year)); } if (year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxCalendarYear)); } return (year); } } }
// 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. /************************************************************** /* a basic test case for GC with cyclic Double linked list leaks. /* Creat a DoubLink object which is a cyclic Double linked list /* object with iObj number node. then deletes its reference when /* the next object is created. Do this loop iRep times. /**************************************************************/ namespace DoubLink { using System; using System.Runtime.CompilerServices; public class DoubLinkGen { // disabling unused variable warning #pragma warning disable 0414 internal DoubLink Mv_Doub; #pragma warning restore 0414 public static int Main(System.String [] Args) { int iRep = 0; int iObj = 0; Console.WriteLine("Test should return with ExitCode 100 ..."); switch( Args.Length ) { case 1: if (!Int32.TryParse( Args[0], out iRep )) { iRep = 100; } break; case 2: if (!Int32.TryParse( Args[0], out iRep )) { iRep = 100; } if (!Int32.TryParse( Args[1], out iObj )) { iObj = 10; } break; default: iRep = 100; iObj = 10; break; } DoubLinkGen Mv_Leak = new DoubLinkGen(); if(Mv_Leak.runTest(iRep, iObj )) { Console.WriteLine("Test Passed"); return 100; } Console.WriteLine("Test Failed"); return 1; } [MethodImpl(MethodImplOptions.NoInlining)] public bool DrainFinalizerQueue(int iRep, int iObj) { int lastValue = DLinkNode.FinalCount; while (true) { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); if (DLinkNode.FinalCount == iRep * iObj) { return true; } if (DLinkNode.FinalCount != lastValue) { Console.WriteLine(" Performing Collect/Wait/Collect cycle again"); lastValue = DLinkNode.FinalCount; continue; } Console.WriteLine(" Finalized number stable at " + lastValue); return false; } } public bool runTest(int iRep, int iObj) { SetLink(iRep, iObj); Mv_Doub = null; bool success = false; if (DrainFinalizerQueue(iRep, iObj)) { success = true; } Console.Write(DLinkNode.FinalCount); Console.WriteLine(" DLinkNodes finalized"); return success; } public void SetLink(int iRep, int iObj) { for(int i=0; i<iRep; i++) { Mv_Doub = new DoubLink(iObj); } } } public class DoubLink { internal DLinkNode[] Mv_DLink; public DoubLink(int Num) : this(Num, false) { } public DoubLink(int Num, bool large) { Mv_DLink = new DLinkNode[Num]; if (Num == 0) { return; } if (Num == 1) { // only one element Mv_DLink[0] = new DLinkNode((large ? 250 : 1), Mv_DLink[0], Mv_DLink[0]); return; } // first element Mv_DLink[0] = new DLinkNode((large ? 250 : 1), Mv_DLink[Num - 1], Mv_DLink[1]); // all elements in between for (int i = 1; i < Num - 1; i++) { Mv_DLink[i] = new DLinkNode((large ? 250 : i + 1), Mv_DLink[i - 1], Mv_DLink[i + 1]); } // last element Mv_DLink[Num - 1] = new DLinkNode((large ? 250 : Num), Mv_DLink[Num - 2], Mv_DLink[0]); } public int NodeNum { get { return Mv_DLink.Length; } } public DLinkNode this[int index] { get { return Mv_DLink[index]; } set { Mv_DLink[index] = value; } } } public class DLinkNode { // disabling unused variable warning #pragma warning disable 0414 internal DLinkNode Last; internal DLinkNode Next; internal int[] Size; #pragma warning restore 0414 public static int FinalCount = 0; public DLinkNode(int SizeNum, DLinkNode LastObject, DLinkNode NextObject) { Last = LastObject; Next = NextObject; Size = new int[SizeNum * 1024]; } ~DLinkNode() { FinalCount++; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Supersim.V1 { /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Create a Fleet /// </summary> public class CreateFleetOptions : IOptions<FleetResource> { /// <summary> /// The SID or unique name of the Network Access Profile of the Fleet /// </summary> public string NetworkAccessProfile { get; } /// <summary> /// An application-defined string that uniquely identifies the resource /// </summary> public string UniqueName { get; set; } /// <summary> /// Defines whether SIMs in the Fleet are capable of using data connectivity /// </summary> public bool? DataEnabled { get; set; } /// <summary> /// The total data usage (download and upload combined) in Megabytes that each Sim resource assigned to the Fleet resource can consume /// </summary> public int? DataLimit { get; set; } /// <summary> /// Deprecated /// </summary> public bool? CommandsEnabled { get; set; } /// <summary> /// Deprecated /// </summary> public Uri CommandsUrl { get; set; } /// <summary> /// Deprecated /// </summary> public Twilio.Http.HttpMethod CommandsMethod { get; set; } /// <summary> /// The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device /// </summary> public Uri IpCommandsUrl { get; set; } /// <summary> /// A string representing the HTTP method to use when making a request to `ip_commands_url` /// </summary> public Twilio.Http.HttpMethod IpCommandsMethod { get; set; } /// <summary> /// Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands /// </summary> public bool? SmsCommandsEnabled { get; set; } /// <summary> /// The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number /// </summary> public Uri SmsCommandsUrl { get; set; } /// <summary> /// A string representing the HTTP method to use when making a request to `sms_commands_url` /// </summary> public Twilio.Http.HttpMethod SmsCommandsMethod { get; set; } /// <summary> /// Construct a new CreateFleetOptions /// </summary> /// <param name="networkAccessProfile"> The SID or unique name of the Network Access Profile of the Fleet </param> public CreateFleetOptions(string networkAccessProfile) { NetworkAccessProfile = networkAccessProfile; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (NetworkAccessProfile != null) { p.Add(new KeyValuePair<string, string>("NetworkAccessProfile", NetworkAccessProfile.ToString())); } if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } if (DataEnabled != null) { p.Add(new KeyValuePair<string, string>("DataEnabled", DataEnabled.Value.ToString().ToLower())); } if (DataLimit != null) { p.Add(new KeyValuePair<string, string>("DataLimit", DataLimit.ToString())); } if (CommandsEnabled != null) { p.Add(new KeyValuePair<string, string>("CommandsEnabled", CommandsEnabled.Value.ToString().ToLower())); } if (CommandsUrl != null) { p.Add(new KeyValuePair<string, string>("CommandsUrl", Serializers.Url(CommandsUrl))); } if (CommandsMethod != null) { p.Add(new KeyValuePair<string, string>("CommandsMethod", CommandsMethod.ToString())); } if (IpCommandsUrl != null) { p.Add(new KeyValuePair<string, string>("IpCommandsUrl", Serializers.Url(IpCommandsUrl))); } if (IpCommandsMethod != null) { p.Add(new KeyValuePair<string, string>("IpCommandsMethod", IpCommandsMethod.ToString())); } if (SmsCommandsEnabled != null) { p.Add(new KeyValuePair<string, string>("SmsCommandsEnabled", SmsCommandsEnabled.Value.ToString().ToLower())); } if (SmsCommandsUrl != null) { p.Add(new KeyValuePair<string, string>("SmsCommandsUrl", Serializers.Url(SmsCommandsUrl))); } if (SmsCommandsMethod != null) { p.Add(new KeyValuePair<string, string>("SmsCommandsMethod", SmsCommandsMethod.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Fetch a Fleet instance from your account. /// </summary> public class FetchFleetOptions : IOptions<FleetResource> { /// <summary> /// The SID that identifies the resource to fetch /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchFleetOptions /// </summary> /// <param name="pathSid"> The SID that identifies the resource to fetch </param> public FetchFleetOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Retrieve a list of Fleets from your account. /// </summary> public class ReadFleetOptions : ReadOptions<FleetResource> { /// <summary> /// The SID or unique name of the Network Access Profile of the Fleet /// </summary> public string NetworkAccessProfile { get; set; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (NetworkAccessProfile != null) { p.Add(new KeyValuePair<string, string>("NetworkAccessProfile", NetworkAccessProfile.ToString())); } if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Updates the given properties of a Super SIM Fleet instance from your account. /// </summary> public class UpdateFleetOptions : IOptions<FleetResource> { /// <summary> /// The SID that identifies the resource to update /// </summary> public string PathSid { get; } /// <summary> /// An application-defined string that uniquely identifies the resource /// </summary> public string UniqueName { get; set; } /// <summary> /// The SID or unique name of the Network Access Profile of the Fleet /// </summary> public string NetworkAccessProfile { get; set; } /// <summary> /// Deprecated /// </summary> public Uri CommandsUrl { get; set; } /// <summary> /// Deprecated /// </summary> public Twilio.Http.HttpMethod CommandsMethod { get; set; } /// <summary> /// The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device /// </summary> public Uri IpCommandsUrl { get; set; } /// <summary> /// A string representing the HTTP method to use when making a request to `ip_commands_url` /// </summary> public Twilio.Http.HttpMethod IpCommandsMethod { get; set; } /// <summary> /// The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number /// </summary> public Uri SmsCommandsUrl { get; set; } /// <summary> /// A string representing the HTTP method to use when making a request to `sms_commands_url` /// </summary> public Twilio.Http.HttpMethod SmsCommandsMethod { get; set; } /// <summary> /// Construct a new UpdateFleetOptions /// </summary> /// <param name="pathSid"> The SID that identifies the resource to update </param> public UpdateFleetOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } if (NetworkAccessProfile != null) { p.Add(new KeyValuePair<string, string>("NetworkAccessProfile", NetworkAccessProfile.ToString())); } if (CommandsUrl != null) { p.Add(new KeyValuePair<string, string>("CommandsUrl", Serializers.Url(CommandsUrl))); } if (CommandsMethod != null) { p.Add(new KeyValuePair<string, string>("CommandsMethod", CommandsMethod.ToString())); } if (IpCommandsUrl != null) { p.Add(new KeyValuePair<string, string>("IpCommandsUrl", Serializers.Url(IpCommandsUrl))); } if (IpCommandsMethod != null) { p.Add(new KeyValuePair<string, string>("IpCommandsMethod", IpCommandsMethod.ToString())); } if (SmsCommandsUrl != null) { p.Add(new KeyValuePair<string, string>("SmsCommandsUrl", Serializers.Url(SmsCommandsUrl))); } if (SmsCommandsMethod != null) { p.Add(new KeyValuePair<string, string>("SmsCommandsMethod", SmsCommandsMethod.ToString())); } return p; } } }
#region BSD License /* Copyright (c) 2010, NETFx All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Clarius Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using Microsoft.CSharp.RuntimeBinder; namespace System.Dynamic { /// <summary> /// Provides reflection-based dynamic syntax for objects and types. /// This class provides the extension methods <see cref="AsDynamicReflection(object)"/> /// and <see cref="AsDynamicReflection(Type)"/> as entry points. /// </summary> /// <nuget id="netfx-System.Dynamic.Reflection" /> internal static partial class DynamicReflection { /// <summary> /// Provides dynamic syntax for accessing the given object members. /// </summary> /// <nuget id="netfx-System.Dynamic.Reflection" /> /// <param name="obj" this="true">The object to access dinamically</param> public static dynamic AsDynamicReflection(this object obj) { if (obj == null) return null; return new DynamicReflectionObject(obj); } /// <summary> /// Provides dynamic syntax for accessing the given type members. /// </summary> /// <nuget id="netfx-System.Dynamic.Reflection" /> /// <param name="type" this="true">The type to access dinamically</param> public static dynamic AsDynamicReflection(this Type type) { if (type == null) return null; return new DynamicReflectionObject(type); } /// <summary> /// Converts the type to a <see cref="TypeParameter"/> that /// the reflection dynamic must use to make a generic /// method invocation. /// </summary> /// <nuget id="netfx-System.Dynamic.Reflection" /> /// <param name="type" this="true">The type to convert</param> public static TypeParameter AsGenericTypeParameter(this Type type) { return new TypeParameter(type); } private class DynamicReflectionObject : DynamicObject { private static readonly BindingFlags s_flags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; private static readonly MethodInfo s_castMethod = typeof(DynamicReflectionObject).GetMethod("Cast", BindingFlags.Static | BindingFlags.NonPublic); private object _target; private Type _targetType; public DynamicReflectionObject(object target) { _target = target; _targetType = target.GetType(); } public DynamicReflectionObject(Type type) { _target = null; _targetType = type; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (!base.TryInvokeMember(binder, args, out result)) { var memberName = (binder.Name == "ctor" || binder.Name == "cctor") ? "." + binder.Name : binder.Name; var method = FindBestMatch(binder, memberName, args); if (method != null) { if (binder.Name == "ctor") { var instance = _target; if (instance == null) instance = FormatterServices.GetSafeUninitializedObject(_targetType); result = Invoke(method, instance, args); result = instance.AsDynamicReflection(); } else { result = AsDynamicIfNecessary(Invoke(method, _target, args)); } return true; } } result = default(object); return false; } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!base.TryGetMember(binder, out result)) { var field = _targetType.GetField(binder.Name, s_flags); var baseType = _targetType.BaseType; while (field == null && baseType != null) { field = baseType.GetField(binder.Name, s_flags); baseType = baseType.BaseType; } if (field != null) { result = AsDynamicIfNecessary(field.GetValue(_target)); return true; } var getter = FindBestMatch(binder, "get_" + binder.Name, new object[0]); if (getter != null) { result = AsDynamicIfNecessary(getter.Invoke(_target, null)); return true; } } // \o/ If nothing else works, and the member is "target", return our target. if (binder.Name == "target") { result = _target; return true; } result = default(object); return false; } public override bool TrySetMember(SetMemberBinder binder, object value) { if (!base.TrySetMember(binder, value)) { var field = _targetType.GetField(binder.Name, s_flags); var baseType = _targetType.BaseType; while (field == null && baseType != null) { field = baseType.GetField(binder.Name, s_flags); baseType = baseType.BaseType; } if (field != null) { field.SetValue(_target, value); return true; } var setter = FindBestMatch(binder, "set_" + binder.Name, new[] { value }); if (setter != null) { setter.Invoke(_target, new[] { value }); return true; } } return false; } public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { if (!base.TryGetIndex(binder, indexes, out result)) { var indexer = FindBestMatch(binder, "get_Item", indexes); if (indexer != null) { result = AsDynamicIfNecessary(indexer.Invoke(_target, indexes)); return true; } } result = default(object); return false; } public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) { if (!base.TrySetIndex(binder, indexes, value)) { var args = indexes.Concat(new[] { value }).ToArray(); var indexer = FindBestMatch(binder, "set_Item", args); if (indexer != null) { indexer.Invoke(_target, args); return true; } } return false; } public override bool TryConvert(ConvertBinder binder, out object result) { try { result = s_castMethod.MakeGenericMethod(binder.Type).Invoke(null, new[] { _target }); return true; } catch (Exception) { } var convertible = _target as IConvertible; if (convertible != null) { try { result = Convert.ChangeType(convertible, binder.Type); return true; } catch (Exception) { } } result = default(object); return false; } private static object Invoke(IInvocable method, object instance, object[] args) { var finalArgs = args.Where(x => !(x is TypeParameter)).Select(UnboxDynamic).ToArray(); var refArgs = new Dictionary<int, RefValue>(); var outArgs = new Dictionary<int, OutValue>(); for (int i = 0; i < method.Parameters.Count; i++) { if (method.Parameters[i].ParameterType.IsByRef) { var refArg = finalArgs[i] as RefValue; var outArg = finalArgs[i] as OutValue; if (refArg != null) refArgs[i] = refArg; else if (outArg != null) outArgs[i] = outArg; } } foreach (var refArg in refArgs) { finalArgs[refArg.Key] = refArg.Value.Value; } foreach (var outArg in outArgs) { finalArgs[outArg.Key] = null; } var result = method.Invoke(instance, finalArgs); foreach (var refArg in refArgs) { refArg.Value.Value = finalArgs[refArg.Key]; } foreach (var outArg in outArgs) { outArg.Value.Value = finalArgs[outArg.Key]; } return result; } /// <summary> /// Converts dynamic objects to object, which may cause unboxing /// of the wrapped dynamic such as in our own DynamicReflectionObject type. /// </summary> private static object UnboxDynamic(object maybeDynamic) { var dyn = maybeDynamic as DynamicObject; if (dyn == null) return maybeDynamic; var binder = (ConvertBinder)Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.ConvertExplicit, typeof(object), typeof(DynamicReflectionObject)); //var site = CallSite<Func<CallSite, object, object>>.Create(binder); object result; dyn.TryConvert(binder, out result); return result; } private IInvocable FindBestMatch(DynamicMetaObjectBinder binder, string memberName, object[] args) { var finalArgs = args.Where(x => !(x is TypeParameter)).Select(UnboxDynamic).ToArray(); var genericTypeArgs = new List<Type>(); if (binder is InvokeBinder || binder is InvokeMemberBinder) { IEnumerable typeArgs = binder.AsDynamicReflection().TypeArguments; genericTypeArgs.AddRange(typeArgs.Cast<Type>()); genericTypeArgs.AddRange(args.OfType<TypeParameter>().Select(x => x.Type)); } var method = FindBestMatch(binder, finalArgs, genericTypeArgs, _targetType .GetMethods(s_flags) .Where(x => x.Name == memberName && x.GetParameters().Length == finalArgs.Length) .Select(x => new MethodInvocable(x))); if (method == null) { // Fallback to explicitly implemented members. method = FindBestMatch(binder, finalArgs, genericTypeArgs, _targetType .GetInterfaces() .SelectMany( iface => _targetType .GetInterfaceMap(iface) .TargetMethods.Select(x => new { Interface = iface, Method = x })) .Where(x => x.Method.GetParameters().Length == finalArgs.Length && x.Method.Name.Replace(x.Interface.FullName.Replace('+', '.') + ".", "") == memberName) .Select(x => (IInvocable)new MethodInvocable(x.Method)) .Concat(_targetType.GetConstructors(s_flags) .Where(x => x.Name == memberName && x.GetParameters().Length == finalArgs.Length) .Select(x => new ConstructorInvocable(x))) .Distinct()); } var methodInvocable = method as MethodInvocable; if (method != null && methodInvocable != null && methodInvocable.Method.IsGenericMethodDefinition) { method = new MethodInvocable(methodInvocable.Method.MakeGenericMethod(genericTypeArgs.ToArray())); } return method; } private IInvocable FindBestMatch(DynamicMetaObjectBinder binder, object[] args, List<Type> genericArgs, IEnumerable<IInvocable> candidates) { var result = FindBestMatchImpl(binder, args, genericArgs, candidates, MatchingStyle.ExactType); if (result == null) result = FindBestMatchImpl(binder, args, genericArgs, candidates, MatchingStyle.AssignableFrom); if (result == null) result = FindBestMatchImpl(binder, args, genericArgs, candidates, MatchingStyle.ExactTypeGenericHint); if (result == null) result = FindBestMatchImpl(binder, args, genericArgs, candidates, MatchingStyle.AssignableFromGenericHint); return result; } /// <summary> /// Finds the best match among the candidates. /// </summary> /// <param name="binder">The binder that is requesting the match.</param> /// <param name="args">The args passed in to the invocation.</param> /// <param name="genericArgs">The generic args if any.</param> /// <param name="candidates">The candidate methods to use for the match..</param> /// <param name="matching">if set to <c>MatchingStyle.AssignableFrom</c>, uses a more lax matching approach for arguments, with IsAssignableFrom instead of == for arg type, /// and <c>MatchingStyle.GenericTypeHint</c> tries to use the generic arguments as type hints if they match the # of args.</param> private IInvocable FindBestMatchImpl(DynamicMetaObjectBinder binder, object[] args, List<Type> genericArgs, IEnumerable<IInvocable> candidates, MatchingStyle matching) { dynamic dynamicBinder = binder.AsDynamicReflection(); for (int i = 0; i < args.Length; i++) { var index = i; if (args[index] != null) { switch (matching) { case MatchingStyle.ExactType: candidates = candidates.Where(x => x.Parameters[index].ParameterType.IsAssignableFrom(GetArgumentType(args[index]))); break; case MatchingStyle.AssignableFrom: candidates = candidates.Where(x => x.Parameters[index].ParameterType.IsEquivalentTo(GetArgumentType(args[index]))); break; case MatchingStyle.ExactTypeGenericHint: candidates = candidates.Where(x => x.Parameters.Count == genericArgs.Count && x.Parameters[index].ParameterType.IsEquivalentTo(genericArgs[index])); break; case MatchingStyle.AssignableFromGenericHint: candidates = candidates.Where(x => x.Parameters.Count == genericArgs.Count && x.Parameters[index].ParameterType.IsAssignableFrom(genericArgs[index])); break; default: break; } } IEnumerable enumerable = dynamicBinder.ArgumentInfo; // The binder has the extra argument info for the "this" parameter at the beginning. if (enumerable.Cast<object>().ToList()[index + 1].AsDynamicReflection().IsByRef) candidates = candidates.Where(x => x.Parameters[index].ParameterType.IsByRef); // Only filter by matching generic argument count if the generics isn't being used as parameter type hints. if (genericArgs.Count > 0 && matching != MatchingStyle.AssignableFromGenericHint && matching != MatchingStyle.ExactTypeGenericHint) candidates = candidates.Where(x => x.IsGeneric && x.GenericParameters == genericArgs.Count); } return candidates.FirstOrDefault(); } private static Type GetArgumentType(object arg) { if (arg is RefValue || arg is OutValue) return arg.GetType().GetGenericArguments()[0].MakeByRefType(); if (arg is DynamicReflectionObject) return ((DynamicReflectionObject)arg)._target.GetType(); return arg.GetType(); } private object AsDynamicIfNecessary(object value) { if (value == null) return value; var type = value.GetType(); if (type.IsClass && type != typeof(string)) return value.AsDynamicReflection(); return value; } private static T Cast<T>(object target) { return (T)target; } private enum MatchingStyle { ExactType, AssignableFrom, ExactTypeGenericHint, AssignableFromGenericHint, } private interface IInvocable { bool IsGeneric { get; } int GenericParameters { get; } IList<ParameterInfo> Parameters { get; } object Invoke(object obj, object[] parameters); } private class MethodInvocable : IInvocable { private MethodInfo _method; private Lazy<IList<ParameterInfo>> _parameters; public MethodInvocable(MethodInfo method) { _method = method; _parameters = new Lazy<IList<ParameterInfo>>(() => _method.GetParameters()); } public object Invoke(object obj, object[] parameters) { return _method.Invoke(obj, parameters); } public IList<ParameterInfo> Parameters { get { return _parameters.Value; } } public MethodInfo Method { get { return _method; } } public bool IsGeneric { get { return _method.IsGenericMethodDefinition; } } public int GenericParameters { get { return _method.GetGenericArguments().Length; } } } private class ConstructorInvocable : IInvocable { private ConstructorInfo _ctor; private Lazy<IList<ParameterInfo>> _parameters; public ConstructorInvocable(ConstructorInfo ctor) { _ctor = ctor; _parameters = new Lazy<IList<ParameterInfo>>(() => _ctor.GetParameters()); } public object Invoke(object obj, object[] parameters) { return _ctor.Invoke(obj, parameters); } public IList<ParameterInfo> Parameters { get { return _parameters.Value; } } public bool IsGeneric { get { return false; } } public int GenericParameters { get { return 0; } } } } } }
// // Copyright (C) 2010 Jackson Harper ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Manos.Caching; using Manos.Http; using Manos.IO; using Manos.Logging; namespace Manos { /// <summary> /// The app runner. This is where the magic happens. /// </summary> public static class AppHost { private static ManosApp app; private static bool started; private static readonly List<IPEndPoint> listenEndPoints = new List<IPEndPoint>(); private static readonly Dictionary<IPEndPoint, Tuple<string, string>> secureListenEndPoints = new Dictionary<IPEndPoint, Tuple<string, string>>(); private static readonly List<HttpServer> servers = new List<HttpServer>(); private static IManosCache cache; private static IManosLogger log; private static List<IManosPipe> pipes; private static readonly Context context; static AppHost() { context = Context.Create(); } public static ManosApp App { get { return app; } } public static IManosCache Cache { get { if (cache == null) cache = new ManosInProcCache(); return cache; } } public static IManosLogger Log { get { if (log == null) log = new ManosConsoleLogger("manos", LogLevel.Debug); return log; } } public static Context Context { get { return context; } } public static IList<IManosPipe> Pipes { get { return pipes; } } public static ICollection<IPEndPoint> ListenEndPoints { get { return listenEndPoints.AsReadOnly(); } } public static void ListenAt(IPEndPoint endPoint) { if (endPoint == null) throw new ArgumentNullException("endPoint"); if (listenEndPoints.Contains(endPoint) || secureListenEndPoints.ContainsKey(endPoint)) throw new InvalidOperationException("Endpoint already registered"); listenEndPoints.Add(endPoint); } public static void SecureListenAt(IPEndPoint endPoint, string cert, string key) { if (endPoint == null) throw new ArgumentNullException("endPoint"); if (cert == null) throw new ArgumentNullException("cert"); if (key == null) throw new ArgumentNullException("key"); if (secureListenEndPoints.ContainsKey(endPoint) || listenEndPoints.Contains(endPoint)) throw new InvalidOperationException("Endpoint already registered"); secureListenEndPoints.Add(endPoint, Tuple.Create(cert, key)); } public static void InitializeTLS(string priorities) { #if !DISABLETLS manos_tls_global_init(priorities); RegenerateDHParams(1024); #endif } public static void RegenerateDHParams(int bits) { #if !DISABLETLS manos_tls_regenerate_dhparams(bits); #endif } #if !DISABLETLS [DllImport("libmanos", CallingConvention = CallingConvention.Cdecl)] private static extern int manos_tls_global_init(string priorities); [DllImport("libmanos", CallingConvention = CallingConvention.Cdecl)] private static extern int manos_tls_regenerate_dhparams(int bits); #endif public static void Start(ManosApp application) { if (application == null) throw new ArgumentNullException("application"); app = application; app.StartInternal(); started = true; foreach (IPEndPoint ep in listenEndPoints) { var server = new HttpServer(Context, HandleTransaction, Context.CreateTcpServerSocket(ep.AddressFamily)); server.Listen(ep.Address.ToString(), ep.Port); servers.Add(server); } foreach (IPEndPoint ep in secureListenEndPoints.Keys) { // var keypair = secureListenEndPoints [ep]; // var socket = Context.CreateSecureSocket (keypair.Item1, keypair.Item2); // var server = new HttpServer (context, HandleTransaction, socket); // server.Listen (ep.Address.ToString (), ep.Port); // // servers.Add (server); } context.Start(); } public static void Stop() { context.Stop(); } public static void HandleTransaction(IHttpTransaction con) { app.HandleTransaction(app, con); } public static void AddPipe(IManosPipe pipe) { if (pipes == null) pipes = new List<IManosPipe>(); pipes.Add(pipe); } public static Timeout AddTimeout(TimeSpan timespan, IRepeatBehavior repeat, object data, TimeoutCallback callback) { return AddTimeout(timespan, timespan, repeat, data, callback); } public static Timeout AddTimeout(TimeSpan begin, TimeSpan timespan, IRepeatBehavior repeat, object data, TimeoutCallback callback) { var t = new Timeout(begin, timespan, repeat, data, callback); ITimerWatcher timer = null; timer = context.CreateTimerWatcher(begin, timespan, delegate { t.Run(app); if (!t.ShouldContinueToRepeat()) { t.Stop(); timer.Dispose(); } }); timer.Start(); return t; } } }
// // Options.cs // // Authors: // Jonathan Pryor <[email protected]> // // Copyright (C) 2008 Novell (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. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // #if LINQ using System.Linq; #endif #if TEST using NDesk.Options; #endif namespace chocolatey.infrastructure.commandline { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; // ReSharper disable InconsistentNaming public class OptionValueCollection : IList, IList<string> { List<string> values = new List<string> (); OptionContext c; internal OptionValueCollection (OptionContext c) { this.c = c; } #region ICollection void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} #endregion #region ICollection<T> public void Add (string item) {values.Add (item);} public void Clear () {values.Clear ();} public bool Contains (string item) {return values.Contains (item);} public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} public bool Remove (string item) {return values.Remove (item);} public int Count {get {return values.Count;}} public bool IsReadOnly {get {return false;}} #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} #endregion #region IEnumerable<T> public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();} #endregion #region IList int IList.Add (object value) {return (values as IList).Add (value);} bool IList.Contains (object value) {return (values as IList).Contains (value);} int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} void IList.Remove (object value) {(values as IList).Remove (value);} void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} bool IList.IsFixedSize {get {return false;}} object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} #endregion #region IList<T> public int IndexOf (string item) {return values.IndexOf (item);} public void Insert (int index, string item) {values.Insert (index, item);} public void RemoveAt (int index) {values.RemoveAt (index);} private void AssertValid (int index) { if (c.Option == null) throw new InvalidOperationException ("OptionContext.Option is null."); if (index >= c.Option.MaxValueCount) throw new ArgumentOutOfRangeException ("index"); if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) throw new OptionException (string.Format ( c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } public string this [int index] { get { AssertValid (index); return index >= values.Count ? null : values [index]; } set { values [index] = value; } } #endregion public List<string> ToList () { return new List<string> (values); } public string[] ToArray () { return values.ToArray (); } public override string ToString () { return string.Join (", ", values.ToArray ()); } } public class OptionContext { private Option option; private string name; private int index; private OptionSet set; private OptionValueCollection c; public OptionContext (OptionSet set) { this.set = set; this.c = new OptionValueCollection (this); } public Option Option { get {return option;} set {option = value;} } public string OptionName { get {return name;} set {name = value;} } public int OptionIndex { get {return index;} set {index = value;} } public OptionSet OptionSet { get {return set;} } public OptionValueCollection OptionValues { get {return c;} } } public enum OptionValueType { None, Optional, Required, } public abstract class Option { string prototype, description; string[] names; OptionValueType type; int count; string[] separators; protected Option (string prototype, string description) : this (prototype, description, 1) { } protected Option (string prototype, string description, int maxValueCount) { if (prototype == null) throw new ArgumentNullException ("prototype"); if (prototype.Length == 0) throw new ArgumentException ("Cannot be the empty string.", "prototype"); if (maxValueCount < 0) throw new ArgumentOutOfRangeException ("maxValueCount"); this.prototype = prototype; this.names = prototype.Split ('|'); this.description = description; this.count = maxValueCount; this.type = ParsePrototype (); if (this.count == 0 && type != OptionValueType.None) throw new ArgumentException ( "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + "OptionValueType.Optional.", "maxValueCount"); if (this.type == OptionValueType.None && maxValueCount > 1) throw new ArgumentException ( string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), "maxValueCount"); if (Array.IndexOf (names, "<>") >= 0 && ((names.Length == 1 && this.type != OptionValueType.None) || (names.Length > 1 && this.MaxValueCount > 1))) throw new ArgumentException ( "The default option handler '<>' cannot require values.", "prototype"); } public string Prototype {get {return prototype;}} public string Description {get {return description;}} public OptionValueType OptionValueType {get {return type;}} public int MaxValueCount {get {return count;}} public string[] GetNames () { return (string[]) names.Clone (); } public string[] GetValueSeparators () { if (separators == null) return new string [0]; return (string[]) separators.Clone (); } protected static T Parse<T> (string value, OptionContext c) { TypeConverter conv = TypeDescriptor.GetConverter (typeof (T)); T t = default (T); try { if (value != null) t = (T) conv.ConvertFromString (value); } catch (Exception e) { throw new OptionException ( string.Format ( c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), value, typeof (T).Name, c.OptionName), c.OptionName, e); } return t; } internal string[] Names {get {return names;}} internal string[] ValueSeparators {get {return separators;}} static readonly char[] NameTerminator = new char[]{'=', ':'}; private OptionValueType ParsePrototype () { char type = '\0'; List<string> seps = new List<string> (); for (int i = 0; i < names.Length; ++i) { string name = names [i]; if (name.Length == 0) throw new ArgumentException ("Empty option names are not supported.", "prototype"); int end = name.IndexOfAny (NameTerminator); if (end == -1) continue; names [i] = name.Substring (0, end); if (type == '\0' || type == name [end]) type = name [end]; else throw new ArgumentException ( string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), "prototype"); AddSeparators (name, end, seps); } if (type == '\0') return OptionValueType.None; if (count <= 1 && seps.Count != 0) throw new ArgumentException ( string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), "prototype"); if (count > 1) { if (seps.Count == 0) this.separators = new string[]{":", "="}; else if (seps.Count == 1 && seps [0].Length == 0) this.separators = null; else this.separators = seps.ToArray (); } return type == '=' ? OptionValueType.Required : OptionValueType.Optional; } private static void AddSeparators (string name, int end, ICollection<string> seps) { int start = -1; for (int i = end+1; i < name.Length; ++i) { switch (name [i]) { case '{': if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); start = i+1; break; case '}': if (start == -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); seps.Add (name.Substring (start, i-start)); start = -1; break; default: if (start == -1) seps.Add (name [i].ToString ()); break; } } if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); } public void Invoke (OptionContext c) { OnParseComplete (c); c.OptionName = null; c.Option = null; c.OptionValues.Clear (); } protected abstract void OnParseComplete (OptionContext c); public override string ToString () { return Prototype; } } [Serializable] public class OptionException : Exception { private string option; public OptionException () { } public OptionException (string message, string optionName) : base (message) { this.option = optionName; } public OptionException (string message, string optionName, Exception innerException) : base (message, innerException) { this.option = optionName; } protected OptionException (SerializationInfo info, StreamingContext context) : base (info, context) { this.option = info.GetString ("OptionName"); } public string OptionName { get {return this.option;} } [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] public override void GetObjectData (SerializationInfo info, StreamingContext context) { base.GetObjectData (info, context); info.AddValue ("OptionName", option); } } public delegate void OptionAction<TKey, TValue> (TKey key, TValue value); public class OptionSet : KeyedCollection<string, Option> { public OptionSet () : this (delegate (string f) {return f;}) { } public OptionSet(Converter<string, string> localizer) : base(StringComparer.OrdinalIgnoreCase) { this.localizer = localizer; } Converter<string, string> localizer; public Converter<string, string> MessageLocalizer { get {return localizer;} } protected override string GetKeyForItem (Option item) { if (item == null) throw new ArgumentNullException ("option"); if (item.Names != null && item.Names.Length > 0) return item.Names [0]; // This should never happen, as it's invalid for Option to be // constructed w/o any names. throw new InvalidOperationException ("Option has no names!"); } [Obsolete ("Use KeyedCollection.this[string]")] protected Option GetOptionForName (string option) { if (option == null) throw new ArgumentNullException ("option"); try { return base [option]; } catch (KeyNotFoundException) { return null; } } protected override void InsertItem (int index, Option item) { base.InsertItem (index, item); AddImpl (item); } protected override void RemoveItem (int index) { base.RemoveItem (index); Option p = Items [index]; // KeyedCollection.RemoveItem() handles the 0th item for (int i = 1; i < p.Names.Length; ++i) { Dictionary.Remove (p.Names [i]); } } protected override void SetItem (int index, Option item) { base.SetItem (index, item); RemoveItem (index); AddImpl (item); } private void AddImpl (Option option) { if (option == null) throw new ArgumentNullException ("option"); List<string> added = new List<string> (option.Names.Length); try { // KeyedCollection.InsertItem/SetItem handle the 0th name. for (int i = 1; i < option.Names.Length; ++i) { Dictionary.Add (option.Names [i], option); added.Add (option.Names [i]); } } catch (Exception) { foreach (string name in added) Dictionary.Remove (name); throw; } } public new OptionSet Add (Option option) { base.Add (option); return this; } sealed class ActionOption : Option { Action<OptionValueCollection> action; public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action) : base (prototype, description, count) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (c.OptionValues); } } public OptionSet Add (string prototype, Action<string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, Action<string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 1, delegate (OptionValueCollection v) { action (v [0]); }); base.Add (p); return this; } public OptionSet Add (string prototype, OptionAction<string, string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, OptionAction<string, string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 2, delegate (OptionValueCollection v) {action (v [0], v [1]);}); base.Add (p); return this; } sealed class ActionOption<T> : Option { Action<T> action; public ActionOption (string prototype, string description, Action<T> action) : base (prototype, description, 1) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (Parse<T> (c.OptionValues [0], c)); } } sealed class ActionOption<TKey, TValue> : Option { OptionAction<TKey, TValue> action; public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action) : base (prototype, description, 2) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action ( Parse<TKey> (c.OptionValues [0], c), Parse<TValue> (c.OptionValues [1], c)); } } public OptionSet Add<T> (string prototype, Action<T> action) { return Add (prototype, null, action); } public OptionSet Add<T> (string prototype, string description, Action<T> action) { return Add (new ActionOption<T> (prototype, description, action)); } public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action) { return Add (prototype, null, action); } public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action) { return Add (new ActionOption<TKey, TValue> (prototype, description, action)); } protected virtual OptionContext CreateOptionContext () { return new OptionContext (this); } #if LINQ public List<string> Parse (IEnumerable<string> arguments) { bool process = true; OptionContext c = CreateOptionContext (); c.OptionIndex = -1; var def = GetOptionForName ("<>"); var unprocessed = from argument in arguments where ++c.OptionIndex >= 0 && (process || def != null) ? process ? argument == "--" ? (process = false) : !Parse (argument, c) ? def != null ? Unprocessed (null, def, c, argument) : true : false : def != null ? Unprocessed (null, def, c, argument) : true : true select argument; List<string> r = unprocessed.ToList (); if (c.Option != null) c.Option.Invoke (c); return r; } #else public List<string> Parse (IEnumerable<string> arguments) { OptionContext c = CreateOptionContext (); c.OptionIndex = -1; bool process = true; List<string> unprocessed = new List<string> (); Option def = Contains ("<>") ? this ["<>"] : null; foreach (string argument in arguments) { ++c.OptionIndex; if (argument == "--") { process = false; continue; } if (!process) { Unprocessed (unprocessed, def, c, argument); continue; } if (!Parse (argument, c)) Unprocessed (unprocessed, def, c, argument); } if (c.Option != null) c.Option.Invoke (c); return unprocessed; } #endif private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument) { if (def == null) { extra.Add (argument); return false; } c.OptionValues.Add (argument); c.Option = def; c.Option.Invoke (c); return false; } private readonly Regex ValueOption = new Regex ( @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) { if (argument == null) throw new ArgumentNullException ("argument"); flag = name = sep = value = null; Match m = ValueOption.Match (argument); if (!m.Success) { return false; } flag = m.Groups ["flag"].Value; name = m.Groups ["name"].Value; if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { sep = m.Groups ["sep"].Value; value = m.Groups ["value"].Value; } return true; } protected virtual bool Parse (string argument, OptionContext c) { if (c.Option != null) { ParseValue (argument, c); return true; } string f, n, s, v; if (!GetOptionParts (argument, out f, out n, out s, out v)) return false; Option p; if (Contains (n)) { p = this [n]; c.OptionName = f + n; c.Option = p; switch (p.OptionValueType) { case OptionValueType.None: c.OptionValues.Add (n); c.Option.Invoke (c); break; case OptionValueType.Optional: case OptionValueType.Required: ParseValue (v, c); break; } return true; } // no match; is it a bool option? if (ParseBool (argument, n, c)) return true; // is it a bundled option? try { if (ParseBundledValue(f, string.Concat(n + s + v), c)) return true; } catch (Exception ex) { "chocolatey".Log().Warn("Parsing {0} resulted in exception:{1} {2}".format_with(argument, Environment.NewLine, ex.Message)); } return false; } private void ParseValue (string option, OptionContext c) { if (option != null) foreach (string o in c.Option.ValueSeparators != null ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None) : new string[]{option}) { c.OptionValues.Add (o); } if (c.OptionValues.Count == c.Option.MaxValueCount || c.Option.OptionValueType == OptionValueType.Optional) c.Option.Invoke (c); else if (c.OptionValues.Count > c.Option.MaxValueCount) { throw new OptionException (localizer (string.Format ( "Error: Found {0} option values when expecting {1}.", c.OptionValues.Count, c.Option.MaxValueCount)), c.OptionName); } } private bool ParseBool (string option, string n, OptionContext c) { Option p; string rn; if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && Contains ((rn = n.Substring (0, n.Length-1)))) { p = this [rn]; string v = n [n.Length-1] == '+' ? option : null; c.OptionName = option; c.Option = p; c.OptionValues.Add (v); p.Invoke (c); return true; } return false; } private bool ParseBundledValue (string f, string n, OptionContext c) { IDictionary<Option,string> normalOptions = new Dictionary<Option, string>(); if (f != "-") return false; for (int i = 0; i < n.Length; ++i) { Option p; string opt = f + n [i].ToString (); string rn = n [i].ToString (); if (!Contains (rn)) { if (i == 0) return false; throw new OptionException (string.Format (localizer ( "Cannot bundle unregistered option '{0}'."), opt), opt); } p = this [rn]; switch (p.OptionValueType) { case OptionValueType.None: normalOptions.Add(p, opt); break; case OptionValueType.Optional: case OptionValueType.Required: { string v = n.Substring(i + 1); c.Option = p; c.OptionName = opt; ParseValue(v.Length != 0 ? v : null, c); return true; } default: throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType); } } // only invoke options for bundled if all options exist foreach (var option in normalOptions) { Invoke(c, option.Value, n, option.Key); } return true; } private static void Invoke (OptionContext c, string name, string value, Option option) { c.OptionName = name; c.Option = option; c.OptionValues.Add (value); option.Invoke (c); } private const int OptionWidth = 5; public void WriteOptionDescriptions (TextWriter o) { foreach (Option p in this) { o.WriteLine(); int written = 0; if (!WriteOptionPrototype (o, p, ref written)) continue; if (written < OptionWidth) o.Write (new string (' ', OptionWidth - written)); else { o.WriteLine (); o.Write (new string (' ', OptionWidth)); } List<string> lines = GetLines (localizer (GetDescription (p.Description))); o.WriteLine (lines [0]); string prefix = new string (' ', OptionWidth+2); for (int i = 1; i < lines.Count; ++i) { o.Write (prefix); o.WriteLine (lines [i]); } } } bool WriteOptionPrototype (TextWriter o, Option p, ref int written) { string[] names = p.Names; int i = GetNextOptionIndex (names, 0); if (i == names.Length) return false; if (names [i].Length == 1) { Write (o, ref written, " -"); Write (o, ref written, names [0]); } else { Write (o, ref written, " --"); Write (o, ref written, names [0]); } for ( i = GetNextOptionIndex (names, i+1); i < names.Length; i = GetNextOptionIndex (names, i+1)) { Write (o, ref written, ", "); Write (o, ref written, names [i].Length == 1 ? "-" : "--"); Write (o, ref written, names [i]); } if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("[")); } Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 ? p.ValueSeparators [0] : " "; for (int c = 1; c < p.MaxValueCount; ++c) { Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("]")); } } return true; } static int GetNextOptionIndex (string[] names, int i) { while (i < names.Length && names [i] == "<>") { ++i; } return i; } static void Write (TextWriter o, ref int n, string s) { n += s.Length; o.Write (s); } private static string GetArgumentName (int index, int maxIndex, string description) { if (description == null) return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); string[] nameStart; if (maxIndex == 1) nameStart = new string[]{"{0:", "{"}; else nameStart = new string[]{"{" + index + ":"}; for (int i = 0; i < nameStart.Length; ++i) { int start, j = 0; do { start = description.IndexOf (nameStart [i], j); } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); if (start == -1) continue; int end = description.IndexOf ("}", start); if (end == -1) continue; return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); } return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); } private static string GetDescription (string description) { if (description == null) return string.Empty; StringBuilder sb = new StringBuilder (description.Length); int start = -1; for (int i = 0; i < description.Length; ++i) { switch (description [i]) { case '{': if (i == start) { sb.Append ('{'); start = -1; } else if (start < 0) start = i + 1; break; case '}': if (start < 0) { if ((i+1) == description.Length || description [i+1] != '}') throw new InvalidOperationException ("Invalid option description: " + description); ++i; sb.Append ("}"); } else { sb.Append (description.Substring (start, i - start)); start = -1; } break; case ':': if (start < 0) goto default; start = i + 1; break; default: if (start < 0) sb.Append (description [i]); break; } } return sb.ToString (); } private static List<string> GetLines (string description) { List<string> lines = new List<string> (); if (string.IsNullOrEmpty (description)) { lines.Add (string.Empty); return lines; } int length = 80 - OptionWidth - 2; int start = 0, end; do { end = GetLineEnd (start, length, description); bool cont = false; if (end < description.Length) { char c = description [end]; if (c == '-' || (char.IsWhiteSpace (c) && c != '\n')) ++end; else if (c != '\n') { cont = true; --end; } } lines.Add (description.Substring (start, end - start)); if (cont) { lines [lines.Count-1] += "-"; } start = end; if (start < description.Length && description [start] == '\n') ++start; } while (end < description.Length); return lines; } private static int GetLineEnd (int start, int length, string description) { int end = Math.Min (start + length, description.Length); int sep = -1; for (int i = start; i < end; ++i) { switch (description [i]) { case ' ': case '\t': case '\v': case '-': case ',': case '.': case ';': sep = i; break; case '\n': return i; } } if (sep == -1 || end == description.Length) return end; return sep; } } // ReSharper restore InconsistentNaming }
//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 SimilarityModel.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.Collections.Generic; using System.Linq; using System.IO; namespace OpenNLP.Tools.Coreference.Similarity { /// <summary> /// Models semantic similarity between two mentions and returns a score based on /// how semantically comparible the mentions are with one another. /// </summary> public class SimilarityModel : ITestSimilarityModel, ITrainSimilarityModel { private readonly string ModelName; private const string ModelExtension = ".nbin"; private readonly SharpEntropy.IMaximumEntropyModel _testModel; private readonly List<SharpEntropy.TrainingEvent> _events; private readonly int _sameIndex; private const string Same = "same"; private const string Different = "diff"; private const bool DebugOn = false; public static ITestSimilarityModel TestModel(string name) { return new SimilarityModel(name, false); } public static ITrainSimilarityModel TrainModel(string name) { return new SimilarityModel(name, true); } private SimilarityModel(string modelName, bool train) { ModelName = modelName; if (train) { _events = new List<SharpEntropy.TrainingEvent>(); } else { _testModel = new SharpEntropy.GisModel(new SharpEntropy.IO.BinaryGisModelReader(modelName + ModelExtension)); _sameIndex = _testModel.GetOutcomeIndex(Same); } } public virtual void SetExtents(Context[] extents) { var entities = new Util.HashList<int, Context>(); // Extents which are not in a coreference chain. var singletons = new List<Context>(); var allExtents = new List<Context>(); //populate data structures foreach (Context currentExtent in extents) { if (currentExtent.Id == -1) { singletons.Add(currentExtent); } else { entities.Put(currentExtent.Id, currentExtent); } allExtents.Add(currentExtent); } int allExtentsIndex = 0; Dictionary<int, Util.Set<string>> headSets = ConstructHeadSets(entities); Dictionary<int, Util.Set<string>> nameSets = ConstructNameSets(entities); foreach (int key in entities.Keys) { Util.Set<string> entityNameSet = nameSets[key]; if (entityNameSet.Count == 0) { continue; } List<Context> entityContexts = entities[key]; Util.Set<Context> exclusionSet = ConstructExclusionSet(key, entities, headSets, nameSets, singletons); //if (entityContexts.Count == 1) //{ //} for (int firstEntityContextIndex = 0; firstEntityContextIndex < entityContexts.Count; firstEntityContextIndex++) { Context firstEntityContext = entityContexts[firstEntityContextIndex]; //if (isPronoun(ec1)) { // continue; //} for (int secondEntityContextIndex = firstEntityContextIndex + 1; secondEntityContextIndex < entityContexts.Count; secondEntityContextIndex++) { Context secondEntityContext = entityContexts[secondEntityContextIndex]; //if (isPronoun(ec2)) { // continue; //} AddEvent(true, firstEntityContext, secondEntityContext); int startIndex = allExtentsIndex; do { Context compareEntityContext = allExtents[allExtentsIndex]; allExtentsIndex = (allExtentsIndex + 1) % allExtents.Count; if (!exclusionSet.Contains(compareEntityContext)) { if (DebugOn) { System.Console.Error.WriteLine(firstEntityContext.ToString() + " " + string.Join(",", entityNameSet.ToArray()) + " " + compareEntityContext.ToString() + " " + nameSets[compareEntityContext.Id]); } AddEvent(false, firstEntityContext, compareEntityContext); break; } } while (allExtentsIndex != startIndex); } } } } private void AddEvent(bool same, Context firstNounPhrase, Context secondNounPhrase) { if (same) { List<string> features = GetFeatures(firstNounPhrase, secondNounPhrase); _events.Add(new SharpEntropy.TrainingEvent(Same, features.ToArray())); } else { List<string> features = GetFeatures(firstNounPhrase, secondNounPhrase); _events.Add(new SharpEntropy.TrainingEvent(Different, features.ToArray())); } } /// <summary> /// Produces a set of head words for the specified list of mentions. /// </summary> /// <param name="mentions"> /// The mentions to use to construct the /// </param> /// <returns> /// A set containing the head words of the sepecified mentions. /// </returns> private Util.Set<string> ConstructHeadSet(IEnumerable<Context> mentions) { Util.Set<string> headSet = new Util.HashSet<string>(); foreach (Context currentContext in mentions) { headSet.Add(currentContext.HeadTokenText.ToLower()); } return headSet; } private bool HasSameHead(IEnumerable<string> entityHeadSet, Util.Set<string> candidateHeadSet) { return entityHeadSet.Any(candidateHeadSet.Contains); } private bool HasSameNameType(IEnumerable<string> entityNameSet, Util.Set<string> candidateNameSet) { return entityNameSet.Any(candidateNameSet.Contains); } private bool HasSuperClass(IEnumerable<Context> entityContexts, List<Context> candidateContexts) { foreach (Context currentEntityContext in entityContexts) { foreach (Context currentCandidateContext in candidateContexts) { if (InSuperClass(currentEntityContext, currentCandidateContext)) { return true; } } } return false; } /// <summary> /// Constructs a set of entities which may be semantically compatible with the entity indicated by /// the specified entityKey. /// </summary> /// <param name="entityKey"> /// The key of the entity for which the set is being constructed. /// </param> /// <param name="entities"> /// A mapping between entity keys and their mentions. /// </param> /// <param name="headSets"> /// A mapping between entity keys and their head sets. /// </param> /// <param name="nameSets"> /// A mapping between entity keys and their name sets. /// </param> /// <param name="singletons"> /// A list of all entities which consists of a single mention. /// </param> /// <returns> /// A set of mentions for all the entities which might be semantically compatible /// with entity indicated by the specified key. /// </returns> private Util.Set<Context> ConstructExclusionSet(int entityKey, Util.HashList<int, Context> entities, Dictionary<int, Util.Set<string>> headSets, Dictionary<int, Util.Set<string>> nameSets, IEnumerable<Context> singletons) { Util.Set<Context> exclusionSet = new Util.HashSet<Context>(); Util.Set<string> entityHeadSet = headSets[entityKey]; Util.Set<string> entityNameSet = nameSets[entityKey]; List<Context> entityContexts = entities[entityKey]; //entities foreach (int key in entities.Keys) { List<Context> candidateContexts = entities[key]; if (key == entityKey) { exclusionSet.AddAll(candidateContexts); } else if (nameSets[key].Count == 0) { exclusionSet.AddAll(candidateContexts); } else if (HasSameHead(entityHeadSet, headSets[key])) { exclusionSet.AddAll(candidateContexts); } else if (HasSameNameType(entityNameSet, nameSets[key])) { exclusionSet.AddAll(candidateContexts); } else if (HasSuperClass(entityContexts, candidateContexts)) { exclusionSet.AddAll(candidateContexts); } } //singles var singles = new List<Context>(1); foreach (Context currentSingleton in singletons) { singles.Clear(); singles.Add(currentSingleton); if (entityHeadSet.Contains(currentSingleton.HeadTokenText.ToLower())) { exclusionSet.Add(currentSingleton); } else if (currentSingleton.NameType == null) { exclusionSet.Add(currentSingleton); } else if (entityNameSet.Contains(currentSingleton.NameType)) { exclusionSet.Add(currentSingleton); } else if (HasSuperClass(entityContexts, singles)) { exclusionSet.Add(currentSingleton); } } return exclusionSet; } /// <summary> /// Constructs a mapping between the specified entities and their head set. /// </summary> /// <param name="entities"> /// Mapping between a key and a list of mentions which compose an entity. /// </param> /// <returns> /// a mapping between the keys of the secified entity mapping and the head set /// generatated from the mentions associated with that key. /// </returns> private Dictionary<int, Util.Set<string>> ConstructHeadSets(Util.HashList<int, Context> entities) { var headSets = new Dictionary<int, Util.Set<string>>(); foreach (int key in entities.Keys) { List<Context> entityContexts = entities[key]; headSets[key] = ConstructHeadSet(entityContexts); } return headSets; } /// <summary> /// Produces the set of name types associated with each of the specified mentions. /// </summary> /// <param name="mentions"> /// A list of mentions. /// </param> /// <returns> /// A set of name types assigned to the specified mentions. /// </returns> private Util.Set<string> ConstructNameSet(IEnumerable<Context> mentions) { Util.Set<string> nameSet = new Util.HashSet<string>(); foreach (Context currentContext in mentions) { if (currentContext.NameType != null) { nameSet.Add(currentContext.NameType); } } return nameSet; } /// <summary> /// Constructs a mappng between the specified entities and the names associated with these entities. /// </summary> /// <param name="entities"> /// A mapping between a key and a list of mentions. /// </param> /// <returns> /// a mapping between each key in the specified entity map and the name types associated with the each mention of that entity. /// </returns> private Dictionary<int, Util.Set<string>> ConstructNameSets(Util.HashList<int, Context> entities) { var nameSets = new Dictionary<int, Util.Set<string>>(); foreach (int key in entities.Keys) { List<Context> entityContexts = entities[key]; nameSets[key] = ConstructNameSet(entityContexts); } return nameSets; } private bool InSuperClass(Context entityContext, Context candidateEntityContext) { if (entityContext.Synsets.Count == 0 || candidateEntityContext.Synsets.Count == 0) { return false; } else { int commonSynsetCount = 0; foreach (string synset in entityContext.Synsets) { if (candidateEntityContext.Synsets.Contains(synset)) { commonSynsetCount++; } } if (commonSynsetCount == 0) { return false; } else if (commonSynsetCount == entityContext.Synsets.Count || commonSynsetCount == candidateEntityContext.Synsets.Count) { return true; } else { return false; } } } /* private boolean isPronoun(MentionContext mention) { return mention.getHeadTokenTag().startsWith("PRP"); } */ /// <summary> /// Returns a number between 0 and 1 which represents the models belief that the specified mentions are /// compatible. /// Value closer to 1 are more compatible, while values closer to 0 are less compatible. /// </summary> /// <param name="firstMention"> /// The first mention to be considered. /// </param> /// <param name="secondMention"> /// The second mention to be considered. /// </param> /// <returns> /// a number between 0 and 1 which represents the models belief that the specified mentions are compatible. /// </returns> public virtual double AreCompatible(Context firstMention, Context secondMention) { List<string> features = GetFeatures(firstMention, secondMention); if (DebugOn) { Console.Error.WriteLine("SimilarityModel.compatible: feats=" + string.Join(",", features.ToArray())); } return _testModel.Evaluate(features.ToArray())[_sameIndex]; } /// <summary>Train a model based on the previously supplied evidence</summary> public virtual void TrainModel() { if (DebugOn) { using (var fileStream = new FileStream(ModelName + ".events", FileMode.Create)){ using (var writer = new StreamWriter(fileStream, Encoding.GetEncoding(0))){ foreach (SharpEntropy.TrainingEvent trainingEvent in _events) { writer.Write(trainingEvent + "\n"); } } } } var trainer = new SharpEntropy.GisTrainer(); trainer.TrainModel(new Util.CollectionEventReader(_events), 100, 10); new SharpEntropy.IO.BinaryGisModelWriter().Persist(new SharpEntropy.GisModel(trainer), ModelName + ModelExtension); } private bool IsName(Context nounPhrase) { return PartsOfSpeech.IsProperNoun(nounPhrase.HeadTokenTag); } private bool IsCommonNoun(Context nounPhrase) { return !PartsOfSpeech.IsProperNoun(nounPhrase.HeadTokenTag) && PartsOfSpeech.IsNoun(nounPhrase.HeadTokenTag); } private bool IsPronoun(Context nounPhrase) { return PartsOfSpeech.IsPersOrPossPronoun(nounPhrase.HeadTokenTag); } private bool IsNumber(Context nounPhrase) { return nounPhrase.HeadTokenTag == PartsOfSpeech.CardinalNumber; } private IEnumerable<string> GetNameCommonFeatures(Context name, Context common) { Util.Set<string> synsets = common.Synsets; var features = new List<string>(2 + synsets.Count) { "nn=" + name.NameType + "," + common.NameType, "nw=" + name.NameType + "," + common.HeadTokenText.ToLower() }; foreach (string synset in synsets) { features.Add("ns=" + name.NameType + "," + synset); } if (name.NameType == null) { //features.addAll(GetCommonCommonFeatures(name,common)); } return features; } private IEnumerable<string> GetNameNumberFeatures(Context name, Context number) { var features = new List<string>(2) { "nt=" + name.NameType + "," + number.HeadTokenTag, "nn=" + name.NameType + "," + number.NameType }; return features; } private IEnumerable<string> GetNamePronounFeatures(Context name, Context pronoun) { var features = new List<string>(2) { "nw=" + name.NameType + "," + pronoun.HeadTokenText.ToLower(), "ng=" + name.NameType + "," + Resolver.AbstractResolver.GetPronounGender(pronoun.HeadTokenText.ToLower()) }; return features; } private IEnumerable<string> GetCommonPronounFeatures(Context common, Context pronoun) { var features = new List<string>(); Util.Set<string> synsets = common.Synsets; string pronounText = pronoun.HeadTokenText.ToLower(); string genderText = Resolver.AbstractResolver.GetPronounGender(pronounText); features.Add("wn=" + pronounText + "," + common.NameType); foreach (string synset in synsets) { features.Add("ws=" + pronounText + "," + synset); features.Add("gs=" + genderText + "," + synset); } return features; } private IEnumerable<string> GetCommonNumberFeatures(Context common, Context number) { var features = new List<string>(); Util.Set<string> synsets = common.Synsets; foreach (string synset in synsets) { features.Add("ts=" + number.HeadTokenTag + "," + synset); features.Add("ns=" + number.NameType + "," + synset); } features.Add("nn=" + number.NameType + "," + common.NameType); return features; } private IEnumerable<string> GetNumberPronounFeatures(Context number, Context pronoun) { var features = new List<string>(); string pronounText = pronoun.HeadTokenText.ToLower(); string genderText = Resolver.AbstractResolver.GetPronounGender(pronounText); features.Add("wt=" + pronounText + "," + number.HeadTokenTag); features.Add("wn=" + pronounText + "," + number.NameType); features.Add("wt=" + genderText + "," + number.HeadTokenTag); features.Add("wn=" + genderText + "," + number.NameType); return features; } private IEnumerable<string> GetNameNameFeatures(Context name1, Context name2) { var features = new List<string>(1); if (name1.NameType == null && name2.NameType == null) { features.Add("nn=" + name1.NameType + "," + name2.NameType); //features.addAll(getCommonCommonFeatures(name1,name2)); } else if (name1.NameType == null) { features.Add("nn=" + name1.NameType + "," + name2.NameType); //features.addAll(getNameCommonFeatures(name2,name1)); } else if (name2.NameType == null) { features.Add("nn=" + name2.NameType + "," + name1.NameType); //features.addAll(getNameCommonFeatures(name1,name2)); } else { if (string.CompareOrdinal(name1.NameType, name2.NameType) < 0) { features.Add("nn=" + name1.NameType + "," + name2.NameType); } else { features.Add("nn=" + name2.NameType + "," + name1.NameType); } if (name1.NameType == name2.NameType) { features.Add("sameNameType"); } } return features; } private IEnumerable<string> GetCommonCommonFeatures(Context common1, Context common2) { var features = new List<string>(); Util.Set<string> synsets1 = common1.Synsets; Util.Set<string> synsets2 = common2.Synsets; if (synsets1.Count == 0) { //features.add("missing_"+common1.headToken); return features; } if (synsets2.Count == 0) { //features.add("missing_"+common2.headToken); return features; } int commonSynsetCount = 0; //RN commented out - this looks wrong in the java //bool same = false; //if (commonSynsetCount == 0) //{ // features.Add("ncss"); //} //else if (commonSynsetCount == synsets1.Count && commonSynsetCount == synsets2.Count) //{ // same = true; // features.Add("samess"); //} //else if (commonSynsetCount == synsets1.Count) //{ // features.Add("2isa1"); // //features.add("2isa1-"+(synsets2.size() - numCommonSynsets)); //} //else if (commonSynsetCount == synsets2.Count) //{ // features.Add("1isa2"); // //features.add("1isa2-"+(synsets1.size() - numCommonSynsets)); //} //if (!same) //{ foreach(string synset in synsets1) { if (synsets2.Contains(synset)) { features.Add("ss=" + synset); commonSynsetCount++; } } //} //end RN commented out if (commonSynsetCount == 0) { features.Add("ncss"); } else if (commonSynsetCount == synsets1.Count && commonSynsetCount == synsets2.Count) { features.Add("samess"); } else if (commonSynsetCount == synsets1.Count) { features.Add("2isa1"); //features.add("2isa1-"+(synsets2.size() - numCommonSynsets)); } else if (commonSynsetCount == synsets2.Count) { features.Add("1isa2"); //features.add("1isa2-"+(synsets1.size() - numCommonSynsets)); } return features; } private IEnumerable<string> GetPronounPronounFeatures(Context pronoun1, Context pronoun2) { var features = new List<string>(); string firstGender = Resolver.AbstractResolver.GetPronounGender(pronoun1.HeadTokenText); string secondGender = Resolver.AbstractResolver.GetPronounGender(pronoun2.HeadTokenText); features.Add(firstGender == secondGender ? "sameGender" : "diffGender"); return features; } private List<string> GetFeatures(Context np1, Context np2) { var features = new List<string> {"default"}; // semantic categories string w1 = np1.HeadTokenText.ToLower(); string w2 = np2.HeadTokenText.ToLower(); if (string.CompareOrdinal(w1, w2) < 0) { features.Add("ww=" + w1 + "," + w2); } else { features.Add("ww=" + w2 + "," + w1); } if (w1 == w2) { features.Add("sameHead"); } //features.add("tt="+np1.headTag+","+np2.headTag); if (IsName(np1)) { if (IsName(np2)) { features.AddRange(GetNameNameFeatures(np1, np2)); } else if (IsCommonNoun(np2)) { features.AddRange(GetNameCommonFeatures(np1, np2)); } else if (IsPronoun(np2)) { features.AddRange(GetNamePronounFeatures(np1, np2)); } else if (IsNumber(np2)) { features.AddRange(GetNameNumberFeatures(np1, np2)); } } else if (IsCommonNoun(np1)) { if (IsName(np2)) { features.AddRange(GetNameCommonFeatures(np2, np1)); } else if (IsCommonNoun(np2)) { features.AddRange(GetCommonCommonFeatures(np1, np2)); } else if (IsPronoun(np2)) { features.AddRange(GetCommonPronounFeatures(np1, np2)); } else if (IsNumber(np2)) { features.AddRange(GetCommonNumberFeatures(np1, np2)); } } else if (IsPronoun(np1)) { if (IsName(np2)) { features.AddRange(GetNamePronounFeatures(np2, np1)); } else if (IsCommonNoun(np2)) { features.AddRange(GetCommonPronounFeatures(np2, np1)); } else if (IsPronoun(np2)) { features.AddRange(GetPronounPronounFeatures(np1, np2)); } else if (IsNumber(np2)) { features.AddRange(GetNumberPronounFeatures(np2, np1)); } } else if (IsNumber(np1)) { if (IsName(np2)) { features.AddRange(GetNameNumberFeatures(np2, np1)); } else if (IsCommonNoun(np2)) { features.AddRange(GetCommonNumberFeatures(np2, np1)); } else if (IsPronoun(np2)) { features.AddRange(GetNumberPronounFeatures(np1, np2)); } else if (IsNumber(np2)) { } } return features; } //Usage: SimilarityModel modelName < tiger/NN bear/NN public static string SimilarityMain(string modelName, string line) { var model = new SimilarityModel(modelName, false); //Context.wn = new WordNet(System.getProperty("WNHOME"), true); //Context.morphy = new Morphy(Context.wn); string[] words = line.Split(' '); double p = model.AreCompatible(Context.ParseContext(words[0]), Context.ParseContext(words[1])); return p + " " + string.Join(",", model.GetFeatures(Context.ParseContext(words[0]), Context.ParseContext(words[1])).ToArray()); } } }
#if !NOT_UNITY3D using System; using System.IO; using UnityEditor; using UnityEngine; using ModestTree; using UnityEditor.SceneManagement; using System.Linq; using UnityEngine.SceneManagement; namespace Zenject { public static class ZenMenuItems { [MenuItem("Edit/Zenject/Validate Current Scenes #%v")] public static void ValidateCurrentScene() { ValidateCurrentSceneInternal(); } [MenuItem("Edit/Zenject/Validate Then Run #%r")] public static void ValidateCurrentSceneThenRun() { if (ValidateCurrentSceneInternal()) { EditorApplication.isPlaying = true; } } [MenuItem("Edit/Zenject/Help...")] public static void OpenDocumentation() { Application.OpenURL("https://github.com/modesttree/zenject"); } [MenuItem("GameObject/Zenject/Scene Context", false, 9)] public static void CreateSceneContext(MenuCommand menuCommand) { var root = new GameObject("SceneContext").AddComponent<SceneContext>(); Selection.activeGameObject = root.gameObject; EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } [MenuItem("GameObject/Zenject/Decorator Context", false, 9)] public static void CreateDecoratorContext(MenuCommand menuCommand) { var root = new GameObject("DecoratorContext").AddComponent<SceneDecoratorContext>(); Selection.activeGameObject = root.gameObject; EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } [MenuItem("GameObject/Zenject/Game Object Context", false, 9)] public static void CreateGameObjectContext(MenuCommand menuCommand) { var root = new GameObject("GameObjectContext").AddComponent<GameObjectContext>(); Selection.activeGameObject = root.gameObject; EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } [MenuItem("Edit/Zenject/Create Project Context")] public static void CreateProjectContextInDefaultLocation() { var fullDirPath = Path.Combine(Application.dataPath, "Resources"); if (!Directory.Exists(fullDirPath)) { Directory.CreateDirectory(fullDirPath); } CreateProjectContextInternal("Assets/Resources"); } [MenuItem("Assets/Create/Zenject/Scriptable Object Installer", false, 1)] public static void CreateScriptableObjectInstaller() { AddCSharpClassTemplate("Scriptable Object Installer", "UntitledInstaller", false, "using UnityEngine;" + "\nusing Zenject;" + "\n" + "\n[CreateAssetMenu(fileName = \"CLASS_NAME\", menuName = \"Installers/CLASS_NAME\")]" + "\npublic class CLASS_NAME : ScriptableObjectInstaller<CLASS_NAME>" + "\n{" + "\n public override void InstallBindings()" + "\n {" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Mono Installer", false, 1)] public static void CreateMonoInstaller() { AddCSharpClassTemplate("Mono Installer", "UntitledInstaller", false, "using UnityEngine;" + "\nusing Zenject;" + "\n" + "\npublic class CLASS_NAME : MonoInstaller<CLASS_NAME>" + "\n{" + "\n public override void InstallBindings()" + "\n {" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Installer", false, 1)] public static void CreateInstaller() { AddCSharpClassTemplate("Installer", "UntitledInstaller", false, "using UnityEngine;" + "\nusing Zenject;" + "\n" + "\npublic class CLASS_NAME : Installer<CLASS_NAME>" + "\n{" + "\n public override void InstallBindings()" + "\n {" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Editor Window", false, 20)] public static void CreateEditorWindow() { AddCSharpClassTemplate("Editor Window", "UntitledEditorWindow", true, "using UnityEngine;" + "\nusing UnityEditor;" + "\nusing Zenject;" + "\n" + "\npublic class CLASS_NAME : ZenjectEditorWindow" + "\n{" + "\n [MenuItem(\"Window/CLASS_NAME\")]" + "\n public static CLASS_NAME GetOrCreateWindow()" + "\n {" + "\n var window = EditorWindow.GetWindow<CLASS_NAME>();" + "\n window.titleContent = new GUIContent(\"CLASS_NAME\");" + "\n return window;" + "\n }" + "\n" + "\n public override void InstallBindings()" + "\n {" + "\n // TODO" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Unit Test", false, 60)] public static void CreateUnitTest() { AddCSharpClassTemplate("Unit Test", "UntitledUnitTest", true, "using Zenject;" + "\nusing NUnit.Framework;" + "\n" + "\n[TestFixture]" + "\npublic class CLASS_NAME : ZenjectUnitTestFixture" + "\n{" + "\n [Test]" + "\n public void RunTest1()" + "\n {" + "\n // TODO" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Integration Test", false, 60)] public static void CreateIntegrationTest() { AddCSharpClassTemplate("Integration Test", "UntitledIntegrationTest", false, "using Zenject;" + "\nusing System.Collections;" + "\nusing UnityEngine.TestTools;" + "\n" + "\npublic class CLASS_NAME : ZenjectIntegrationTestFixture" + "\n{" + "\n [UnityTest]" + "\n public IEnumerator RunTest1()" + "\n {" + "\n // Setup initial state by creating game objects from scratch, loading prefabs/scenes, etc" + "\n" + "\n PreInstall();" + "\n" + "\n // Call Container.Bind methods" + "\n" + "\n PostInstall();" + "\n" + "\n // Add test assertions for expected state" + "\n // Using Container.Resolve or [Inject] fields" + "\n yield break;" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Project Context", false, 40)] public static void CreateProjectContext() { var absoluteDir = ZenUnityEditorUtil.TryGetSelectedFolderPathInProjectsTab(); if (absoluteDir == null) { EditorUtility.DisplayDialog("Error", "Could not find directory to place the '{0}.prefab' asset. Please try again by right clicking in the desired folder within the projects pane." .Fmt(ProjectContext.ProjectContextResourcePath), "Ok"); return; } var parentFolderName = Path.GetFileName(absoluteDir); if (parentFolderName != "Resources") { EditorUtility.DisplayDialog("Error", "'{0}.prefab' must be placed inside a directory named 'Resources'. Please try again by right clicking within the Project pane in a valid Resources folder." .Fmt(ProjectContext.ProjectContextResourcePath), "Ok"); return; } CreateProjectContextInternal(absoluteDir); } static void CreateProjectContextInternal(string absoluteDir) { var assetPath = ZenUnityEditorUtil.ConvertFullAbsolutePathToAssetPath(absoluteDir); var prefabPath = (Path.Combine(assetPath, ProjectContext.ProjectContextResourcePath) + ".prefab").Replace("\\", "/"); var emptyPrefab = PrefabUtility.CreateEmptyPrefab(prefabPath); var gameObject = new GameObject(); try { gameObject.AddComponent<ProjectContext>(); var prefabObj = PrefabUtility.ReplacePrefab(gameObject, emptyPrefab); Selection.activeObject = prefabObj; } finally { GameObject.DestroyImmediate(gameObject); } Debug.Log("Created new ProjectContext at '{0}'".Fmt(prefabPath)); } static void AddCSharpClassTemplate( string friendlyName, string defaultFileName, bool editorOnly, string templateStr) { var folderPath = ZenUnityEditorUtil.GetCurrentDirectoryAssetPathFromSelection(); if (editorOnly && !folderPath.Contains("/Editor")) { EditorUtility.DisplayDialog("Error", "Editor window classes must have a parent folder above them named 'Editor'. Please create or find an Editor folder and try again", "Ok"); return; } var absolutePath = EditorUtility.SaveFilePanel( "Choose name for " + friendlyName, folderPath, defaultFileName + ".cs", "cs"); if (absolutePath == "") { // Dialog was cancelled return; } if (!absolutePath.ToLower().EndsWith(".cs")) { absolutePath += ".cs"; } var className = Path.GetFileNameWithoutExtension(absolutePath); File.WriteAllText(absolutePath, templateStr.Replace("CLASS_NAME", className)); AssetDatabase.Refresh(); var assetPath = ZenUnityEditorUtil.ConvertFullAbsolutePathToAssetPath(absolutePath); EditorUtility.FocusProjectWindow(); Selection.activeObject = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(assetPath); } [MenuItem("Edit/Zenject/Validate All Active Scenes")] public static void ValidateAllActiveScenes() { ValidateWrapper(() => { var numValidated = ZenUnityEditorUtil.ValidateAllActiveScenes(); Log.Info("Validated all '{0}' active scenes successfully", numValidated); }); } static bool ValidateWrapper(Action action) { if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { var originalSceneSetup = EditorSceneManager.GetSceneManagerSetup(); try { action(); return true; } catch (Exception e) { Log.ErrorException(e); return false; } finally { EditorSceneManager.RestoreSceneManagerSetup(originalSceneSetup); } } else { Debug.Log("Validation cancelled - All scenes must be saved first for validation to take place"); return false; } } static bool ValidateCurrentSceneInternal() { return ValidateWrapper(() => { ZenUnityEditorUtil.ValidateCurrentSceneSetup(); Log.Info("All scenes validated successfully"); }); } } } #endif
using System.Net.Http.Headers; using System; using System.Threading; using System.Threading.Tasks; namespace Ceen.Extras { /// <summary> /// Shared interface for the debounce timer /// </summary> public interface IDebounceTimer { /// <summary> /// Signals the debounce timer to run the action /// </summary> /// <param name="condition">A flag used to choose if the notification should be triggered</param> /// <returns><c>true</c> if the signal was used, <c>false</c> if the signal was ignored</returns> bool Notify(bool condition = true); } /// <summary> /// Helper class to allow cancellation of a pending task /// </summary> public class CancelAbleDelayedTask : IDisposable { /// <summary> /// The cancelation token used to control cancellation of the task /// </summary> private readonly CancellationTokenSource m_tcs = new CancellationTokenSource(); /// <summary> /// The pending task /// </summary> private readonly Task m_task; /// <summary> /// Make the cancelable delayed task awaitable /// </summary> System.Runtime.CompilerServices.TaskAwaiter GetAwaiter() => m_task.GetAwaiter(); /// <summary> /// Constructs a new cancel-able delayed task /// </summary> /// <param name="action">The method to execute after the time has passed</param> /// <param name="delay">The delay to use before running the task</param> public CancelAbleDelayedTask(Action action, TimeSpan delay) { m_task = Task.Delay(delay, m_tcs.Token) .ContinueWith(_ => action(), TaskContinuationOptions.OnlyOnRanToCompletion); } /// <summary> /// Disposes all held resources /// </summary> public void Dispose() { m_tcs.Cancel(); } } /// <summary> /// Helper class for debouncing events. /// Note that this class does not guarantee that /// invocations cannot run in parallel. /// Note that repeated notification of the timer /// can cause the action to never execute, /// as it is repeatedly postponed /// </summary> public class DebounceTimerPostpone : IDebounceTimer { /// <summary> /// The internal runner task /// </summary> private CancelAbleDelayedTask m_runner; /// <summary> /// The action to run /// </summary> private readonly Action m_action; /// <summary> /// The delay between each run /// </summary> private readonly TimeSpan m_delay; /// <summary> /// Constructs a new debounce timer /// </summary> /// <param name="action">The action to run</param> /// <param name="delay">The delay between each run</param> /// <param name="notify">Notify on construction</param> public DebounceTimerPostpone(Action action, TimeSpan delay, bool notify = false) { if (delay < TimeSpan.FromMilliseconds(1)) throw new ArgumentOutOfRangeException("The delay must be at least one millisecond"); m_delay = delay; m_action = action ?? throw new ArgumentNullException(nameof(action)); if (notify) Notify(); } /// <summary> /// Triggers the timer and runs the action after the timer has expired /// </summary> /// <param name="condition">A flag used to choose if the notification should be triggered</param> /// <returns><c>true</c> if the signal was used, <c>false</c> if the signal was ignored</returns> public bool Notify(bool condition = true) { if (!condition) return false; var task = new CancelAbleDelayedTask(m_action, m_delay); var prev = System.Threading.Interlocked.Exchange(ref m_runner, task); if (prev != task) prev?.Dispose(); // Stop the previous task return true; } } /// <summary> /// Helper class for debouncing events. /// This class runs at most once for each delay. /// This class guarantees that only one task can /// run at a time, and will restart the timer /// after running, if signalled while running. /// </summary> public class DebounceTimerRepeat : IDebounceTimer { /// <summary> /// The lock guarding the runner /// </summary> private readonly object m_lock = new object(); /// <summary> /// The action to run /// </summary> private readonly Action m_action; /// <summary> /// The delay between each run /// </summary> private readonly TimeSpan m_delay; /// <summary> /// The current runner, if any /// </summary> private Task m_runner; /// <summary> /// Flag used to check if we should re-activate /// </summary> private int m_reactivate; /// <summary> /// Constructs a new debounce timer /// </summary> /// <param name="action">The action to run</param> /// <param name="delay">The delay between each run</param> /// <param name="notify">Notify on construction</param> public DebounceTimerRepeat(Action action, TimeSpan delay, bool notify = false) { if (delay < TimeSpan.FromMilliseconds(1)) throw new ArgumentOutOfRangeException("The delay must be at least one millisecond"); m_delay = delay; m_action = action ?? throw new ArgumentNullException(nameof(action)); if (notify) Notify(); } /// <summary> /// Triggers the timer and runs the action after the timer has expired /// </summary> /// <param name="condition">A flag used to choose if the notification should be triggered</param> /// <returns><c>true</c> if the signal was used, <c>false</c> if the signal was ignored</returns> public bool Notify(bool condition = true) { if (!condition) return false; // Register that we want to run System.Threading.Interlocked.Increment(ref m_reactivate); // As we read/write the m_runner variable, acquire the lock lock(m_lock) { // Check if we are not running, // the IsCompleted check guards against a crashed task if (m_runner == null || m_runner.IsCompleted) { m_runner = Task.Delay(m_delay).ContinueWith(_ => { // Note that the lock is NOT taken when // this method runs // Clear any requests prior to running the action System.Threading.Interlocked.Exchange(ref m_reactivate, 0); try { m_action(); } finally { // Check if any new requests are recorded while running if (System.Threading.Interlocked.Exchange(ref m_reactivate, 0) != 0) { // Prematurely signal that we have completed lock(m_lock) m_runner = null; // Then call notify, when we know that the runner is null Notify(true); } } }); return true; } } return false; } } /// <summary> /// A debounce timer that runs on first notification, /// and then ignores subsequent notifications until a /// certain period /// </summary> public class DebounceTimerRatelimit : IDebounceTimer { /// <summary> /// The time when a new runner is accepted /// </summary> private DateTime m_ignoreUntil; /// <summary> /// The lock guarding the runner /// </summary> private readonly object m_lock = new object(); /// <summary> /// The action to run /// </summary> private readonly Action m_action; /// <summary> /// The delay between each run /// </summary> private readonly TimeSpan m_delay; /// <summary> /// Constructs a new debounce timer /// </summary> /// <param name="action">The action to run</param> /// <param name="delay">The delay between each run</param> /// <param name="notify">Notify on construction</param> public DebounceTimerRatelimit(Action action, TimeSpan delay, bool notify = false) { if (delay < TimeSpan.FromMilliseconds(1)) throw new ArgumentOutOfRangeException("The delay must be at least one millisecond"); m_delay = delay; m_action = action ?? throw new ArgumentNullException(nameof(action)); m_ignoreUntil = DateTime.Now.AddSeconds(-1); if (notify) Notify(); } /// <summary> /// Triggers the timer and runs the action after the timer has expired /// </summary> /// <param name="condition">A flag used to choose if the notification should be triggered</param> /// <returns><c>true</c> if the signal was used, <c>false</c> if the signal was ignored</returns> public bool Notify(bool condition = true) { if (!condition) return false; if (DateTime.Now > m_ignoreUntil) { // Variable to allow running the action without holding the lock var runnotify = false; lock(m_lock) { if (DateTime.Now > m_ignoreUntil) { m_ignoreUntil = DateTime.Now + m_delay; runnotify = true; } } if (runnotify) { m_action(); return true; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Cryptography; using Internal.NativeCrypto; using System.IO; namespace System.Security.Cryptography { public sealed class DSACryptoServiceProvider : DSA, ICspAsymmetricAlgorithm { private const int SHA1_HASHSIZE = 20; private readonly DSA _impl; private bool _publicOnly; private static KeySizes[] s_legalKeySizes = { new KeySizes(512, 1024, 64) // Use the same values as Csp Windows because the _impl has different values (512, 3072, 64) }; public DSACryptoServiceProvider() : base() { // This class wraps DSA _impl = DSA.Create(); KeySize = 1024; } public DSACryptoServiceProvider(int dwKeySize) : base() { if (dwKeySize < 0) throw new ArgumentOutOfRangeException(nameof(dwKeySize), SR.ArgumentOutOfRange_NeedNonNegNum); // This class wraps DSA _impl = DSA.Create(); KeySize = dwKeySize; } public DSACryptoServiceProvider(int dwKeySize, CspParameters parameters) { throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspParameters))); } public DSACryptoServiceProvider(CspParameters parameters) { throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspParameters))); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of DSACryptoServiceProvider")] public override byte[] CreateSignature(byte[] rgbHash) => _impl.CreateSignature(rgbHash); public override bool TryCreateSignature(ReadOnlySpan<byte> hash, Span<byte> destination, out int bytesWritten) => _impl.TryCreateSignature(hash, destination, out bytesWritten); public CspKeyContainerInfo CspKeyContainerInfo { get { throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspKeyContainerInfo))); } } protected override void Dispose(bool disposing) { if (disposing) { _impl.Dispose(); base.Dispose(disposing); } } public byte[] ExportCspBlob(bool includePrivateParameters) { DSAParameters parameters = ExportParameters(includePrivateParameters); return parameters.ToKeyBlob(); } public override DSAParameters ExportParameters(bool includePrivateParameters) => _impl.ExportParameters(includePrivateParameters); public override void FromXmlString(string xmlString) => _impl.FromXmlString(xmlString); protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { if (hashAlgorithm != HashAlgorithmName.SHA1) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); return AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm); } protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { if (hashAlgorithm != HashAlgorithmName.SHA1) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); return AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm); } protected override bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { if (hashAlgorithm != HashAlgorithmName.SHA1) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); return AsymmetricAlgorithmHelpers.TryHashData(data, destination, hashAlgorithm, out bytesWritten); } public void ImportCspBlob(byte[] keyBlob) { DSAParameters parameters = keyBlob.ToDSAParameters(!IsPublic(keyBlob), null); ImportParameters(parameters); } public override void ImportParameters(DSAParameters parameters) { // Although _impl supports key sizes > 1024, limit here for compat. if (parameters.Y != null && parameters.Y.Length > 1024 / 8) throw new CryptographicException(SR.Argument_InvalidValue); _impl.ImportParameters(parameters); _publicOnly = (parameters.X == null); } public override string KeyExchangeAlgorithm => _impl.KeyExchangeAlgorithm; public override int KeySize { get { return _impl.KeySize; } set { // Perform the check here because LegalKeySizes are more restrictive here than _impl if (!value.IsLegalSize(s_legalKeySizes)) throw new CryptographicException(SR.Cryptography_InvalidKeySize); _impl.KeySize = value; } } public override KeySizes[] LegalKeySizes => s_legalKeySizes.CloneKeySizesArray(); // PersistKeyInCsp has no effect in Unix public bool PersistKeyInCsp { get; set; } public bool PublicOnly { get { return _publicOnly; } } public override string SignatureAlgorithm => "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; public byte[] SignData(byte[] buffer) { return _impl.SignData(buffer, HashAlgorithmName.SHA1); } public byte[] SignData(byte[] buffer, int offset, int count) { return _impl.SignData(buffer, offset, count, HashAlgorithmName.SHA1); } public byte[] SignData(Stream inputStream) { return _impl.SignData(inputStream, HashAlgorithmName.SHA1); } public override string ToXmlString(bool includePrivateParameters) => _impl.ToXmlString(includePrivateParameters); public override byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { if (hashAlgorithm != HashAlgorithmName.SHA1) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); return _impl.SignData(data, offset, count, hashAlgorithm); } public override byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm) { if (hashAlgorithm != HashAlgorithmName.SHA1) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); return _impl.SignData(data, hashAlgorithm); } public override bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { if (hashAlgorithm != HashAlgorithmName.SHA1) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); return _impl.TrySignData(data, destination, hashAlgorithm, out bytesWritten); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of DSACryptoServiceProvider")] public byte[] SignHash(byte[] rgbHash, string str) { if (rgbHash == null) throw new ArgumentNullException(nameof(rgbHash)); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); if (rgbHash.Length != SHA1_HASHSIZE) throw new CryptographicException(string.Format(SR.Cryptography_InvalidHashSize, "SHA1", SHA1_HASHSIZE)); // Only SHA1 allowed; the default value is SHA1 if (str != null && string.Compare(str, "SHA1", StringComparison.OrdinalIgnoreCase) != 0) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, str); return CreateSignature(rgbHash); } public bool VerifyData(byte[] rgbData, byte[] rgbSignature) => _impl.VerifyData(rgbData, rgbSignature, HashAlgorithmName.SHA1); public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { if (rgbHash == null) throw new ArgumentNullException(nameof(rgbHash)); if (rgbSignature == null) throw new ArgumentNullException(nameof(rgbSignature)); // For compat with Windows, no check for rgbHash.Length != SHA1_HASHSIZE // Only SHA1 allowed; the default value is SHA1 if (str != null && string.Compare(str, "SHA1", StringComparison.OrdinalIgnoreCase) != 0) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, str); return _impl.VerifySignature(rgbHash, rgbSignature); } public override bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm) { if (hashAlgorithm != HashAlgorithmName.SHA1) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); return _impl.VerifyData(data, offset, count, signature, hashAlgorithm); } public override bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm) { if (hashAlgorithm != HashAlgorithmName.SHA1) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); return _impl.VerifyData(data, signature, hashAlgorithm); } public override bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm) { if (hashAlgorithm != HashAlgorithmName.SHA1) throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); return _impl.VerifyData(data, signature, hashAlgorithm); } public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) => _impl.VerifySignature(rgbHash, rgbSignature); public override bool VerifySignature(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature) => _impl.VerifySignature(hash, signature); // UseMachineKeyStore has no effect in Unix public static bool UseMachineKeyStore { get; set; } /// <summary> /// Find whether a DSS key blob is public. /// </summary> private static bool IsPublic(byte[] keyBlob) { if (keyBlob == null) throw new ArgumentNullException(nameof(keyBlob)); // The CAPI DSS public key representation consists of the following sequence: // - BLOBHEADER (the first byte is bType) // - DSSPUBKEY or DSSPUBKEY_VER3 (the first field is the magic field) // The first byte should be PUBLICKEYBLOB if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB) { return false; } // Magic should be DSS_MAGIC or DSS_PUB_MAGIC_VER3 if ((keyBlob[11] != 0x31 && keyBlob[11] != 0x33) || keyBlob[10] != 0x53 || keyBlob[9] != 0x53 || keyBlob[8] != 0x44) { return false; } return true; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using WebApiDocumentation.HelpPage.Areas.HelpPage.ModelDescriptions; using WebApiDocumentation.HelpPage.Areas.HelpPage.Models; namespace WebApiDocumentation.HelpPage.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.Serialization; using System.Web; using System.Web.Configuration; using System.Xml.Linq; using MarkdownSharp; using NServiceKit.Common.ServiceModel; using NServiceKit.Common.Utils; using NServiceKit.Common.Web; using NServiceKit.Configuration; using NServiceKit.Logging; using NServiceKit.Logging.Support.Logging; using NServiceKit.Markdown; using NServiceKit.ServiceHost; using NServiceKit.ServiceModel; using NServiceKit.Text; using NServiceKit.WebHost.Endpoints.Extensions; using NServiceKit.WebHost.Endpoints.Support; namespace NServiceKit.WebHost.Endpoints { /// <summary>An endpoint host configuration.</summary> public class EndpointHostConfig { private static ILog log = LogManager.GetLogger(typeof(EndpointHostConfig)); /// <summary>The public key.</summary> public static readonly string PublicKey = "<RSAKeyValue><Modulus>xRzMrP3m+3kvT6239OP1YuWIfc/S7qF5NJiPe2/kXnetXiuYtSL4bQRIX1qYh4Cz+dXqZE/sNGJJ4jl2iJQa1tjp+rK28EG6gcuTDHJdvOBBF+aSwJy1MSiT8D0KtP6pe2uvjl9m3jZP/8uRePZTSkt/GjlPOk85JXzOsyzemlaLFiJoGImGvp8dw8vQ7jzA3Ynmywpt5OQxklJfrfALHJ93ny1M5lN5Q+bGPEHLXNCXfF05EA0l9mZpa4ouicYvlbY/OAwefFXIwPQN9ER6Pu7Eq9XWLvnh1YUH8HDckuKK+ESWbAuOgnVbUDEF1BreoWutJ//a/oLDR87Q36cmwQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; /// <summary>.</summary> public static readonly string LicensePublicKey = "<RSAKeyValue><Modulus>19kx2dJoOIrMYypMTf8ssiCALJ7RS/Iz2QG0rJtYJ2X0+GI+NrgOCapkh/9aDVBieobdClnuBgW08C5QkfBdLRqsptiSu50YIqzVaNBMwZPT0e7Ke02L/fV/M/fVPsolHwzMstKhdWGdK8eNLF4SsLEcvnb79cx3/GnZbXku/ro5eOrTseKL3s4nM4SdMRNn7rEAU0o0Ijb3/RQbhab8IIRB4pHwk1mB+j/mcAQAtMerwpHfwpEBLWlQyVpu0kyKJCEkQjbaPzvfglDRpyBOT5GMUnrcTT/sBr5kSJYpYrgHnA5n4xJnvrnyFqdzXwgGFlikRTbc60pk1cQEWcHgYw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; /// <summary>The skip path validation.</summary> public static bool SkipPathValidation = false; /// <summary> /// Use: \[Route\("[^\/] regular expression to find violating routes in your sln /// </summary> public static bool SkipRouteValidation = false; /// <summary>Full pathname of the service kit file.</summary> public static string NServiceKitPath = null; private static EndpointHostConfig instance; /// <summary>Gets the instance.</summary> /// /// <value>The instance.</value> public static EndpointHostConfig Instance { get { if (instance == null) { instance = new EndpointHostConfig { MetadataTypesConfig = new MetadataTypesConfig(addDefaultXmlNamespace: "http://schemas.NServiceKit.net/types"), WsdlServiceNamespace = "http://schemas.NServiceKit.net/types", WsdlSoapActionNamespace = "http://schemas.NServiceKit.net/types", MetadataPageBodyHtml = @"<br /> <h3><a href=""https://github.com/NServiceKit/NServiceKit/wiki/Clients-overview"">Clients Overview</a></h3>", MetadataOperationPageBodyHtml = @"<br /> <h3><a href=""https://github.com/NServiceKit/NServiceKit/wiki/Clients-overview"">Clients Overview</a></h3>", MetadataCustomPath = "Views/Templates/Metadata/", UseCustomMetadataTemplates = false, LogFactory = new NullLogFactory(), EnableAccessRestrictions = true, WebHostPhysicalPath = "~".MapServerPath(), NServiceKitHandlerFactoryPath = NServiceKitPath, MetadataRedirectPath = null, DefaultContentType = null, AllowJsonpRequests = true, AllowRouteContentTypeExtensions = true, AllowNonHttpOnlyCookies = false, UseHttpsLinks = false, DebugMode = false, DefaultDocuments = new List<string> { "default.htm", "default.html", "default.cshtml", "default.md", "index.htm", "index.html", "default.aspx", "default.ashx", }, GlobalResponseHeaders = new Dictionary<string, string> { { "X-Powered-By", Env.ServerUserAgent } }, IgnoreFormatsInMetadata = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase), AllowFileExtensions = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "js", "css", "htm", "html", "shtm", "txt", "xml", "rss", "csv", "pdf", "jpg", "jpeg", "gif", "png", "bmp", "ico", "tif", "tiff", "svg", "avi", "divx", "m3u", "mov", "mp3", "mpeg", "mpg", "qt", "vob", "wav", "wma", "wmv", "flv", "xap", "xaml", "ogg", "mp4", "webm", "eot", "ttf", "woff" }, DebugAspNetHostEnvironment = Env.IsMono ? "FastCGI" : "IIS7", DebugHttpListenerHostEnvironment = Env.IsMono ? "XSP" : "WebServer20", EnableFeatures = Feature.All, WriteErrorsToResponse = true, ReturnsInnerException = true, MarkdownOptions = new MarkdownOptions(), MarkdownBaseType = typeof(MarkdownViewBase), MarkdownGlobalHelpers = new Dictionary<string, Type>(), HtmlReplaceTokens = new Dictionary<string, string>(), AddMaxAgeForStaticMimeTypes = new Dictionary<string, TimeSpan> { { "image/gif", TimeSpan.FromHours(1) }, { "image/png", TimeSpan.FromHours(1) }, { "image/jpeg", TimeSpan.FromHours(1) }, }, AppendUtf8CharsetOnContentTypes = new HashSet<string> { ContentType.Json, }, RawHttpHandlers = new List<Func<IHttpRequest, IHttpHandler>>(), RouteNamingConventions = new List<RouteNamingConventionDelegate> { RouteNamingConvention.WithRequestDtoName, RouteNamingConvention.WithMatchingAttributes, RouteNamingConvention.WithMatchingPropertyNames }, CustomHttpHandlers = new Dictionary<HttpStatusCode, INServiceKitHttpHandler>(), GlobalHtmlErrorHttpHandler = null, MapExceptionToStatusCode = new Dictionary<Type, int>(), OnlySendSessionCookiesSecurely = false, RestrictAllCookiesToDomain = null, DefaultJsonpCacheExpiration = new TimeSpan(0, 20, 0), MetadataVisibility = EndpointAttributes.Any, Return204NoContentForEmptyResponse = true, AllowPartialResponses = true, AllowAclUrlReservation = true, IgnoreWarningsOnPropertyNames = new List<string> { "format", "callback", "debug", "_", "authsecret" } }; if (instance.NServiceKitHandlerFactoryPath == null) { InferHttpHandlerPath(); } } return instance; } } /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.EndpointHostConfig class.</summary> /// /// <param name="serviceName"> The name of the service.</param> /// <param name="serviceManager">The service manager.</param> public EndpointHostConfig(string serviceName, ServiceManager serviceManager) : this() { this.ServiceName = serviceName; this.ServiceManager = serviceManager; } /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.EndpointHostConfig class.</summary> public EndpointHostConfig() { if (instance == null) return; //Get a copy of the singleton already partially configured this.MetadataTypesConfig = instance.MetadataTypesConfig; this.WsdlServiceNamespace = instance.WsdlServiceNamespace; this.WsdlSoapActionNamespace = instance.WsdlSoapActionNamespace; this.MetadataPageBodyHtml = instance.MetadataPageBodyHtml; this.MetadataOperationPageBodyHtml = instance.MetadataOperationPageBodyHtml; this.MetadataCustomPath = instance.MetadataCustomPath; this.UseCustomMetadataTemplates = instance.UseCustomMetadataTemplates; this.EnableAccessRestrictions = instance.EnableAccessRestrictions; this.ServiceEndpointsMetadataConfig = instance.ServiceEndpointsMetadataConfig; this.LogFactory = instance.LogFactory; this.EnableAccessRestrictions = instance.EnableAccessRestrictions; this.WebHostUrl = instance.WebHostUrl; this.WebHostPhysicalPath = instance.WebHostPhysicalPath; this.DefaultRedirectPath = instance.DefaultRedirectPath; this.MetadataRedirectPath = instance.MetadataRedirectPath; this.NServiceKitHandlerFactoryPath = instance.NServiceKitHandlerFactoryPath; this.DefaultContentType = instance.DefaultContentType; this.AllowJsonpRequests = instance.AllowJsonpRequests; this.AllowRouteContentTypeExtensions = instance.AllowRouteContentTypeExtensions; this.DebugMode = instance.DebugMode; this.DefaultDocuments = instance.DefaultDocuments; this.GlobalResponseHeaders = instance.GlobalResponseHeaders; this.IgnoreFormatsInMetadata = instance.IgnoreFormatsInMetadata; this.AllowFileExtensions = instance.AllowFileExtensions; this.EnableFeatures = instance.EnableFeatures; this.WriteErrorsToResponse = instance.WriteErrorsToResponse; this.ReturnsInnerException = instance.ReturnsInnerException; this.MarkdownOptions = instance.MarkdownOptions; this.MarkdownBaseType = instance.MarkdownBaseType; this.MarkdownGlobalHelpers = instance.MarkdownGlobalHelpers; this.HtmlReplaceTokens = instance.HtmlReplaceTokens; this.AddMaxAgeForStaticMimeTypes = instance.AddMaxAgeForStaticMimeTypes; this.AppendUtf8CharsetOnContentTypes = instance.AppendUtf8CharsetOnContentTypes; this.RawHttpHandlers = instance.RawHttpHandlers; this.RouteNamingConventions = instance.RouteNamingConventions; this.CustomHttpHandlers = instance.CustomHttpHandlers; this.GlobalHtmlErrorHttpHandler = instance.GlobalHtmlErrorHttpHandler; this.MapExceptionToStatusCode = instance.MapExceptionToStatusCode; this.OnlySendSessionCookiesSecurely = instance.OnlySendSessionCookiesSecurely; this.RestrictAllCookiesToDomain = instance.RestrictAllCookiesToDomain; this.DefaultJsonpCacheExpiration = instance.DefaultJsonpCacheExpiration; this.MetadataVisibility = instance.MetadataVisibility; this.Return204NoContentForEmptyResponse = Return204NoContentForEmptyResponse; this.AllowNonHttpOnlyCookies = instance.AllowNonHttpOnlyCookies; this.AllowPartialResponses = instance.AllowPartialResponses; this.IgnoreWarningsOnPropertyNames = instance.IgnoreWarningsOnPropertyNames; this.PreExecuteServiceFilter = instance.PreExecuteServiceFilter; this.PostExecuteServiceFilter = instance.PostExecuteServiceFilter; this.FallbackRestPath = instance.FallbackRestPath; this.AllowAclUrlReservation = instance.AllowAclUrlReservation; this.AdminAuthSecret = instance.AdminAuthSecret; } /// <summary>Gets application configuration path.</summary> /// /// <returns>The application configuration path.</returns> public static string GetAppConfigPath() { if (EndpointHost.AppHost == null) return null; var configPath = "~/web.config".MapHostAbsolutePath(); if (File.Exists(configPath)) return configPath; configPath = "~/Web.config".MapHostAbsolutePath(); //*nix FS FTW! if (File.Exists(configPath)) return configPath; var appHostDll = new FileInfo(EndpointHost.AppHost.GetType().Assembly.Location).Name; configPath = "~/{0}.config".Fmt(appHostDll).MapAbsolutePath(); return File.Exists(configPath) ? configPath : null; } const string NamespacesAppSettingsKey = "NServiceKit.razor.namespaces"; private static HashSet<string> razorNamespaces; /// <summary>Gets the razor namespaces.</summary> /// /// <value>The razor namespaces.</value> public static HashSet<string> RazorNamespaces { get { if (razorNamespaces != null) return razorNamespaces; razorNamespaces = new HashSet<string>(); //Infer from <system.web.webPages.razor> - what VS.NET's intell-sense uses var configPath = GetAppConfigPath(); if (configPath != null) { var xml = configPath.ReadAllText(); var doc = XElement.Parse(xml); doc.AnyElement("system.web.webPages.razor") .AnyElement("pages") .AnyElement("namespaces") .AllElements("add").ToList() .ForEach(x => razorNamespaces.Add(x.AnyAttribute("namespace").Value)); } //E.g. <add key="NServiceKit.razor.namespaces" value="System,NServiceKit.Text" /> if (ConfigUtils.GetNullableAppSetting(NamespacesAppSettingsKey) != null) { ConfigUtils.GetListFromAppSetting(NamespacesAppSettingsKey) .ForEach(x => razorNamespaces.Add(x)); } //log.Debug("Loaded Razor Namespaces: in {0}: {1}: {2}" // .Fmt(configPath, "~/Web.config".MapHostAbsolutePath(), razorNamespaces.Dump())); return razorNamespaces; } } private static System.Configuration.Configuration GetAppConfig() { Assembly entryAssembly; //Read the user-defined path in the Web.Config if (EndpointHost.AppHost is AppHostBase) return WebConfigurationManager.OpenWebConfiguration("~/"); if ((entryAssembly = Assembly.GetEntryAssembly()) != null) return ConfigurationManager.OpenExeConfiguration(entryAssembly.Location); return null; } private static void InferHttpHandlerPath() { try { var config = GetAppConfig(); if (config == null) return; SetPathsFromConfiguration(config, null); if (instance.MetadataRedirectPath == null) { foreach (ConfigurationLocation location in config.Locations) { SetPathsFromConfiguration(location.OpenConfiguration(), (location.Path ?? "").ToLower()); if (instance.MetadataRedirectPath != null) { break; } } } if (!SkipPathValidation && instance.MetadataRedirectPath == null) { throw new ConfigurationErrorsException( "Unable to infer NServiceKit's <httpHandler.Path/> from the Web.Config\n" + "Check with http://www.NServiceKit.net/NServiceKit.Hello/ to ensure you have configured NServiceKit properly.\n" + "Otherwise you can explicitly set your httpHandler.Path by setting: EndpointHostConfig.NServiceKitPath"); } } catch (Exception) { } } private static void SetPathsFromConfiguration(System.Configuration.Configuration config, string locationPath) { if (config == null) return; //standard config var handlersSection = config.GetSection("system.web/httpHandlers") as HttpHandlersSection; if (handlersSection != null) { for (var i = 0; i < handlersSection.Handlers.Count; i++) { var httpHandler = handlersSection.Handlers[i]; if (!httpHandler.Type.StartsWith("NServiceKit")) continue; SetPaths(httpHandler.Path, locationPath); break; } } //IIS7+ integrated mode system.webServer/handlers var pathsNotSet = instance.MetadataRedirectPath == null; if (pathsNotSet) { var webServerSection = config.GetSection("system.webServer"); if (webServerSection != null) { var rawXml = webServerSection.SectionInformation.GetRawXml(); if (!String.IsNullOrEmpty(rawXml)) { SetPaths(ExtractHandlerPathFromWebServerConfigurationXml(rawXml), locationPath); } } //In some MVC Hosts auto-inferencing doesn't work, in these cases assume the most likely default of "/api" path pathsNotSet = instance.MetadataRedirectPath == null; if (pathsNotSet) { var isMvcHost = Type.GetType("System.Web.Mvc.Controller") != null; if (isMvcHost) { SetPaths("api", null); } } } } private static void SetPaths(string handlerPath, string locationPath) { if (handlerPath == null) return; if (locationPath == null) { handlerPath = handlerPath.Replace("*", String.Empty); } instance.NServiceKitHandlerFactoryPath = locationPath ?? (String.IsNullOrEmpty(handlerPath) ? null : handlerPath); instance.MetadataRedirectPath = PathUtils.CombinePaths( null != locationPath ? instance.NServiceKitHandlerFactoryPath : handlerPath , "metadata"); } private static string ExtractHandlerPathFromWebServerConfigurationXml(string rawXml) { return XDocument.Parse(rawXml).Root.Element("handlers") .Descendants("add") .Where(handler => EnsureHandlerTypeAttribute(handler).StartsWith("NServiceKit")) .Select(handler => handler.Attribute("path").Value) .FirstOrDefault(); } private static string EnsureHandlerTypeAttribute(XElement handler) { if (handler.Attribute("type") != null && !String.IsNullOrEmpty(handler.Attribute("type").Value)) { return handler.Attribute("type").Value; } return String.Empty; } /// <summary>Gets the manager for service.</summary> /// /// <value>The service manager.</value> public ServiceManager ServiceManager { get; internal set; } /// <summary>Gets the metadata.</summary> /// /// <value>The metadata.</value> public ServiceMetadata Metadata { get { return ServiceManager.Metadata; } } /// <summary>Gets the service controller.</summary> /// /// <value>The service controller.</value> public IServiceController ServiceController { get { return ServiceManager.ServiceController; } } /// <summary>Gets or sets the metadata types configuration.</summary> /// /// <value>The metadata types configuration.</value> public MetadataTypesConfig MetadataTypesConfig { get; set; } /// <summary>Gets or sets the wsdl service namespace.</summary> /// /// <value>The wsdl service namespace.</value> public string WsdlServiceNamespace { get; set; } /// <summary>Gets or sets the wsdl SOAP action namespace.</summary> /// /// <value>The wsdl SOAP action namespace.</value> public string WsdlSoapActionNamespace { get; set; } private EndpointAttributes metadataVisibility; /// <summary>Gets or sets the metadata visibility.</summary> /// /// <value>The metadata visibility.</value> public EndpointAttributes MetadataVisibility { get { return metadataVisibility; } set { metadataVisibility = value.ToAllowedFlagsSet(); } } /// <summary>Gets or sets the metadata page body HTML.</summary> /// /// <value>The metadata page body HTML.</value> public string MetadataPageBodyHtml { get; set; } /// <summary>Gets or sets the metadata operation page body HTML.</summary> /// /// <value>The metadata operation page body HTML.</value> public string MetadataOperationPageBodyHtml { get; set; } /// <summary>Gets or sets the full pathname of the metadata custom file.</summary> /// /// <value>The full pathname of the metadata custom file.</value> public string MetadataCustomPath { get; set; } /// <summary>Gets or sets a value indicating whether this object use custom metadata templates.</summary> /// /// <value>true if use custom metadata templates, false if not.</value> public bool UseCustomMetadataTemplates { get; set; } /// <summary>Gets or sets the name of the service.</summary> /// /// <value>The name of the service.</value> public string ServiceName { get; set; } /// <summary>Gets or sets the name of the SOAP service.</summary> /// /// <value>The name of the SOAP service.</value> public string SoapServiceName { get; set; } /// <summary>Gets or sets the default content type.</summary> /// /// <value>The default content type.</value> public string DefaultContentType { get; set; } /// <summary>Gets or sets a value indicating whether we allow jsonp requests.</summary> /// /// <value>true if allow jsonp requests, false if not.</value> public bool AllowJsonpRequests { get; set; } /// <summary>Gets or sets a value indicating whether we allow route content type extensions.</summary> /// /// <value>true if allow route content type extensions, false if not.</value> public bool AllowRouteContentTypeExtensions { get; set; } /// <summary>Gets or sets a value indicating whether the debug mode.</summary> /// /// <value>true if debug mode, false if not.</value> public bool DebugMode { get; set; } /// <summary>Gets or sets a value indicating whether the debug only return request information.</summary> /// /// <value>true if debug only return request information, false if not.</value> public bool DebugOnlyReturnRequestInfo { get; set; } /// <summary>Gets or sets the debug ASP net host environment.</summary> /// /// <value>The debug ASP net host environment.</value> public string DebugAspNetHostEnvironment { get; set; } /// <summary>Gets or sets the debug HTTP listener host environment.</summary> /// /// <value>The debug HTTP listener host environment.</value> public string DebugHttpListenerHostEnvironment { get; set; } /// <summary>Gets the default documents.</summary> /// /// <value>The default documents.</value> public List<string> DefaultDocuments { get; private set; } /// <summary>Gets a list of names of the ignore warnings on properties.</summary> /// /// <value>A list of names of the ignore warnings on properties.</value> public List<string> IgnoreWarningsOnPropertyNames { get; private set; } /// <summary>Gets or sets the ignore formats in metadata.</summary> /// /// <value>The ignore formats in metadata.</value> public HashSet<string> IgnoreFormatsInMetadata { get; set; } /// <summary>Gets or sets the allow file extensions.</summary> /// /// <value>The allow file extensions.</value> public HashSet<string> AllowFileExtensions { get; set; } /// <summary>Gets or sets URL of the web host.</summary> /// /// <value>The web host URL.</value> public string WebHostUrl { get; set; } /// <summary>Gets or sets the full pathname of the web host physical file.</summary> /// /// <value>The full pathname of the web host physical file.</value> public string WebHostPhysicalPath { get; set; } /// <summary>Gets or sets the full pathname of the service kit handler factory file.</summary> /// /// <value>The full pathname of the service kit handler factory file.</value> public string NServiceKitHandlerFactoryPath { get; set; } /// <summary>Gets or sets the default redirect path.</summary> /// /// <value>The default redirect path.</value> public string DefaultRedirectPath { get; set; } /// <summary>Gets or sets the full pathname of the metadata redirect file.</summary> /// /// <value>The full pathname of the metadata redirect file.</value> public string MetadataRedirectPath { get; set; } /// <summary>Gets or sets the service endpoints metadata configuration.</summary> /// /// <value>The service endpoints metadata configuration.</value> public ServiceEndpointsMetadataConfig ServiceEndpointsMetadataConfig { get; set; } /// <summary>Gets or sets the log factory.</summary> /// /// <value>The log factory.</value> public ILogFactory LogFactory { get; set; } /// <summary>Gets or sets a value indicating whether the access restrictions is enabled.</summary> /// /// <value>true if enable access restrictions, false if not.</value> public bool EnableAccessRestrictions { get; set; } /// <summary>Gets or sets a value indicating whether this object use bcl JSON serializers.</summary> /// /// <value>true if use bcl JSON serializers, false if not.</value> public bool UseBclJsonSerializers { get; set; } /// <summary>Gets or sets the global response headers.</summary> /// /// <value>The global response headers.</value> public Dictionary<string, string> GlobalResponseHeaders { get; set; } /// <summary>Gets or sets the enable features.</summary> /// /// <value>The enable features.</value> public Feature EnableFeatures { get; set; } /// <summary>Gets or sets a value indicating whether the returns inner exception.</summary> /// /// <value>true if returns inner exception, false if not.</value> public bool ReturnsInnerException { get; set; } /// <summary>Gets or sets a value indicating whether the errors to response should be written.</summary> /// /// <value>true if write errors to response, false if not.</value> public bool WriteErrorsToResponse { get; set; } /// <summary>Gets or sets options for controlling the markdown.</summary> /// /// <value>Options that control the markdown.</value> public MarkdownOptions MarkdownOptions { get; set; } /// <summary>Gets or sets the type of the markdown base.</summary> /// /// <value>The type of the markdown base.</value> public Type MarkdownBaseType { get; set; } /// <summary>Gets or sets the markdown global helpers.</summary> /// /// <value>The markdown global helpers.</value> public Dictionary<string, Type> MarkdownGlobalHelpers { get; set; } /// <summary>Gets or sets the HTML replace tokens.</summary> /// /// <value>The HTML replace tokens.</value> public Dictionary<string, string> HtmlReplaceTokens { get; set; } /// <summary>Gets or sets a list of types of the append UTF 8 charset on contents.</summary> /// /// <value>A list of types of the append UTF 8 charset on contents.</value> public HashSet<string> AppendUtf8CharsetOnContentTypes { get; set; } /// <summary>Gets or sets a list of types of the add maximum age for static mimes.</summary> /// /// <value>A list of types of the add maximum age for static mimes.</value> public Dictionary<string, TimeSpan> AddMaxAgeForStaticMimeTypes { get; set; } /// <summary>Gets or sets the raw HTTP handlers.</summary> /// /// <value>The raw HTTP handlers.</value> public List<Func<IHttpRequest, IHttpHandler>> RawHttpHandlers { get; set; } /// <summary>Gets or sets the route naming conventions.</summary> /// /// <value>The route naming conventions.</value> public List<RouteNamingConventionDelegate> RouteNamingConventions { get; set; } /// <summary>Gets or sets the custom HTTP handlers.</summary> /// /// <value>The custom HTTP handlers.</value> public Dictionary<HttpStatusCode, INServiceKitHttpHandler> CustomHttpHandlers { get; set; } /// <summary>Gets or sets the global HTML error HTTP handler.</summary> /// /// <value>The global HTML error HTTP handler.</value> public INServiceKitHttpHandler GlobalHtmlErrorHttpHandler { get; set; } /// <summary>Gets or sets the map exception to status code.</summary> /// /// <value>The map exception to status code.</value> public Dictionary<Type, int> MapExceptionToStatusCode { get; set; } /// <summary>Gets or sets a value indicating whether the only send session cookies securely.</summary> /// /// <value>true if only send session cookies securely, false if not.</value> public bool OnlySendSessionCookiesSecurely { get; set; } /// <summary>Gets or sets the restrict all cookies to domain.</summary> /// /// <value>The restrict all cookies to domain.</value> public string RestrictAllCookiesToDomain { get; set; } /// <summary>Gets or sets the default jsonp cache expiration.</summary> /// /// <value>The default jsonp cache expiration.</value> public TimeSpan DefaultJsonpCacheExpiration { get; set; } /// <summary>Gets or sets a value indicating whether the return 204 no content for empty response.</summary> /// /// <value>true if return 204 no content for empty response, false if not.</value> public bool Return204NoContentForEmptyResponse { get; set; } /// <summary>Gets or sets a value indicating whether we allow partial responses.</summary> /// /// <value>true if allow partial responses, false if not.</value> public bool AllowPartialResponses { get; set; } /// <summary>Gets or sets a value indicating whether we allow non HTTP only cookies.</summary> /// /// <value>true if allow non HTTP only cookies, false if not.</value> public bool AllowNonHttpOnlyCookies { get; set; } /// <summary>Gets or sets a value indicating whether we allow ACL URL reservation.</summary> /// /// <value>true if allow ACL URL reservation, false if not.</value> public bool AllowAclUrlReservation { get; set; } /// <summary>Gets or sets a value indicating whether this object use HTTPS links.</summary> /// /// <value>true if use HTTPS links, false if not.</value> public bool UseHttpsLinks { get; set; } /// <summary>Gets or sets the admin authentication secret.</summary> /// /// <value>The admin authentication secret.</value> public string AdminAuthSecret { get; set; } private string defaultOperationNamespace; /// <summary>Gets or sets the default operation namespace.</summary> /// /// <value>The default operation namespace.</value> public string DefaultOperationNamespace { get { if (this.defaultOperationNamespace == null) { this.defaultOperationNamespace = GetDefaultNamespace(); } return this.defaultOperationNamespace; } set { this.defaultOperationNamespace = value; } } private string GetDefaultNamespace() { if (!String.IsNullOrEmpty(this.defaultOperationNamespace) || this.ServiceController == null) return null; foreach (var operationType in this.Metadata.RequestTypes) { var attrs = operationType.GetCustomAttributes( typeof(DataContractAttribute), false); if (attrs.Length <= 0) continue; var attr = (DataContractAttribute)attrs[0]; if (String.IsNullOrEmpty(attr.Namespace)) continue; return attr.Namespace; } return null; } /// <summary>Query if 'feature' has feature.</summary> /// /// <param name="feature">The feature.</param> /// /// <returns>true if feature, false if not.</returns> public bool HasFeature(Feature feature) { return (feature & EndpointHost.Config.EnableFeatures) == feature; } /// <summary>Assert features.</summary> /// /// <exception cref="UnauthorizedAccessException">Thrown when an Unauthorized Access error condition occurs.</exception> /// /// <param name="usesFeatures">The uses features.</param> public void AssertFeatures(Feature usesFeatures) { if (EndpointHost.Config.EnableFeatures == Feature.All) return; if (!HasFeature(usesFeatures)) { throw new UnauthorizedAccessException( String.Format("'{0}' Features have been disabled by your administrator", usesFeatures)); } } /// <summary>Unauthorized access.</summary> /// /// <param name="requestAttrs">The request attributes.</param> /// /// <returns>An UnauthorizedAccessException.</returns> public UnauthorizedAccessException UnauthorizedAccess(EndpointAttributes requestAttrs) { return new UnauthorizedAccessException( String.Format("Request with '{0}' is not allowed", requestAttrs)); } /// <summary>Assert content type.</summary> /// /// <param name="contentType">Type of the content.</param> public void AssertContentType(string contentType) { if (EndpointHost.Config.EnableFeatures == Feature.All) return; AssertFeatures(contentType.ToFeature()); } /// <summary>Gets the metadata pages configuration.</summary> /// /// <value>The metadata pages configuration.</value> public MetadataPagesConfig MetadataPagesConfig { get { return new MetadataPagesConfig( Metadata, ServiceEndpointsMetadataConfig, IgnoreFormatsInMetadata, EndpointHost.ContentTypeFilter.ContentTypeFormats.Keys.ToList()); } } /// <summary>Query if 'httpReq' has access to metadata.</summary> /// /// <param name="httpReq">The HTTP request.</param> /// <param name="httpRes">The HTTP resource.</param> /// /// <returns>true if access to metadata, false if not.</returns> public bool HasAccessToMetadata(IHttpRequest httpReq, IHttpResponse httpRes) { if (!HasFeature(Feature.Metadata)) { EndpointHost.Config.HandleErrorResponse(httpReq, httpRes, HttpStatusCode.Forbidden, "Metadata Not Available"); return false; } if (MetadataVisibility != EndpointAttributes.Any) { var actualAttributes = httpReq.GetAttributes(); if ((actualAttributes & MetadataVisibility) != MetadataVisibility) { HandleErrorResponse(httpReq, httpRes, HttpStatusCode.Forbidden, "Metadata Not Visible"); return false; } } return true; } /// <summary>Handles the error response.</summary> /// /// <param name="httpReq"> The HTTP request.</param> /// <param name="httpRes"> The HTTP resource.</param> /// <param name="errorStatus"> The error status.</param> /// <param name="errorStatusDescription">Information describing the error status.</param> public void HandleErrorResponse(IHttpRequest httpReq, IHttpResponse httpRes, HttpStatusCode errorStatus, string errorStatusDescription = null) { if (httpRes.IsClosed) return; httpRes.StatusDescription = errorStatusDescription; var handler = GetHandlerForErrorStatus(errorStatus); handler.ProcessRequest(httpReq, httpRes, httpReq.OperationName); } /// <summary>Gets handler for error status.</summary> /// /// <param name="errorStatus">The error status.</param> /// /// <returns>The handler for error status.</returns> public INServiceKitHttpHandler GetHandlerForErrorStatus(HttpStatusCode errorStatus) { var httpHandler = GetCustomErrorHandler(errorStatus); switch (errorStatus) { case HttpStatusCode.Forbidden: return httpHandler ?? new ForbiddenHttpHandler(); case HttpStatusCode.NotFound: return httpHandler ?? new NotFoundHttpHandler(); } if (CustomHttpHandlers != null) { CustomHttpHandlers.TryGetValue(HttpStatusCode.NotFound, out httpHandler); } return httpHandler ?? new NotFoundHttpHandler(); } /// <summary>Handler, called when the get custom error.</summary> /// /// <param name="errorStatusCode">The error status code.</param> /// /// <returns>The custom error handler.</returns> public INServiceKitHttpHandler GetCustomErrorHandler(int errorStatusCode) { try { return GetCustomErrorHandler((HttpStatusCode)errorStatusCode); } catch { return null; } } /// <summary>Handler, called when the get custom error.</summary> /// /// <param name="errorStatus">The error status.</param> /// /// <returns>The custom error handler.</returns> public INServiceKitHttpHandler GetCustomErrorHandler(HttpStatusCode errorStatus) { INServiceKitHttpHandler httpHandler = null; if (CustomHttpHandlers != null) { CustomHttpHandlers.TryGetValue(errorStatus, out httpHandler); } return httpHandler ?? GlobalHtmlErrorHttpHandler; } /// <summary>Handler, called when the get custom error HTTP.</summary> /// /// <param name="errorStatus">The error status.</param> /// /// <returns>The custom error HTTP handler.</returns> public IHttpHandler GetCustomErrorHttpHandler(HttpStatusCode errorStatus) { var ssHandler = GetCustomErrorHandler(errorStatus); if (ssHandler == null) return null; var httpHandler = ssHandler as IHttpHandler; return httpHandler ?? new NServiceKitHttpHandler(ssHandler); } /// <summary>Gets or sets the pre execute service filter.</summary> /// /// <value>The pre execute service filter.</value> public Action<object, IHttpRequest, IHttpResponse> PreExecuteServiceFilter { get; set; } /// <summary>Gets or sets the post execute service filter.</summary> /// /// <value>The post execute service filter.</value> public Action<object, IHttpRequest, IHttpResponse> PostExecuteServiceFilter { get; set; } /// <summary>Gets or sets the full pathname of the fallback rest file.</summary> /// /// <value>The full pathname of the fallback rest file.</value> public FallbackRestPathDelegate FallbackRestPath { get; set; } /// <summary>Query if 'req' has valid authentication secret.</summary> /// /// <param name="req">The request.</param> /// /// <returns>true if valid authentication secret, false if not.</returns> public bool HasValidAuthSecret(IHttpRequest req) { if (AdminAuthSecret != null) { var authSecret = req.GetParam("authsecret"); return authSecret == EndpointHost.Config.AdminAuthSecret; } return false; } } }
using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AttributeSource = Lucene.Net.Util.AttributeSource; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; /// <summary> /// Abstract class for enumerating a subset of all terms. /// <para/> /// Term enumerations are always ordered by /// <see cref="Comparer"/>. Each term in the enumeration is /// greater than all that precede it. /// <para/><c>Please note:</c> Consumers of this enumeration cannot /// call <c>Seek()</c>, it is forward only; it throws /// <see cref="NotSupportedException"/> when a seeking method /// is called. /// </summary> public abstract class FilteredTermsEnum : TermsEnum { private BytesRef initialSeekTerm = null; private bool doSeek; private BytesRef actualTerm = null; private readonly TermsEnum tenum; /// <summary> /// Return value, if term should be accepted or the iteration should /// <see cref="END"/>. The <c>*_SEEK</c> values denote, that after handling the current term /// the enum should call <see cref="NextSeekTerm(BytesRef)"/> and step forward. </summary> /// <seealso cref="Accept(BytesRef)"/> protected internal enum AcceptStatus { /// <summary> /// Accept the term and position the enum at the next term. </summary> YES, /// <summary> /// Accept the term and advance (<see cref="FilteredTermsEnum.NextSeekTerm(BytesRef)"/>) /// to the next term. /// </summary> YES_AND_SEEK, /// <summary> /// Reject the term and position the enum at the next term. </summary> NO, /// <summary> /// Reject the term and advance (<see cref="FilteredTermsEnum.NextSeekTerm(BytesRef)"/>) /// to the next term. /// </summary> NO_AND_SEEK, /// <summary> /// Reject the term and stop enumerating. </summary> END } /// <summary> /// Return if term is accepted, not accepted or the iteration should ended /// (and possibly seek). /// </summary> protected abstract AcceptStatus Accept(BytesRef term); /// <summary> /// Creates a filtered <see cref="TermsEnum"/> on a terms enum. </summary> /// <param name="tenum"> the terms enumeration to filter. </param> public FilteredTermsEnum(TermsEnum tenum) : this(tenum, true) { } /// <summary> /// Creates a filtered <see cref="TermsEnum"/> on a terms enum. </summary> /// <param name="tenum"> the terms enumeration to filter. </param> /// <param name="startWithSeek"> start with seek </param> public FilteredTermsEnum(TermsEnum tenum, bool startWithSeek) { if (Debugging.AssertsEnabled) Debugging.Assert(tenum != null); this.tenum = tenum; doSeek = startWithSeek; } /// <summary> /// Use this method to set the initial <see cref="BytesRef"/> /// to seek before iterating. This is a convenience method for /// subclasses that do not override <see cref="NextSeekTerm(BytesRef)"/>. /// If the initial seek term is <c>null</c> (default), /// the enum is empty. /// <para/>You can only use this method, if you keep the default /// implementation of <see cref="NextSeekTerm(BytesRef)"/>. /// </summary> protected void SetInitialSeekTerm(BytesRef term) { this.initialSeekTerm = term; } /// <summary> /// On the first call to <see cref="MoveNext()"/> or if <see cref="Accept(BytesRef)"/> returns /// <see cref="AcceptStatus.YES_AND_SEEK"/> or <see cref="AcceptStatus.NO_AND_SEEK"/>, /// this method will be called to eventually seek the underlying <see cref="TermsEnum"/> /// to a new position. /// On the first call, <paramref name="currentTerm"/> will be <c>null</c>, later /// calls will provide the term the underlying enum is positioned at. /// This method returns per default only one time the initial seek term /// and then <c>null</c>, so no repositioning is ever done. /// <para/> /// Override this method, if you want a more sophisticated <see cref="TermsEnum"/>, /// that repositions the iterator during enumeration. /// If this method always returns <c>null</c> the enum is empty. /// <para/><c>Please note:</c> this method should always provide a greater term /// than the last enumerated term, else the behavior of this enum /// violates the contract for <see cref="TermsEnum"/>s. /// </summary> protected virtual BytesRef NextSeekTerm(BytesRef currentTerm) { BytesRef t = initialSeekTerm; initialSeekTerm = null; return t; } /// <summary> /// Returns the related attributes, the returned <see cref="AttributeSource"/> /// is shared with the delegate <see cref="TermsEnum"/>. /// </summary> public override AttributeSource Attributes => tenum.Attributes; public override BytesRef Term => tenum.Term; public override IComparer<BytesRef> Comparer => tenum.Comparer; public override int DocFreq => tenum.DocFreq; public override long TotalTermFreq => tenum.TotalTermFreq; /// <summary> /// this enum does not support seeking! </summary> /// <exception cref="NotSupportedException"> In general, subclasses do not /// support seeking. </exception> public override bool SeekExact(BytesRef term) { throw new NotSupportedException(this.GetType().Name + " does not support seeking"); } /// <summary> /// this enum does not support seeking! </summary> /// <exception cref="NotSupportedException"> In general, subclasses do not /// support seeking. </exception> public override SeekStatus SeekCeil(BytesRef term) { throw new NotSupportedException(this.GetType().Name + " does not support seeking"); } /// <summary> /// this enum does not support seeking! </summary> /// <exception cref="NotSupportedException"> In general, subclasses do not /// support seeking. </exception> public override void SeekExact(long ord) { throw new NotSupportedException(this.GetType().Name + " does not support seeking"); } public override long Ord => tenum.Ord; public override DocsEnum Docs(IBits bits, DocsEnum reuse, DocsFlags flags) { return tenum.Docs(bits, reuse, flags); } public override DocsAndPositionsEnum DocsAndPositions(IBits bits, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { return tenum.DocsAndPositions(bits, reuse, flags); } /// <summary> /// this enum does not support seeking! </summary> /// <exception cref="NotSupportedException"> In general, subclasses do not /// support seeking. </exception> public override void SeekExact(BytesRef term, TermState state) { throw new NotSupportedException(this.GetType().Name + " does not support seeking"); } /// <summary> /// Returns the filtered enums term state /// </summary> public override TermState GetTermState() { if (Debugging.AssertsEnabled) Debugging.Assert(tenum != null); return tenum.GetTermState(); } public override bool MoveNext() { //System.out.println("FTE.next doSeek=" + doSeek); //new Throwable().printStackTrace(System.out); for (; ; ) { // Seek or forward the iterator if (doSeek) { doSeek = false; BytesRef t = NextSeekTerm(actualTerm); //System.out.println(" seek to t=" + (t == null ? "null" : t.utf8ToString()) + " tenum=" + tenum); // Make sure we always seek forward: if (Debugging.AssertsEnabled) Debugging.Assert(actualTerm == null || t == null || Comparer.Compare(t, actualTerm) > 0, () => "curTerm=" + actualTerm + " seekTerm=" + t); if (t == null || tenum.SeekCeil(t) == SeekStatus.END) { // no more terms to seek to or enum exhausted //System.out.println(" return null"); return false; } actualTerm = tenum.Term; //System.out.println(" got term=" + actualTerm.utf8ToString()); } else { if (tenum.MoveNext()) { actualTerm = tenum.Term; } else { // enum exhausted actualTerm = null; return false; } } // check if term is accepted switch (Accept(actualTerm)) { case FilteredTermsEnum.AcceptStatus.YES_AND_SEEK: doSeek = true; // term accepted, but we need to seek so fall-through goto case FilteredTermsEnum.AcceptStatus.YES; case FilteredTermsEnum.AcceptStatus.YES: // term accepted return true; case FilteredTermsEnum.AcceptStatus.NO_AND_SEEK: // invalid term, seek next time doSeek = true; break; case FilteredTermsEnum.AcceptStatus.END: // we are supposed to end the enum return false; } } } [Obsolete("Use MoveNext() and Term instead. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override BytesRef Next() { if (MoveNext()) return actualTerm; return null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Research.CodeAnalysis; using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO.Pipes; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; namespace Microsoft.Research.ClousotPulse.Messages { public class CommonNames { private const string PIPENAME = "CCCHECKPulsePipe"; private const string PIPENAME_CALLBACK = "CCCHECKPulsePipeForCallback"; [Pure] public static string GetPipeNameForCCCheckPulse() { Contract.Ensures(Contract.Result<string>() != null); return GetPipeNameForCCCheckPulse(Process.GetCurrentProcess().Id); } [Pure] public static string GetPipeNameForCCCheckPulse(int procID) { Contract.Ensures(Contract.Result<string>() != null); return PIPENAME + procID; } [Pure] public static string GetPipeNameForCCCheckPulseCallBack(int procID) { Contract.Ensures(Contract.Result<string>() != null); return PIPENAME_CALLBACK + procID; } } public class PipeStreamSimple { [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(formatter != null); } private readonly PipeStream stream; private readonly IFormatter formatter; public PipeStreamSimple(PipeStream stream) { Contract.Requires(stream != null); this.stream = stream; formatter = new BinaryFormatter(); } public bool TryRead<T>(out T result) { try { if (stream.IsConnected) { var tmp = formatter.Deserialize(stream); if (tmp is T) { result = (T)tmp; return true; } } } catch (Exception e) { Trace.TraceWarning("error in reading from the stream: {0}", e.Message); // do nothing? } result = default(T); return false; } public bool WriteIfConnected(string graph) { try { if (stream.IsConnected) { formatter.Serialize(stream, graph); return true; } } catch { // do nothing? } return false; // we failed } public bool WriteIfConnected(List<Tuple<string, object>> graph) { try { if (stream.IsConnected) { formatter.Serialize(stream, graph); return true; } } catch { // do nothing? } return false; // we failed } } public abstract class ClousotAnalysisInfoBaseClass { #region Poor man serialization, to avoid the issues from the type being defined in cccheck (via ILMERGE) and cccpulse public List<Tuple<string, object>> ToList() { Contract.Ensures(Contract.Result<List<Tuple<string, object>>>() != null); var result = new List<Tuple<string, object>>(); foreach (var f in this.GetType().GetFields()) { result.Add(new Tuple<string, object>(f.Name, f.GetValue(this))); } return result; } protected void FromList(List<Tuple<string, object>> list) { Contract.Requires(list != null); foreach (var tuple in list) { Contract.Assume(tuple != null); var f = this.GetType().GetField(tuple.Item1); Contract.Assume(f != null); f.SetValue(this, tuple.Item2); } } #endregion } [Serializable] public class ClousotAnalysisState : ClousotAnalysisInfoBaseClass { public int CurrMethodNumber; public string CurrMethodName; public double CurrPercentage; public string CurrPhase; public string CurrAssembly; public int CurrMemory; public ClousotAnalysisState() { } public ClousotAnalysisState(List<Tuple<string, object>> list) { Contract.Requires(list != null); this.FromList(list); } public override string ToString() { return string.Format("{0,6:P1}, Method #{1} {2} {3}", CurrPercentage, CurrMethodNumber, CurrMethodName, CurrPhase ?? " "); } } [Serializable] public class ClousotAnalysisResults : ClousotAnalysisInfoBaseClass { public int Pid; public string AnalyzedAssembly; // Assertions public long Total, True, Top, False, Bottom, Masked; // Methods public int MethodsTotal, MethodsFromCache, MethodsMissedInCache, MethodsTimedOut, MethodsWithCheaperAD; public DateTime StartTime, EndTime; public TimeSpan Elapsed; // Crashed? public bool ClousotCrashed = false; public ClousotAnalysisResults() { this.Pid = Process.GetCurrentProcess().Id; this.StartTime = DateTime.Now; } public ClousotAnalysisResults(List<Tuple<string, object>> list) { Contract.Requires(list != null); this.FromList(list); } public void NotifyDone() { this.EndTime = DateTime.Now; this.Elapsed = this.EndTime - this.StartTime; } public void UpdateAssertionStatisticsFrom(ClousotAnalysisResults results, int outputWarns) { Contract.Requires(results != null); this.Total = results.Total; this.True = results.True; this.False = results.False; this.Bottom = results.Bottom; this.Top = results.Top; this.Masked = results.Masked; } } }
using System; using System.Threading; using System.IO; using System.IO.Pipes; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Termie { public partial class Form1 : Form { /// <summary> /// Class to keep track of string and color for lines in output window. /// </summary> private class Line { public string Str; public Color ForeColor; public Line(string str, Color color) { Str = str; ForeColor = color; } }; ArrayList lines = new ArrayList(); Font origFont; Font monoFont; Thread PipeThread; NamedPipeServerStream Pipe; StreamReader SR; System.Threading.Timer IOtimer; public Form1() { InitializeComponent(); splitContainer1.FixedPanel = FixedPanel.Panel1; splitContainer2.FixedPanel = FixedPanel.Panel2; AcceptButton = button5; //Send CancelButton = button4; //Close outputList_Initialize(); Settings.Read(); TopMost = Settings.Option.StayOnTop; // let form use multiple fonts origFont = Font; FontFamily ff = new FontFamily("Consolas"); monoFont = new Font(ff, 10, FontStyle.Regular); Font = Settings.Option.MonoFont ? monoFont : origFont; CommPort com = CommPort.Instance; com.StatusChanged += OnStatusChanged; com.DataReceived += OnDataReceived; com.Open(); // Now start a thread to monitor the pipe that allows the flasher to request the com port PipeThread = new Thread(PipeTask); PipeThread.Start(); } // Timer routine that gets called after 1 minute of waiting for release from flasher // Tries to reopen the port if flasher has crashed void TimerCB(Object ob) { CommPort com = CommPort.Instance; System.Threading.Timer obT = (System.Threading.Timer) ob; if (!com.IsOpen) { com.Open(); if (com.IsOpen) OnDataReceived("TIMEOUT: PORT OPENED\n"); } if (com.IsOpen) obT.Change(Timeout.Infinite, Timeout.Infinite); // No need for more timer callbacks } // Task that watches the pipe that the flasher will connect to void PipeTask() { Pipe = new NamedPipeServerStream("TERMPIPE", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); CommPort com = CommPort.Instance; IOtimer = new System.Threading.Timer(new TimerCallback(TimerCB)); try { for (; ; ) { Pipe.WaitForConnection(); while (!Pipe.IsConnected) { Thread.Sleep(250); } //OnDataReceived("CONNECT\n"); SR = new StreamReader(Pipe); do { string s = null; try { if (!com.IsOpen) { IOtimer.Change(60000, 10000); // In case the flasher crashes while the port is closed } s = SR.ReadLine(); IOtimer.Change(Timeout.Infinite, Timeout.Infinite); // Call off the timer } catch (Exception ex) { // Broken pipe or read timeout if (!com.IsOpen) { // If the flasher crashed, com.Open(); // Try to reopen the port if (com.IsOpen) { // Say so if we succeeded OnDataReceived("PORT OPEN\n"); } } } if (s != null && s.Length != 0) { if (s.Contains("<REQUEST>")) { com.Close(); if (!com.IsOpen) OnDataReceived("PORT CLOSED\n"); } else if (s.Contains("<RELEASE>")) { Thread.Sleep(250); // Give the flasher some time to close the com port com.Open(); if (com.IsOpen) OnDataReceived("PORT OPEN\n"); } } } while (Pipe.IsConnected); //OnDataReceived("DISCONNECT\n"); Pipe.Disconnect(); } } catch (Exception e) { // Arrive here when we need to quit return; } } // shutdown the worker thread when the form closes protected override void OnClosed(EventArgs e) { CommPort com = CommPort.Instance; Pipe.Close(); // Will cause an exception in pipe thread, causing it to terminate com.Close(); base.OnClosed(e); } /// <summary> /// output string to log file /// </summary> /// <param name="stringOut">string to output</param> public void logFile_writeLine(string stringOut) { if(Settings.Option.LogFileName != "") { Stream myStream = File.Open(Settings.Option.LogFileName, FileMode.Append, FileAccess.Write, FileShare.Read); if(myStream != null) { StreamWriter myWriter = new StreamWriter(myStream, Encoding.UTF8); myWriter.WriteLine(stringOut); myWriter.Close(); } } } #region Output window string filterString = ""; bool scrolling = true; Color receivedColor = Color.Green; Color sentColor = Color.Blue; /// <summary> /// context menu for the output window /// </summary> ContextMenu popUpMenu; /// <summary> /// check to see if filter matches string /// </summary> /// <param name="s">string to check</param> /// <returns>true if matches filter</returns> bool outputList_ApplyFilter(String s) { if(filterString == "") { return true; } else if(s == "") { return false; } else if(Settings.Option.FilterUseCase) { return (s.IndexOf(filterString) != -1); } else { string upperString = s.ToUpper(); string upperFilter = filterString.ToUpper(); return (upperString.IndexOf(upperFilter) != -1); } } /// <summary> /// clear the output window /// </summary> void outputList_ClearAll() { lines.Clear(); partialLine = null; outputList.Items.Clear(); } /// <summary> /// refresh the output window /// </summary> void outputList_Refresh() { outputList.BeginUpdate(); outputList.Items.Clear(); foreach(Line line in lines) { if(outputList_ApplyFilter(line.Str)) { outputList.Items.Add(line); } } outputList.EndUpdate(); outputList_Scroll(); } /// <summary> /// add a new line to output window /// </summary> Line outputList_Add(string str, Color color) { Line newLine = new Line(str, color); lines.Add(newLine); if(outputList_ApplyFilter(newLine.Str)) { outputList.Items.Add(newLine); outputList_Scroll(); } return newLine; } /// <summary> /// Update a line in the output window. /// </summary> /// <param name="line">line to update</param> void outputList_Update(Line line) { // should we add to output? if(outputList_ApplyFilter(line.Str)) { // is the line already displayed? bool found = false; for(int i = 0; i < outputList.Items.Count; ++i) { int index = (outputList.Items.Count - 1) - i; if(line == outputList.Items[index]) { // is item visible? int itemsPerPage = (int)(outputList.Height / outputList.ItemHeight); if(index >= outputList.TopIndex && index < (outputList.TopIndex + itemsPerPage)) { // is there a way to refresh just one line // without redrawing the entire listbox? // changing the item value has no effect outputList.Refresh(); } found = true; break; } } if(!found) { // not found, so add it outputList.Items.Add(line); } } } /// <summary> /// Initialize the output window /// </summary> private void outputList_Initialize() { // owner draw for listbox so we can add color outputList.DrawMode = DrawMode.OwnerDrawFixed; outputList.DrawItem += new DrawItemEventHandler(outputList_DrawItem); outputList.ClearSelected(); // build the outputList context menu popUpMenu = new ContextMenu(); popUpMenu.MenuItems.Add("&Copy", new EventHandler(outputList_Copy)); popUpMenu.MenuItems[0].Visible = true; popUpMenu.MenuItems[0].Enabled = false; popUpMenu.MenuItems[0].Shortcut = Shortcut.CtrlC; popUpMenu.MenuItems[0].ShowShortcut = true; popUpMenu.MenuItems.Add("Copy All", new EventHandler(outputList_CopyAll)); popUpMenu.MenuItems[1].Visible = true; popUpMenu.MenuItems.Add("Select &All", new EventHandler(outputList_SelectAll)); popUpMenu.MenuItems[2].Visible = true; popUpMenu.MenuItems[2].Shortcut = Shortcut.CtrlA; popUpMenu.MenuItems[2].ShowShortcut = true; popUpMenu.MenuItems.Add("Clear Selected", new EventHandler(outputList_ClearSelected)); popUpMenu.MenuItems[3].Visible = true; outputList.ContextMenu = popUpMenu; } /// <summary> /// draw item with color in output window /// </summary> void outputList_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); if(e.Index >= 0 && e.Index < outputList.Items.Count) { Line line = (Line)outputList.Items[e.Index]; // if selected, make the text color readable Color color = line.ForeColor; if((e.State & DrawItemState.Selected) == DrawItemState.Selected) { color = Color.Black; // make it readable } e.Graphics.DrawString(line.Str, e.Font, new SolidBrush(color), e.Bounds, StringFormat.GenericDefault); } e.DrawFocusRectangle(); } /// <summary> /// Scroll to bottom of output window /// </summary> void outputList_Scroll() { if(scrolling) { int itemsPerPage = (int)(outputList.Height / outputList.ItemHeight); outputList.TopIndex = outputList.Items.Count - itemsPerPage; } } /// <summary> /// Enable/Disable copy selection in output window /// </summary> private void outputList_SelectedIndexChanged(object sender, EventArgs e) { popUpMenu.MenuItems[0].Enabled = (outputList.SelectedItems.Count > 0); } /// <summary> /// copy selection in output window to clipboard /// </summary> private void outputList_Copy(object sender, EventArgs e) { int iCount = outputList.SelectedItems.Count; if(iCount > 0) { String[] source = new String[iCount]; for(int i = 0; i < iCount; ++i) { source[i] = ((Line)outputList.SelectedItems[i]).Str; } String dest = String.Join("\r\n", source); Clipboard.SetText(dest); } } /// <summary> /// copy all lines in output window /// </summary> private void outputList_CopyAll(object sender, EventArgs e) { int iCount = outputList.Items.Count; if(iCount > 0) { String[] source = new String[iCount]; for(int i = 0; i < iCount; ++i) { source[i] = ((Line)outputList.Items[i]).Str; } String dest = String.Join("\r\n", source); Clipboard.SetText(dest); } } /// <summary> /// select all lines in output window /// </summary> private void outputList_SelectAll(object sender, EventArgs e) { outputList.BeginUpdate(); for(int i = 0; i < outputList.Items.Count; ++i) { outputList.SetSelected(i, true); } outputList.EndUpdate(); } /// <summary> /// clear selected in output window /// </summary> private void outputList_ClearSelected(object sender, EventArgs e) { outputList.ClearSelected(); outputList.SelectedItem = -1; } #endregion #region Event handling - data received and status changed /// <summary> /// Prepare a string for output by converting non-printable characters. /// </summary> /// <param name="StringIn">input string to prepare.</param> /// <returns>output string.</returns> private String PrepareData(String StringIn) { // The names of the first 32 characters string[] charNames = { "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", "BS", "TAB", "LF", "VT", "FF", "CR", "SO", "SI", "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US", "Space" }; string StringOut = ""; foreach(char c in StringIn) { if(Settings.Option.HexOutput) { StringOut = StringOut + String.Format("{0:X2} ", (int)c); } else if(c < 32 && c != 9 && c != 10) { StringOut = StringOut + "<" + charNames[c] + ">"; //Uglier "Termite" style //StringOut = StringOut + String.Format("[{0:X2}]", (int)c); } else if (c != 10) { StringOut = StringOut + c; } } return StringOut; } /// <summary> /// Partial line for AddData(). /// </summary> private Line partialLine = null; /// <summary> /// Add data to the output. /// </summary> /// <param name="StringIn"></param> /// <returns></returns> private Line AddData(String StringIn) { String StringOut = PrepareData(StringIn); // if we have a partial line, add to it. if(partialLine != null) { // tack it on partialLine.Str = partialLine.Str + StringOut; outputList_Update(partialLine); return partialLine; } return outputList_Add(StringOut, receivedColor); } // delegate used for Invoke internal delegate void StringDelegate(string data); /// <summary> /// Handle data received event from serial port. /// </summary> /// <param name="data">incoming data</param> public void OnDataReceived(string dataIn) { //Handle multi-threading if(InvokeRequired) { Invoke(new StringDelegate(OnDataReceived), new object[] { dataIn }); return; } // pause scrolling to speed up output of multiple lines bool saveScrolling = scrolling; scrolling = false; // if we detect a line terminator, add line to output int index; while(dataIn.Length > 0 && ((index = dataIn.IndexOf("\r")) != -1 || (index = dataIn.IndexOf("\n")) != -1)) { String StringIn = dataIn.Substring(0, index); dataIn = dataIn.Remove(0, index + 1); logFile_writeLine(AddData(StringIn).Str); partialLine = null; // terminate partial line } // if we have data remaining, add a partial line if(dataIn.Length > 0) { partialLine = AddData(dataIn); } // restore scrolling scrolling = saveScrolling; outputList_Scroll(); } /// <summary> /// Update the connection status /// </summary> public void OnStatusChanged(string status) { //Handle multi-threading if(InvokeRequired) { Invoke(new StringDelegate(OnStatusChanged), new object[] { status }); return; } textBox1.Text = status; } #endregion #region User interaction /// <summary> /// toggle connection status /// </summary> private void textBox1_Click(object sender, MouseEventArgs e) { CommPort com = CommPort.Instance; if(com.IsOpen) { com.Close(); } else { com.Open(); } outputList.Focus(); } /// <summary> /// Change filter /// </summary> private void textBox2_TextChanged(object sender, EventArgs e) { filterString = textBox2.Text; outputList_Refresh(); } /// <summary> /// Show settings dialog /// </summary> private void button1_Click(object sender, EventArgs e) { TopMost = false; Form2 form2 = new Form2(); form2.ShowDialog(); TopMost = Settings.Option.StayOnTop; Font = Settings.Option.MonoFont ? monoFont : origFont; } /// <summary> /// Clear the output window /// </summary> private void button2_Click(object sender, EventArgs e) { outputList_ClearAll(); } /// <summary> /// Show about dialog /// </summary> private void button3_Click(object sender, EventArgs e) { TopMost = false; AboutBox about = new AboutBox(); about.ShowDialog(); TopMost = Settings.Option.StayOnTop; } /// <summary> /// Close the application /// </summary> private void button4_Click(object sender, EventArgs e) { Close(); } /// <summary> /// If character 0-9 a-f A-F, then return hex digit value ? /// </summary> private static int GetHexDigit(char c) { if('0' <= c && c <= '9') return (c - '0'); if('a' <= c && c <= 'f') return (c - 'a') + 10; if('A' <= c && c <= 'F') return (c - 'A') + 10; return 0; } /// <summary> /// Parse states for ConvertEscapeSequences() /// </summary> public enum Expecting : byte { ANY = 1, ESCAPED_CHAR, HEX_1ST_DIGIT, HEX_2ND_DIGIT }; /// <summary> /// Convert escape sequences /// </summary> private string ConvertEscapeSequences(string s) { Expecting expecting = Expecting.ANY; int hexNum = 0; string outs = ""; foreach(char c in s) { switch(expecting) { case Expecting.ANY: if(c == '\\') expecting = Expecting.ESCAPED_CHAR; else outs += c; break; case Expecting.ESCAPED_CHAR: if(c == 'x') { expecting = Expecting.HEX_1ST_DIGIT; } else { char c2 = c; switch(c) { case 'n': c2 = '\n'; break; case 'r': c2 = '\r'; break; case 't': c2 = '\t'; break; } outs += c2; expecting = Expecting.ANY; } break; case Expecting.HEX_1ST_DIGIT: hexNum = GetHexDigit(c) * 16; expecting = Expecting.HEX_2ND_DIGIT; break; case Expecting.HEX_2ND_DIGIT: hexNum += GetHexDigit(c); outs += (char)hexNum; expecting = Expecting.ANY; break; } } return outs; } /// <summary> /// Send command /// </summary> private void button5_Click(object sender, EventArgs e) { string command = comboBox1.Text; comboBox1.Items.Add(comboBox1.Text); comboBox1.Text = ""; comboBox1.Focus(); if(command.Length > 0) { command = ConvertEscapeSequences(command); CommPort com = CommPort.Instance; com.Send(command); if(Settings.Option.LocalEcho) { outputList_Add(command + "\n", sentColor); } } } /// <summary> /// send file to serial port /// </summary> private void button6_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.RestoreDirectory = false; dialog.Title = "Select a file"; if(dialog.ShowDialog() == DialogResult.OK) { String text = System.IO.File.ReadAllText(dialog.FileName); CommPort com = CommPort.Instance; com.Send(text); if(Settings.Option.LocalEcho) { outputList_Add("SendFile " + dialog.FileName + "," + text.Length.ToString() + " byte(s)\n", sentColor); } } } /// <summary> /// toggle scrolling /// </summary> private void button7_Click(object sender, EventArgs e) { scrolling = !scrolling; outputList_Scroll(); } #endregion } }
/* * Copyright 2006 Jeremias Maerki in part, and ZXing Authors in part * * 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. */ /* * This file has been modified from its original form in Barcode4J. */ using System; using System.Text; namespace ZXing.PDF417.Internal { /// <summary> /// PDF417 error correction code following the algorithm described in ISO/IEC 15438:2001(E) in /// chapter 4.10. /// </summary> internal static class PDF417ErrorCorrection { /// <summary> /// Tables of coefficients for calculating error correction words /// (see annex F, ISO/IEC 15438:2001(E)) /// </summary> private static readonly int[][] EC_COEFFICIENTS = { new[] {27, 917}, new[] {522, 568, 723, 809}, new[] {237, 308, 436, 284, 646, 653, 428, 379}, new[] { 274, 562, 232, 755, 599, 524, 801, 132, 295, 116, 442, 428, 295, 42, 176, 65 }, new[] { 361, 575, 922, 525, 176, 586, 640, 321, 536, 742, 677, 742, 687, 284, 193, 517, 273, 494, 263, 147, 593, 800, 571, 320, 803, 133, 231, 390, 685, 330, 63, 410 }, new[] { 539, 422, 6, 93, 862, 771, 453, 106, 610, 287, 107, 505, 733, 877, 381, 612, 723, 476, 462, 172, 430, 609, 858, 822, 543, 376, 511, 400, 672, 762, 283, 184, 440, 35, 519, 31, 460, 594, 225, 535, 517, 352, 605, 158, 651, 201, 488, 502, 648, 733, 717, 83, 404, 97, 280, 771, 840, 629, 4, 381, 843, 623, 264, 543 }, new[] { 521, 310, 864, 547, 858, 580, 296, 379, 53, 779, 897, 444, 400, 925, 749, 415, 822, 93, 217, 208, 928, 244, 583, 620, 246, 148, 447, 631, 292, 908, 490, 704, 516, 258, 457, 907, 594, 723, 674, 292, 272, 96, 684, 432, 686, 606, 860, 569, 193, 219, 129, 186, 236, 287, 192, 775, 278, 173, 40, 379, 712, 463, 646, 776, 171, 491, 297, 763, 156, 732, 95, 270, 447, 90, 507, 48, 228, 821, 808, 898, 784, 663, 627, 378, 382, 262, 380, 602, 754, 336, 89, 614, 87, 432, 670, 616, 157, 374, 242, 726, 600, 269, 375, 898, 845, 454, 354, 130, 814, 587, 804, 34, 211, 330, 539, 297, 827, 865, 37, 517, 834, 315, 550, 86, 801, 4, 108, 539 }, new[] { 524, 894, 75, 766, 882, 857, 74, 204, 82, 586, 708, 250, 905, 786, 138, 720, 858, 194, 311, 913, 275, 190, 375, 850, 438, 733, 194, 280, 201, 280, 828, 757, 710, 814, 919, 89, 68, 569, 11, 204, 796, 605, 540, 913, 801, 700, 799, 137, 439, 418, 592, 668, 353, 859, 370, 694, 325, 240, 216, 257, 284, 549, 209, 884, 315, 70, 329, 793, 490, 274, 877, 162, 749, 812, 684, 461, 334, 376, 849, 521, 307, 291, 803, 712, 19, 358, 399, 908, 103, 511, 51, 8, 517, 225, 289, 470, 637, 731, 66, 255, 917, 269, 463, 830, 730, 433, 848, 585, 136, 538, 906, 90, 2, 290, 743, 199, 655, 903, 329, 49, 802, 580, 355, 588, 188, 462, 10, 134, 628, 320, 479, 130, 739, 71, 263, 318, 374, 601, 192, 605, 142, 673, 687, 234, 722, 384, 177, 752, 607, 640, 455, 193, 689, 707, 805, 641, 48, 60, 732, 621, 895, 544, 261, 852, 655, 309, 697, 755, 756, 60, 231, 773, 434, 421, 726, 528, 503, 118, 49, 795, 32, 144, 500, 238, 836, 394, 280, 566, 319, 9, 647, 550, 73, 914, 342, 126, 32, 681, 331, 792, 620, 60, 609, 441, 180, 791, 893, 754, 605, 383, 228, 749, 760, 213, 54, 297, 134, 54, 834, 299, 922, 191, 910, 532, 609, 829, 189, 20, 167, 29, 872, 449, 83, 402, 41, 656, 505, 579, 481, 173, 404, 251, 688, 95, 497, 555, 642, 543, 307, 159, 924, 558, 648, 55, 497, 10 }, new[] { 352, 77, 373, 504, 35, 599, 428, 207, 409, 574, 118, 498, 285, 380, 350, 492, 197, 265, 920, 155, 914, 299, 229, 643, 294, 871, 306, 88, 87, 193, 352, 781, 846, 75, 327, 520, 435, 543, 203, 666, 249, 346, 781, 621, 640, 268, 794, 534, 539, 781, 408, 390, 644, 102, 476, 499, 290, 632, 545, 37, 858, 916, 552, 41, 542, 289, 122, 272, 383, 800, 485, 98, 752, 472, 761, 107, 784, 860, 658, 741, 290, 204, 681, 407, 855, 85, 99, 62, 482, 180, 20, 297, 451, 593, 913, 142, 808, 684, 287, 536, 561, 76, 653, 899, 729, 567, 744, 390, 513, 192, 516, 258, 240, 518, 794, 395, 768, 848, 51, 610, 384, 168, 190, 826, 328, 596, 786, 303, 570, 381, 415, 641, 156, 237, 151, 429, 531, 207, 676, 710, 89, 168, 304, 402, 40, 708, 575, 162, 864, 229, 65, 861, 841, 512, 164, 477, 221, 92, 358, 785, 288, 357, 850, 836, 827, 736, 707, 94, 8, 494, 114, 521, 2, 499, 851, 543, 152, 729, 771, 95, 248, 361, 578, 323, 856, 797, 289, 51, 684, 466, 533, 820, 669, 45, 902, 452, 167, 342, 244, 173, 35, 463, 651, 51, 699, 591, 452, 578, 37, 124, 298, 332, 552, 43, 427, 119, 662, 777, 475, 850, 764, 364, 578, 911, 283, 711, 472, 420, 245, 288, 594, 394, 511, 327, 589, 777, 699, 688, 43, 408, 842, 383, 721, 521, 560, 644, 714, 559, 62, 145, 873, 663, 713, 159, 672, 729, 624, 59, 193, 417, 158, 209, 563, 564, 343, 693, 109, 608, 563, 365, 181, 772, 677, 310, 248, 353, 708, 410, 579, 870, 617, 841, 632, 860, 289, 536, 35, 777, 618, 586, 424, 833, 77, 597, 346, 269, 757, 632, 695, 751, 331, 247, 184, 45, 787, 680, 18, 66, 407, 369, 54, 492, 228, 613, 830, 922, 437, 519, 644, 905, 789, 420, 305, 441, 207, 300, 892, 827, 141, 537, 381, 662, 513, 56, 252, 341, 242, 797, 838, 837, 720, 224, 307, 631, 61, 87, 560, 310, 756, 665, 397, 808, 851, 309, 473, 795, 378, 31, 647, 915, 459, 806, 590, 731, 425, 216, 548, 249, 321, 881, 699, 535, 673, 782, 210, 815, 905, 303, 843, 922, 281, 73, 469, 791, 660, 162, 498, 308, 155, 422, 907, 817, 187, 62, 16, 425, 535, 336, 286, 437, 375, 273, 610, 296, 183, 923, 116, 667, 751, 353, 62, 366, 691, 379, 687, 842, 37, 357, 720, 742, 330, 5, 39, 923, 311, 424, 242, 749, 321, 54, 669, 316, 342, 299, 534, 105, 667, 488, 640, 672, 576, 540, 316, 486, 721, 610, 46, 656, 447, 171, 616, 464, 190, 531, 297, 321, 762, 752, 533, 175, 134, 14, 381, 433, 717, 45, 111, 20, 596, 284, 736, 138, 646, 411, 877, 669, 141, 919, 45, 780, 407, 164, 332, 899, 165, 726, 600, 325, 498, 655, 357, 752, 768, 223, 849, 647, 63, 310, 863, 251, 366, 304, 282, 738, 675, 410, 389, 244, 31, 121, 303, 263 } }; /// <summary> /// Determines the number of error correction codewords for a specified error correction /// level. /// </summary> /// <param name="errorCorrectionLevel">the error correction level (0-8)</param> /// <returns>the number of codewords generated for error correction</returns> internal static int getErrorCorrectionCodewordCount(int errorCorrectionLevel) { if (errorCorrectionLevel < 0 || errorCorrectionLevel > 8) { throw new ArgumentException("Error correction level must be between 0 and 8!"); } return 1 << (errorCorrectionLevel + 1); } /// <summary> /// Returns the recommended minimum error correction level as described in annex E of /// ISO/IEC 15438:2001(E). /// </summary> /// <param name="n">the number of data codewords</param> /// <returns>the recommended minimum error correction level</returns> internal static int getRecommendedMinimumErrorCorrectionLevel(int n) { if (n <= 0) { throw new ArgumentException("n must be > 0"); } if (n <= 40) { return 2; } if (n <= 160) { return 3; } if (n <= 320) { return 4; } if (n <= 863) { return 5; } throw new WriterException("No recommendation possible"); } /// <summary> /// Generates the error correction codewords according to 4.10 in ISO/IEC 15438:2001(E). /// </summary> /// <param name="dataCodewords">the data codewords</param> /// <param name="errorCorrectionLevel">the error correction level (0-8)</param> /// <returns>the String representing the error correction codewords</returns> internal static String generateErrorCorrection(String dataCodewords, int errorCorrectionLevel) { int k = getErrorCorrectionCodewordCount(errorCorrectionLevel); char[] e = new char[k]; int sld = dataCodewords.Length; for (int i = 0; i < sld; i++) { int t1 = (dataCodewords[i] + e[e.Length - 1])%929; int t2; int t3; for (int j = k - 1; j >= 1; j--) { t2 = (t1*EC_COEFFICIENTS[errorCorrectionLevel][j])%929; t3 = 929 - t2; e[j] = (char) ((e[j - 1] + t3)%929); } t2 = (t1*EC_COEFFICIENTS[errorCorrectionLevel][0])%929; t3 = 929 - t2; e[0] = (char) (t3%929); } StringBuilder sb = new StringBuilder(k); for (int j = k - 1; j >= 0; j--) { if (e[j] != 0) { e[j] = (char) (929 - e[j]); } sb.Append(e[j]); } return sb.ToString(); } } /// <summary> /// defines the level of the error correction / count of error correction codewords /// </summary> public enum PDF417ErrorCorrectionLevel { L0 = 0, L1, L2, L3, L4, L5, L6, L7, L8 } }
using RootSystem = System; using System.Linq; using System.Collections.Generic; namespace Windows.Kinect { // // Windows.Kinect.LongExposureInfraredFrameSource // public sealed partial class LongExposureInfraredFrameSource : Helper.INativeWrapper { internal RootSystem.IntPtr _pNative; RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } } // Constructors and Finalizers internal LongExposureInfraredFrameSource(RootSystem.IntPtr pNative) { _pNative = pNative; Windows_Kinect_LongExposureInfraredFrameSource_AddRefObject(ref _pNative); } ~LongExposureInfraredFrameSource() { Dispose(false); } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_LongExposureInfraredFrameSource_ReleaseObject(ref RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_LongExposureInfraredFrameSource_AddRefObject(ref RootSystem.IntPtr pNative); private void Dispose(bool disposing) { if (_pNative == RootSystem.IntPtr.Zero) { return; } __EventCleanup(); Helper.NativeObjectCache.RemoveObject<LongExposureInfraredFrameSource>(_pNative); Windows_Kinect_LongExposureInfraredFrameSource_ReleaseObject(ref _pNative); _pNative = RootSystem.IntPtr.Zero; } // Public Properties [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_LongExposureInfraredFrameSource_get_FrameDescription(RootSystem.IntPtr pNative); public Windows.Kinect.FrameDescription FrameDescription { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameSource"); } RootSystem.IntPtr objectPointer = Windows_Kinect_LongExposureInfraredFrameSource_get_FrameDescription(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.FrameDescription>(objectPointer, n => new Windows.Kinect.FrameDescription(n)); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern bool Windows_Kinect_LongExposureInfraredFrameSource_get_IsActive(RootSystem.IntPtr pNative); public bool IsActive { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameSource"); } return Windows_Kinect_LongExposureInfraredFrameSource_get_IsActive(_pNative); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_LongExposureInfraredFrameSource_get_KinectSensor(RootSystem.IntPtr pNative); public Windows.Kinect.KinectSensor KinectSensor { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameSource"); } RootSystem.IntPtr objectPointer = Windows_Kinect_LongExposureInfraredFrameSource_get_KinectSensor(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.KinectSensor>(objectPointer, n => new Windows.Kinect.KinectSensor(n)); } } // Events private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Kinect_FrameCapturedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Kinect_FrameCapturedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.FrameCapturedEventArgs>>> Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.FrameCapturedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Kinect_FrameCapturedEventArgs_Delegate))] private static void Windows_Kinect_FrameCapturedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Kinect.FrameCapturedEventArgs>> callbackList = null; Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<LongExposureInfraredFrameSource>(pNative); var args = new Windows.Kinect.FrameCapturedEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_LongExposureInfraredFrameSource_add_FrameCaptured(RootSystem.IntPtr pNative, _Windows_Kinect_FrameCapturedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Kinect.FrameCapturedEventArgs> FrameCaptured { add { Helper.EventPump.EnsureInitialized(); Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Kinect_FrameCapturedEventArgs_Delegate(Windows_Kinect_FrameCapturedEventArgs_Delegate_Handler); _Windows_Kinect_FrameCapturedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Windows_Kinect_LongExposureInfraredFrameSource_add_FrameCaptured(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Windows_Kinect_LongExposureInfraredFrameSource_add_FrameCaptured(_pNative, Windows_Kinect_FrameCapturedEventArgs_Delegate_Handler, true); _Windows_Kinect_FrameCapturedEventArgs_Delegate_Handle.Free(); } } } } private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))] private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null; Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<LongExposureInfraredFrameSource>(pNative); var args = new Windows.Data.PropertyChangedEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_LongExposureInfraredFrameSource_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged { add { Helper.EventPump.EnsureInitialized(); Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Windows_Kinect_LongExposureInfraredFrameSource_add_PropertyChanged(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Windows_Kinect_LongExposureInfraredFrameSource_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } // Public Methods [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_LongExposureInfraredFrameSource_OpenReader(RootSystem.IntPtr pNative); public Windows.Kinect.LongExposureInfraredFrameReader OpenReader() { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameSource"); } RootSystem.IntPtr objectPointer = Windows_Kinect_LongExposureInfraredFrameSource_OpenReader(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.LongExposureInfraredFrameReader>(objectPointer, n => new Windows.Kinect.LongExposureInfraredFrameReader(n)); } private void __EventCleanup() { { Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Windows_Kinect_LongExposureInfraredFrameSource_add_FrameCaptured(_pNative, Windows_Kinect_FrameCapturedEventArgs_Delegate_Handler, true); } _Windows_Kinect_FrameCapturedEventArgs_Delegate_Handle.Free(); } } } { Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Windows_Kinect_LongExposureInfraredFrameSource_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); } _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Numerics; using System.Text; using Xunit; namespace System.SpanTests { public static partial class ReadOnlySpanTests { [Theory] [InlineData("a", "a", 'a', 0)] [InlineData("ab", "a", 'a', 0)] [InlineData("aab", "a", 'a', 0)] [InlineData("acab", "a", 'a', 0)] [InlineData("acab", "c", 'c', 1)] [InlineData("abcdefghijklmnopqrstuvwxyz", "lo", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyz", "ol", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyz", "ll", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyz", "rml", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyz", "mlr", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)] [InlineData("aaaaaaaaaaalmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)] [InlineData("aaaaaaaaaaacmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'm', 12)] [InlineData("aaaaaaaaaaarmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'r', 11)] [InlineData("/localhost:5000/PATH/%2FPATH2/ HTTP/1.1", " %?", '%', 21)] [InlineData("/localhost:5000/PATH/%2FPATH2/?key=value HTTP/1.1", " %?", '%', 21)] [InlineData("/localhost:5000/PATH/PATH2/?key=value HTTP/1.1", " %?", '?', 27)] [InlineData("/localhost:5000/PATH/PATH2/ HTTP/1.1", " %?", ' ', 27)] public static void IndexOfAnyStrings_Char(string raw, string search, char expectResult, int expectIndex) { ReadOnlySpan<char> span = raw.AsSpan(); char[] searchFor = search.ToCharArray(); int index = span.IndexOfAny(searchFor); if (searchFor.Length == 1) { Assert.Equal(index, span.IndexOf(searchFor[0])); } else if (searchFor.Length == 2) { Assert.Equal(index, span.IndexOfAny(searchFor[0], searchFor[1])); } else if (searchFor.Length == 3) { Assert.Equal(index, span.IndexOfAny(searchFor[0], searchFor[1], searchFor[2])); } char found = span[index]; Assert.Equal(expectResult, found); Assert.Equal(expectIndex, index); } [Fact] public static void ZeroLengthIndexOfTwo_Char() { ReadOnlySpan<char> sp = new ReadOnlySpan<char>(Array.Empty<char>()); int idx = sp.IndexOfAny<char>((char)0, (char)0); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfTwo_Char() { Random rnd = new Random(42); for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); char[] targets = { default, (char)99 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, targets.Length) == 0 ? 0 : 1; char target0 = targets[index]; char target1 = targets[(index + 1) % 2]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchTwo_Char() { for (int length = Vector<short>.Count; length <= byte.MaxValue + 1; length++) { char[] a = Enumerable.Range(0, length).Select(i => (char)(i + 1)).ToArray(); for (int i = 0; i < Vector<short>.Count; i++) { ReadOnlySpan<char> span = new ReadOnlySpan<char>(a).Slice(i); for (int targetIndex = 0; targetIndex < length - Vector<short>.Count; targetIndex++) { char target0 = a[targetIndex + i]; char target1 = (char)0; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 1 - Vector<short>.Count; targetIndex++) { char target0 = a[targetIndex + i]; char target1 = a[targetIndex + i + 1]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 1 - Vector<short>.Count; targetIndex++) { char target0 = (char)0; char target1 = a[targetIndex + i + 1]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex + 1, idx); } } } } [Fact] public static void TestNoMatchTwo_Char() { Random rnd = new Random(42); for (int length = 0; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; char target0 = (char)rnd.Next(1, 256); char target1 = (char)rnd.Next(1, 256); ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); int idx = span.IndexOfAny(target0, target1); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchTwo_Char() { for (int length = 3; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; for (int i = 0; i < length; i++) { char val = (char)(i + 1); a[i] = val == (char)200 ? (char)201 : val; } a[length - 1] = (char)200; a[length - 2] = (char)200; a[length - 3] = (char)200; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); int idx = span.IndexOfAny<char>((char)200, (char)200); Assert.Equal(length - 3, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeTwo_Char() { for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length + 2]; a[0] = (char)99; a[length + 1] = (char)98; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a, 1, length - 1); int index = span.IndexOfAny<char>((char)99, (char)98); Assert.Equal(-1, index); } for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length + 2]; a[0] = (char)99; a[length + 1] = (char)99; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a, 1, length - 1); int index = span.IndexOfAny<char>((char)99, (char)99); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOfThree_Char() { ReadOnlySpan<char> sp = new ReadOnlySpan<char>(Array.Empty<char>()); int idx = sp.IndexOfAny<char>((char)0, (char)0, (char)0); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfThree_Char() { Random rnd = new Random(42); for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); char[] targets = { default, (char)99, (char)98 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, targets.Length); char target0 = targets[index]; char target1 = targets[(index + 1) % 2]; char target2 = targets[(index + 1) % 3]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchThree_Char() { for (int length = Vector<short>.Count; length <= byte.MaxValue + 1; length++) { char[] a = Enumerable.Range(0, length).Select(i => (char)(i + 1)).ToArray(); for (int i = 0; i < Vector<short>.Count; i++) { ReadOnlySpan<char> span = new ReadOnlySpan<char>(a).Slice(i); for (int targetIndex = 0; targetIndex < length - Vector<short>.Count; targetIndex++) { char target0 = a[targetIndex + i]; char target1 = (char)0; char target2 = (char)0; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 2 - Vector<short>.Count; targetIndex++) { char target0 = a[targetIndex + i]; char target1 = a[targetIndex + i + 1]; char target2 = a[targetIndex + i + 2]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 2 - Vector<short>.Count; targetIndex++) { char target0 = (char)0; char target1 = (char)0; char target2 = a[targetIndex + i + 2]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex + 2, idx); } } } } [Fact] public static void TestNoMatchThree_Char() { Random rnd = new Random(42); for (int length = 0; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; char target0 = (char)rnd.Next(1, 256); char target1 = (char)rnd.Next(1, 256); char target2 = (char)rnd.Next(1, 256); ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchThree_Char() { for (int length = 4; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; for (int i = 0; i < length; i++) { char val = (char)(i + 1); a[i] = val == (char)200 ? (char)201 : val; } a[length - 1] = (char)200; a[length - 2] = (char)200; a[length - 3] = (char)200; a[length - 4] = (char)200; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); int idx = span.IndexOfAny<char>((char)200, (char)200, (char)200); Assert.Equal(length - 4, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeThree_Char() { for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length + 2]; a[0] = (char)99; a[length + 1] = (char)98; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a, 1, length - 1); int index = span.IndexOfAny<char>((char)99, (char)98, (char)99); Assert.Equal(-1, index); } for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length + 2]; a[0] = (char)99; a[length + 1] = (char)99; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a, 1, length - 1); int index = span.IndexOfAny<char>((char)99, (char)99, (char)99); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOfFour_Char() { ReadOnlySpan<char> sp = new ReadOnlySpan<char>(Array.Empty<char>()); ReadOnlySpan<char> values = new char[] { (char)0, (char)0, (char)0, (char)0 }; int idx = sp.IndexOfAny<char>(values); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfFour_Char() { Random rnd = new Random(42); for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); char[] targets = { default, (char)99, (char)98, (char)97 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, targets.Length); ReadOnlySpan<char> values = new char[] { (char)targets[index], (char)targets[(index + 1) % 2], (char)targets[(index + 1) % 3], (char)targets[(index + 1) % 4] }; int idx = span.IndexOfAny(values); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchFour_Char() { for (int length = Vector<short>.Count; length <= byte.MaxValue + 1; length++) { char[] a = Enumerable.Range(0, length).Select(i => (char)(i + 1)).ToArray(); for (int i = 0; i < Vector<short>.Count; i++) { ReadOnlySpan<char> span = new ReadOnlySpan<char>(a).Slice(i); for (int targetIndex = 0; targetIndex < length - Vector<short>.Count; targetIndex++) { ReadOnlySpan<char> values = new char[] { (char)a[targetIndex + i], (char)0, (char)0, (char)0 }; int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 3 - Vector<short>.Count; targetIndex++) { ReadOnlySpan<char> values = new char[] { (char)a[targetIndex + i], (char)a[targetIndex + i + 1], (char)a[targetIndex + i + 2], (char)a[targetIndex + i + 3] }; int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 3 - Vector<short>.Count; targetIndex++) { ReadOnlySpan<char> values = new char[] { (char)0, (char)0, (char)0, (char)a[targetIndex + i + 3] }; int idx = span.IndexOfAny(values); Assert.Equal(targetIndex + 3, idx); } } } } [Fact] public static void TestNoMatchFour_Char() { Random rnd = new Random(42); for (int length = 0; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; ReadOnlySpan<char> values = new char[] { (char)rnd.Next(1, 256), (char)rnd.Next(1, 256), (char)rnd.Next(1, 256), (char)rnd.Next(1, 256) }; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); int idx = span.IndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchFour_Char() { for (int length = 5; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; for (int i = 0; i < length; i++) { char val = (char)(i + 1); a[i] = val == (char)200 ? (char)201 : val; } a[length - 1] = (char)200; a[length - 2] = (char)200; a[length - 3] = (char)200; a[length - 4] = (char)200; a[length - 5] = (char)200; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); ReadOnlySpan<char> values = new char[] { (char)200, (char)200, (char)200, (char)200 }; int idx = span.IndexOfAny<char>(values); Assert.Equal(length - 5, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeFour_Char() { for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length + 2]; a[0] = (char)99; a[length + 1] = (char)98; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a, 1, length - 1); ReadOnlySpan<char> values = new char[] { (char)99, (char)98, (char)99, (char)99 }; int index = span.IndexOfAny<char>(values); Assert.Equal(-1, index); } for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length + 2]; a[0] = (char)99; a[length + 1] = (char)99; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a, 1, length - 1); ReadOnlySpan<char> values = new char[] { (char)99, (char)99, (char)99, (char)99 }; int index = span.IndexOfAny<char>(values); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOfFive_Char() { ReadOnlySpan<char> sp = new ReadOnlySpan<char>(Array.Empty<char>()); ReadOnlySpan<char> values = new char[] { (char)0, (char)0, (char)0, (char)0, (char)0 }; int idx = sp.IndexOfAny<char>(values); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfFive_Char() { Random rnd = new Random(42); for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); char[] targets = { default, (char)99, (char)98, (char)97, (char)96 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, targets.Length); ReadOnlySpan<char> values = new char[] { (char)targets[index], (char)targets[(index + 1) % 2], (char)targets[(index + 1) % 3], (char)targets[(index + 1) % 4], (char)targets[(index + 1) % 5] }; int idx = span.IndexOfAny(values); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchFive_Char() { for (int length = Vector<short>.Count; length <= byte.MaxValue + 1; length++) { char[] a = Enumerable.Range(0, length).Select(i => (char)(i + 1)).ToArray(); for (int i = 0; i < Vector<short>.Count; i++) { ReadOnlySpan<char> span = new ReadOnlySpan<char>(a).Slice(i); for (int targetIndex = 0; targetIndex < length - Vector<short>.Count; targetIndex++) { ReadOnlySpan<char> values = new char[] { (char)a[targetIndex + i], (char)0, (char)0, (char)0, (char)0 }; int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 4 - Vector<short>.Count; targetIndex++) { ReadOnlySpan<char> values = new char[] { (char)a[targetIndex + i], (char)a[targetIndex + i + 1], (char)a[targetIndex + i + 2], (char)a[targetIndex + i + 3], (char)a[targetIndex + i + 4] }; int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 4 - Vector<short>.Count; targetIndex++) { ReadOnlySpan<char> values = new char[] { (char)0, (char)0, (char)0, (char)0, (char)a[targetIndex + i + 4] }; int idx = span.IndexOfAny(values); Assert.Equal(targetIndex + 4, idx); } } } } [Fact] public static void TestNoMatchFive_Char() { Random rnd = new Random(42); for (int length = 0; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; ReadOnlySpan<char> values = new char[] { (char)rnd.Next(1, 256), (char)rnd.Next(1, 256), (char)rnd.Next(1, 256), (char)rnd.Next(1, 256), (char)rnd.Next(1, 256) }; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); int idx = span.IndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchFive_Char() { for (int length = 6; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; for (int i = 0; i < length; i++) { char val = (char)(i + 1); a[i] = val == (char)200 ? (char)201 : val; } a[length - 1] = (char)200; a[length - 2] = (char)200; a[length - 3] = (char)200; a[length - 4] = (char)200; a[length - 5] = (char)200; a[length - 6] = (char)200; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); ReadOnlySpan<char> values = new char[] { (char)200, (char)200, (char)200, (char)200, (char)200 }; int idx = span.IndexOfAny<char>(values); Assert.Equal(length - 6, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeFive_Char() { for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length + 2]; a[0] = (char)99; a[length + 1] = (char)98; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a, 1, length - 1); ReadOnlySpan<char> values = new char[] { (char)99, (char)98, (char)99, (char)99, (char)99 }; int index = span.IndexOfAny<char>(values); Assert.Equal(-1, index); } for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length + 2]; a[0] = (char)99; a[length + 1] = (char)99; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a, 1, length - 1); ReadOnlySpan<char> values = new char[] { (char)99, (char)99, (char)99, (char)99, (char)99 }; int index = span.IndexOfAny<char>(values); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOfMany_Char() { ReadOnlySpan<char> sp = new ReadOnlySpan<char>(Array.Empty<char>()); ReadOnlySpan<char> values = new ReadOnlySpan<char>(new char[] { (char)0, (char)0, (char)0, (char)0, (char)0, (char)0 }); int idx = sp.IndexOfAny(values); Assert.Equal(-1, idx); values = new ReadOnlySpan<char>(new char[] { }); idx = sp.IndexOfAny(values); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfMany_Char() { for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); ReadOnlySpan<char> values = new ReadOnlySpan<char>(new char[] { default, (char)99, (char)98, (char)97, (char)96, (char)0 }); for (int i = 0; i < length; i++) { int idx = span.IndexOfAny(values); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchMany_Char() { for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = Enumerable.Range(0, length).Select(i => (char)(i + 1)).ToArray(); ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { ReadOnlySpan<char> values = new ReadOnlySpan<char>(new char[] { a[targetIndex], (char)0, (char)0, (char)0, (char)0, (char)0 }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 5; targetIndex++) { ReadOnlySpan<char> values = new ReadOnlySpan<char>(new char[] { a[targetIndex], a[targetIndex + 1], a[targetIndex + 2], a[targetIndex + 3], a[targetIndex + 4], a[targetIndex + 5] }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 5; targetIndex++) { ReadOnlySpan<char> values = new ReadOnlySpan<char>(new char[] { (char)0, (char)0, (char)0, (char)0, (char)0, a[targetIndex + 5] }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex + 5, idx); } } } [Fact] public static void TestMatchValuesLargerMany_Char() { Random rnd = new Random(42); for (int length = 2; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; int expectedIndex = length / 2; for (int i = 0; i < length; i++) { if (i == expectedIndex) { continue; } a[i] = (char)255; } ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); char[] targets = new char[length * 2]; for (int i = 0; i < targets.Length; i++) { if (i == length + 1) { continue; } targets[i] = (char)rnd.Next(1, 255); } ReadOnlySpan<char> values = new ReadOnlySpan<char>(targets); int idx = span.IndexOfAny(values); Assert.Equal(expectedIndex, idx); } } [Fact] public static void TestNoMatchMany_Char() { Random rnd = new Random(42); for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; char[] targets = new char[length]; for (int i = 0; i < targets.Length; i++) { targets[i] = (char)rnd.Next(1, 256); } ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); ReadOnlySpan<char> values = new ReadOnlySpan<char>(targets); int idx = span.IndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestNoMatchValuesLargerMany_Char() { Random rnd = new Random(42); for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; char[] targets = new char[length * 2]; for (int i = 0; i < targets.Length; i++) { targets[i] = (char)rnd.Next(1, 256); } ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); ReadOnlySpan<char> values = new ReadOnlySpan<char>(targets); int idx = span.IndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchMany_Char() { for (int length = 5; length <= byte.MaxValue + 1; length++) { char[] a = new char[length]; for (int i = 0; i < length; i++) { char val = (char)(i + 1); a[i] = val == 200 ? (char)201 : val; } a[length - 1] = (char)200; a[length - 2] = (char)200; a[length - 3] = (char)200; a[length - 4] = (char)200; a[length - 5] = (char)200; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a); ReadOnlySpan<char> values = new ReadOnlySpan<char>(new char[] { (char)200, (char)200, (char)200, (char)200, (char)200, (char)200, (char)200, (char)200, (char)200 }); int idx = span.IndexOfAny(values); Assert.Equal(length - 5, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeMany_Char() { for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length + 2]; a[0] = (char)99; a[length + 1] = (char)98; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a, 1, length - 1); ReadOnlySpan<char> values = new ReadOnlySpan<char>(new char[] { (char)99, (char)98, (char)99, (char)98, (char)99, (char)98 }); int index = span.IndexOfAny(values); Assert.Equal(-1, index); } for (int length = 1; length <= byte.MaxValue + 1; length++) { char[] a = new char[length + 2]; a[0] = (char)99; a[length + 1] = (char)99; ReadOnlySpan<char> span = new ReadOnlySpan<char>(a, 1, length - 1); ReadOnlySpan<char> values = new ReadOnlySpan<char>(new char[] { (char)99, (char)99, (char)99, (char)99, (char)99, (char)99 }); int index = span.IndexOfAny(values); Assert.Equal(-1, index); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.ServiceBus.Core { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Transactions; using Microsoft.Azure.Amqp; using Microsoft.Azure.Amqp.Encoding; using Microsoft.Azure.Amqp.Framing; using Microsoft.Azure.ServiceBus.Amqp; using Microsoft.Azure.ServiceBus.Primitives; /// <summary> /// The MessageSender can be used to send messages to Queues or Topics. /// </summary> /// <example> /// Create a new MessageSender to send to a Queue /// <code> /// IMessageSender messageSender = new MessageSender( /// namespaceConnectionString, /// queueName) /// </code> /// /// Send message /// <code> /// byte[] data = GetData(); /// await messageSender.SendAsync(data); /// </code> /// </example> /// <remarks>This uses AMQP protocol to communicate with service.</remarks> public class MessageSender : ClientEntity, IMessageSender { int deliveryCount; readonly ActiveClientLinkManager clientLinkManager; readonly ServiceBusDiagnosticSource diagnosticSource; readonly bool isViaSender; /// <summary> /// Creates a new AMQP MessageSender. /// </summary> /// <param name="connectionStringBuilder">The <see cref="ServiceBusConnectionStringBuilder"/> having entity level connection details.</param> /// <param name="retryPolicy">The <see cref="RetryPolicy"/> that will be used when communicating with Service Bus. Defaults to <see cref="RetryPolicy.Default"/></param> /// <remarks>Creates a new connection to the entity, which is opened during the first operation.</remarks> public MessageSender( ServiceBusConnectionStringBuilder connectionStringBuilder, RetryPolicy retryPolicy = null) : this(connectionStringBuilder?.GetNamespaceConnectionString(), connectionStringBuilder?.EntityPath, retryPolicy) { } /// <summary> /// Creates a new AMQP MessageSender. /// </summary> /// <param name="connectionString">Namespace connection string used to communicate with Service Bus. Must not contain Entity details.</param> /// <param name="entityPath">The path of the entity this sender should connect to.</param> /// <param name="retryPolicy">The <see cref="RetryPolicy"/> that will be used when communicating with Service Bus. Defaults to <see cref="RetryPolicy.Default"/></param> /// <remarks>Creates a new connection to the entity, which is opened during the first operation.</remarks> public MessageSender( string connectionString, string entityPath, RetryPolicy retryPolicy = null) : this(entityPath, null, null, new ServiceBusConnection(connectionString), null, retryPolicy) { if (string.IsNullOrWhiteSpace(connectionString)) { throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString); } this.OwnsConnection = true; } /// <summary> /// Creates a new MessageSender /// </summary> /// <param name="endpoint">Fully qualified domain name for Service Bus. Most likely, {yournamespace}.servicebus.windows.net</param> /// <param name="entityPath">Queue path.</param> /// <param name="tokenProvider">Token provider which will generate security tokens for authorization.</param> /// <param name="transportType">Transport type.</param> /// <param name="retryPolicy">Retry policy for queue operations. Defaults to <see cref="RetryPolicy.Default"/></param> /// <remarks>Creates a new connection to the entity, which is opened during the first operation.</remarks> public MessageSender( string endpoint, string entityPath, ITokenProvider tokenProvider, TransportType transportType = TransportType.Amqp, RetryPolicy retryPolicy = null) : this(entityPath, null, null, new ServiceBusConnection(endpoint, transportType, retryPolicy) {TokenProvider = tokenProvider}, null, retryPolicy) { this.OwnsConnection = true; } /// <summary> /// Creates a new AMQP MessageSender on a given <see cref="ServiceBusConnection"/> /// </summary> /// <param name="serviceBusConnection">Connection object to the service bus namespace.</param> /// <param name="entityPath">The path of the entity this sender should connect to.</param> /// <param name="retryPolicy">The <see cref="RetryPolicy"/> that will be used when communicating with Service Bus. Defaults to <see cref="RetryPolicy.Default"/></param> public MessageSender( ServiceBusConnection serviceBusConnection, string entityPath, RetryPolicy retryPolicy = null) : this(entityPath, null, null, serviceBusConnection, null, retryPolicy) { this.OwnsConnection = false; } /// <summary> /// Creates a ViaMessageSender. This can be used to send messages to a destination entity via another another entity. /// </summary> /// <param name="serviceBusConnection">Connection object to the service bus namespace.</param> /// <param name="entityPath">The final destination of the message.</param> /// <param name="viaEntityPath">The first destination of the message.</param> /// <param name="retryPolicy">The <see cref="RetryPolicy"/> that will be used when communicating with Service Bus. Defaults to <see cref="RetryPolicy.Default"/></param> /// <remarks> /// This is mainly to be used when sending messages in a transaction. /// When messages need to be sent across entities in a single transaction, this can be used to ensure /// all the messages land initially in the same entity/partition for local transactions, and then /// let service bus handle transferring the message to the actual destination. /// </remarks> public MessageSender( ServiceBusConnection serviceBusConnection, string entityPath, string viaEntityPath, RetryPolicy retryPolicy = null) :this(viaEntityPath, entityPath, null, serviceBusConnection, null, retryPolicy) { this.OwnsConnection = false; } internal MessageSender( string entityPath, string transferDestinationPath, MessagingEntityType? entityType, ServiceBusConnection serviceBusConnection, ICbsTokenProvider cbsTokenProvider, RetryPolicy retryPolicy) : base(nameof(MessageSender), entityPath, retryPolicy ?? RetryPolicy.Default) { MessagingEventSource.Log.MessageSenderCreateStart(serviceBusConnection?.Endpoint.Authority, entityPath); if (string.IsNullOrWhiteSpace(entityPath)) { throw Fx.Exception.ArgumentNullOrWhiteSpace(entityPath); } this.ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); this.Path = entityPath; this.SendingLinkDestination = entityPath; this.EntityType = entityType; this.ServiceBusConnection.ThrowIfClosed(); if (cbsTokenProvider != null) { this.CbsTokenProvider = cbsTokenProvider; } else if (this.ServiceBusConnection.TokenProvider != null) { this.CbsTokenProvider = new TokenProviderAdapter(this.ServiceBusConnection.TokenProvider, this.ServiceBusConnection.OperationTimeout); } else { throw new ArgumentNullException($"{nameof(ServiceBusConnection)} doesn't have a valid token provider"); } this.SendLinkManager = new FaultTolerantAmqpObject<SendingAmqpLink>(this.CreateLinkAsync, CloseSession); this.RequestResponseLinkManager = new FaultTolerantAmqpObject<RequestResponseAmqpLink>(this.CreateRequestResponseLinkAsync, CloseRequestResponseSession); this.clientLinkManager = new ActiveClientLinkManager(this, this.CbsTokenProvider); this.diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); if (!string.IsNullOrWhiteSpace(transferDestinationPath)) { this.isViaSender = true; this.TransferDestinationPath = transferDestinationPath; this.ViaEntityPath = entityPath; } MessagingEventSource.Log.MessageSenderCreateStop(serviceBusConnection.Endpoint.Authority, entityPath, this.ClientId); } /// <summary> /// Gets a list of currently registered plugins for this sender. /// </summary> /// <seealso cref="RegisterPlugin"/> public override IList<ServiceBusPlugin> RegisteredPlugins { get; } = new List<ServiceBusPlugin>(); /// <summary> /// Gets the entity path of the MessageSender. /// In the case of a via-sender, this returns the path of the via entity. /// </summary> public override string Path { get; } /// <summary> /// In the case of a via-sender, gets the final destination path of the messages; null otherwise. /// </summary> public string TransferDestinationPath { get; } /// <summary> /// In the case of a via-sender, the message is sent to <see cref="TransferDestinationPath"/> via <see cref="ViaEntityPath"/>; null otherwise. /// </summary> public string ViaEntityPath { get; } /// <summary> /// Duration after which individual operations will timeout. /// </summary> public override TimeSpan OperationTimeout { get => this.ServiceBusConnection.OperationTimeout; set => this.ServiceBusConnection.OperationTimeout = value; } /// <summary> /// Connection object to the service bus namespace. /// </summary> public override ServiceBusConnection ServiceBusConnection { get; } internal MessagingEntityType? EntityType { get; } internal string SendingLinkDestination { get; set; } ICbsTokenProvider CbsTokenProvider { get; } FaultTolerantAmqpObject<SendingAmqpLink> SendLinkManager { get; } FaultTolerantAmqpObject<RequestResponseAmqpLink> RequestResponseLinkManager { get; } /// <summary> /// Sends a message to the entity as described by <see cref="Path"/>. /// </summary> public Task SendAsync(Message message) { return this.SendAsync(new[] { message }); } /// <summary> /// Sends a list of messages to the entity as described by <see cref="Path"/>. /// When called on partitioned entities, messages meant for different partitions cannot be batched together. /// </summary> public async Task SendAsync(IList<Message> messageList) { this.ThrowIfClosed(); var count = MessageSender.ValidateMessages(messageList); if (count <= 0) { return; } MessagingEventSource.Log.MessageSendStart(this.ClientId, count); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.SendStart(messageList) : null; Task sendTask = null; try { var processedMessages = await this.ProcessMessages(messageList).ConfigureAwait(false); sendTask = this.RetryPolicy.RunOperation(() => this.OnSendAsync(processedMessages), this.OperationTimeout); await sendTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { this.diagnosticSource.ReportException(exception); } MessagingEventSource.Log.MessageSendException(this.ClientId, exception); throw; } finally { this.diagnosticSource.SendStop(activity, messageList, sendTask?.Status); } MessagingEventSource.Log.MessageSendStop(this.ClientId); } /// <summary> /// Schedules a message to appear on Service Bus at a later time. /// </summary> /// <param name="message">The <see cref="Message"/> that needs to be scheduled.</param> /// <param name="scheduleEnqueueTimeUtc">The UTC time at which the message should be available for processing</param> /// <returns>The sequence number of the message that was scheduled.</returns> public async Task<long> ScheduleMessageAsync(Message message, DateTimeOffset scheduleEnqueueTimeUtc) { this.ThrowIfClosed(); if (message == null) { throw Fx.Exception.ArgumentNull(nameof(message)); } if (scheduleEnqueueTimeUtc.CompareTo(DateTimeOffset.UtcNow) < 0) { throw Fx.Exception.ArgumentOutOfRange( nameof(scheduleEnqueueTimeUtc), scheduleEnqueueTimeUtc.ToString(), "Cannot schedule messages in the past"); } if (this.isViaSender && Transaction.Current != null) { throw new ServiceBusException(false, $"{nameof(ScheduleMessageAsync)} method is not supported in a Via-Sender with transactions."); } message.ScheduledEnqueueTimeUtc = scheduleEnqueueTimeUtc.UtcDateTime; MessageSender.ValidateMessage(message); MessagingEventSource.Log.ScheduleMessageStart(this.ClientId, scheduleEnqueueTimeUtc); long result = 0; bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.ScheduleStart(message, scheduleEnqueueTimeUtc) : null; Task scheduleTask = null; try { var processedMessage = await this.ProcessMessage(message).ConfigureAwait(false); scheduleTask = this.RetryPolicy.RunOperation( async () => { result = await this.OnScheduleMessageAsync(processedMessage).ConfigureAwait(false); }, this.OperationTimeout); await scheduleTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { this.diagnosticSource.ReportException(exception); } MessagingEventSource.Log.ScheduleMessageException(this.ClientId, exception); throw; } finally { this.diagnosticSource.ScheduleStop(activity, message, scheduleEnqueueTimeUtc, scheduleTask?.Status, result); } MessagingEventSource.Log.ScheduleMessageStop(this.ClientId); return result; } /// <summary> /// Cancels a message that was scheduled. /// </summary> /// <param name="sequenceNumber">The <see cref="Message.SystemPropertiesCollection.SequenceNumber"/> of the message to be cancelled.</param> public async Task CancelScheduledMessageAsync(long sequenceNumber) { this.ThrowIfClosed(); if (Transaction.Current != null) { throw new ServiceBusException(false, $"{nameof(CancelScheduledMessageAsync)} method is not supported within a transaction."); } MessagingEventSource.Log.CancelScheduledMessageStart(this.ClientId, sequenceNumber); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.CancelStart(sequenceNumber) : null; Task cancelTask = null; try { cancelTask = this.RetryPolicy.RunOperation(() => this.OnCancelScheduledMessageAsync(sequenceNumber), this.OperationTimeout); await cancelTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { this.diagnosticSource.ReportException(exception); } MessagingEventSource.Log.CancelScheduledMessageException(this.ClientId, exception); throw; } finally { this.diagnosticSource.CancelStop(activity, sequenceNumber, cancelTask?.Status); } MessagingEventSource.Log.CancelScheduledMessageStop(this.ClientId); } /// <summary> /// Registers a <see cref="ServiceBusPlugin"/> to be used with this sender. /// </summary> /// <param name="serviceBusPlugin">The <see cref="ServiceBusPlugin"/> to register.</param> public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) { this.ThrowIfClosed(); if (serviceBusPlugin == null) { throw new ArgumentNullException(nameof(serviceBusPlugin), Resources.ArgumentNullOrWhiteSpace.FormatForUser(nameof(serviceBusPlugin))); } if (this.RegisteredPlugins.Any(p => p.GetType() == serviceBusPlugin.GetType())) { throw new ArgumentException(nameof(serviceBusPlugin), Resources.PluginAlreadyRegistered.FormatForUser(serviceBusPlugin.Name)); } this.RegisteredPlugins.Add(serviceBusPlugin); } /// <summary> /// Unregisters a <see cref="ServiceBusPlugin"/>. /// </summary> /// <param name="serviceBusPluginName">The name <see cref="ServiceBusPlugin.Name"/> to be unregistered</param> public override void UnregisterPlugin(string serviceBusPluginName) { this.ThrowIfClosed(); if (string.IsNullOrWhiteSpace(serviceBusPluginName)) { throw new ArgumentNullException(nameof(serviceBusPluginName), Resources.ArgumentNullOrWhiteSpace.FormatForUser(nameof(serviceBusPluginName))); } if (this.RegisteredPlugins.Any(p => p.Name == serviceBusPluginName)) { var plugin = this.RegisteredPlugins.First(p => p.Name == serviceBusPluginName); this.RegisteredPlugins.Remove(plugin); } } internal async Task<AmqpResponseMessage> ExecuteRequestResponseAsync(AmqpRequestMessage amqpRequestMessage) { var amqpMessage = amqpRequestMessage.AmqpMessage; var timeoutHelper = new TimeoutHelper(this.OperationTimeout, true); ArraySegment<byte> transactionId = AmqpConstants.NullBinary; var ambientTransaction = Transaction.Current; if (ambientTransaction != null) { transactionId = await AmqpTransactionManager.Instance.EnlistAsync(ambientTransaction, this.ServiceBusConnection).ConfigureAwait(false); } if (!this.RequestResponseLinkManager.TryGetOpenedObject(out var requestResponseAmqpLink)) { requestResponseAmqpLink = await this.RequestResponseLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } var responseAmqpMessage = await Task.Factory.FromAsync( (c, s) => requestResponseAmqpLink.BeginRequest(amqpMessage, transactionId, timeoutHelper.RemainingTime(), c, s), a => requestResponseAmqpLink.EndRequest(a), this).ConfigureAwait(false); return AmqpResponseMessage.CreateResponse(responseAmqpMessage); } /// <summary>Closes the connection.</summary> protected override async Task OnClosingAsync() { this.clientLinkManager.Close(); await this.SendLinkManager.CloseAsync().ConfigureAwait(false); await this.RequestResponseLinkManager.CloseAsync().ConfigureAwait(false); } static int ValidateMessages(IList<Message> messageList) { var count = 0; if (messageList == null) { throw Fx.Exception.ArgumentNull(nameof(messageList)); } foreach (var message in messageList) { count++; ValidateMessage(message); } return count; } static void ValidateMessage(Message message) { if (message.SystemProperties.IsLockTokenSet) { throw Fx.Exception.Argument(nameof(message), "Cannot send a message that was already received."); } } static void CloseSession(SendingAmqpLink link) { // Note we close the session (which includes the link). link.Session.SafeClose(); } static void CloseRequestResponseSession(RequestResponseAmqpLink requestResponseAmqpLink) { requestResponseAmqpLink.Session.SafeClose(); } async Task<Message> ProcessMessage(Message message) { var processedMessage = message; foreach (var plugin in this.RegisteredPlugins) { try { MessagingEventSource.Log.PluginCallStarted(plugin.Name, message.MessageId); processedMessage = await plugin.BeforeMessageSend(message).ConfigureAwait(false); MessagingEventSource.Log.PluginCallCompleted(plugin.Name, message.MessageId); } catch (Exception ex) { MessagingEventSource.Log.PluginCallFailed(plugin.Name, message.MessageId, ex); if (!plugin.ShouldContinueOnException) { throw; } } } return processedMessage; } async Task<IList<Message>> ProcessMessages(IList<Message> messageList) { if (this.RegisteredPlugins.Count < 1) { return messageList; } var processedMessageList = new List<Message>(); foreach (var message in messageList) { var processedMessage = await this.ProcessMessage(message).ConfigureAwait(false); processedMessageList.Add(processedMessage); } return processedMessageList; } async Task OnSendAsync(IList<Message> messageList) { var timeoutHelper = new TimeoutHelper(this.OperationTimeout, true); using (var amqpMessage = AmqpMessageConverter.BatchSBMessagesAsAmqpMessage(messageList)) { SendingAmqpLink amqpLink = null; try { ArraySegment<byte> transactionId = AmqpConstants.NullBinary; var ambientTransaction = Transaction.Current; if (ambientTransaction != null) { transactionId = await AmqpTransactionManager.Instance.EnlistAsync(ambientTransaction, this.ServiceBusConnection).ConfigureAwait(false); } if (!this.SendLinkManager.TryGetOpenedObject(out amqpLink)) { amqpLink = await this.SendLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } if (amqpLink.Settings.MaxMessageSize.HasValue) { var size = (ulong)amqpMessage.SerializedMessageSize; if (size > amqpLink.Settings.MaxMessageSize.Value) { throw new MessageSizeExceededException(Resources.AmqpMessageSizeExceeded.FormatForUser(amqpMessage.DeliveryId.Value, size, amqpLink.Settings.MaxMessageSize.Value)); } } var outcome = await amqpLink.SendMessageAsync(amqpMessage, this.GetNextDeliveryTag(), transactionId, timeoutHelper.RemainingTime()).ConfigureAwait(false); if (outcome.DescriptorCode != Accepted.Code) { var rejected = (Rejected)outcome; throw Fx.Exception.AsError(rejected.Error.ToMessagingContractException()); } } catch (Exception exception) { throw AmqpExceptionHelper.GetClientException(exception, amqpLink?.GetTrackingId(), null, amqpLink?.Session.IsClosing() ?? false); } } } async Task<long> OnScheduleMessageAsync(Message message) { using (var amqpMessage = AmqpMessageConverter.SBMessageToAmqpMessage(message)) { var request = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.ScheduleMessageOperation, this.OperationTimeout, null); SendingAmqpLink sendLink = null; try { if (this.SendLinkManager.TryGetOpenedObject(out sendLink)) { request.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = sendLink.Name; } ArraySegment<byte>[] payload = amqpMessage.GetPayload(); var buffer = new BufferListStream(payload); ArraySegment<byte> value = buffer.ReadBytes((int)buffer.Length); var entry = new AmqpMap(); { entry[ManagementConstants.Properties.Message] = value; entry[ManagementConstants.Properties.MessageId] = message.MessageId; if (!string.IsNullOrWhiteSpace(message.SessionId)) { entry[ManagementConstants.Properties.SessionId] = message.SessionId; } if (!string.IsNullOrWhiteSpace(message.PartitionKey)) { entry[ManagementConstants.Properties.PartitionKey] = message.PartitionKey; } if (!string.IsNullOrWhiteSpace(message.ViaPartitionKey)) { entry[ManagementConstants.Properties.ViaPartitionKey] = message.ViaPartitionKey; } } request.Map[ManagementConstants.Properties.Messages] = new List<AmqpMap> { entry }; var response = await this.ExecuteRequestResponseAsync(request).ConfigureAwait(false); if (response.StatusCode == AmqpResponseStatusCode.OK) { var sequenceNumbers = response.GetValue<long[]>(ManagementConstants.Properties.SequenceNumbers); if (sequenceNumbers == null || sequenceNumbers.Length < 1) { throw new ServiceBusException(true, "Could not schedule message successfully."); } return sequenceNumbers[0]; } else { throw response.ToMessagingContractException(); } } catch (Exception exception) { throw AmqpExceptionHelper.GetClientException(exception, sendLink?.GetTrackingId(), null, sendLink?.Session.IsClosing() ?? false); } } } async Task OnCancelScheduledMessageAsync(long sequenceNumber) { var request = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.CancelScheduledMessageOperation, this.OperationTimeout, null); SendingAmqpLink sendLink = null; try { if (this.SendLinkManager.TryGetOpenedObject(out sendLink)) { request.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = sendLink.Name; } request.Map[ManagementConstants.Properties.SequenceNumbers] = new[] { sequenceNumber }; var response = await this.ExecuteRequestResponseAsync(request).ConfigureAwait(false); if (response.StatusCode != AmqpResponseStatusCode.OK) { throw response.ToMessagingContractException(); } } catch (Exception exception) { throw AmqpExceptionHelper.GetClientException(exception, sendLink?.GetTrackingId(), null, sendLink?.Session.IsClosing() ?? false); } } async Task<SendingAmqpLink> CreateLinkAsync(TimeSpan timeout) { MessagingEventSource.Log.AmqpSendLinkCreateStart(this.ClientId, this.EntityType, this.SendingLinkDestination); var amqpLinkSettings = new AmqpLinkSettings { Role = false, InitialDeliveryCount = 0, Target = new Target { Address = this.SendingLinkDestination }, Source = new Source { Address = this.ClientId }, }; if (this.EntityType != null) { amqpLinkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)this.EntityType); } var endpointUri = new Uri(this.ServiceBusConnection.Endpoint, this.SendingLinkDestination); string[] audience; if (this.isViaSender) { var transferDestinationEndpointUri = new Uri(this.ServiceBusConnection.Endpoint, this.TransferDestinationPath); audience = new string[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; amqpLinkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, this.TransferDestinationPath); } else { audience = new string[] { endpointUri.AbsoluteUri }; } string[] claims = {ClaimConstants.Send}; var amqpSendReceiveLinkCreator = new AmqpSendReceiveLinkCreator(this.SendingLinkDestination, this.ServiceBusConnection, endpointUri, audience, claims, this.CbsTokenProvider, amqpLinkSettings, this.ClientId); Tuple<AmqpObject, DateTime> linkDetails = await amqpSendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); var sendingAmqpLink = (SendingAmqpLink) linkDetails.Item1; var activeSendReceiveClientLink = new ActiveSendReceiveClientLink( sendingAmqpLink, endpointUri, audience, claims, linkDetails.Item2); this.clientLinkManager.SetActiveSendReceiveLink(activeSendReceiveClientLink); MessagingEventSource.Log.AmqpSendLinkCreateStop(this.ClientId); return sendingAmqpLink; } async Task<RequestResponseAmqpLink> CreateRequestResponseLinkAsync(TimeSpan timeout) { var entityPath = this.SendingLinkDestination + '/' + AmqpClientConstants.ManagementAddress; var amqpLinkSettings = new AmqpLinkSettings(); amqpLinkSettings.AddProperty(AmqpClientConstants.EntityTypeName, AmqpClientConstants.EntityTypeManagement); var endpointUri = new Uri(this.ServiceBusConnection.Endpoint, entityPath); string[] audience; if (this.isViaSender) { var transferDestinationEndpointUri = new Uri(this.ServiceBusConnection.Endpoint, this.TransferDestinationPath); audience = new string[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; amqpLinkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, this.TransferDestinationPath); } else { audience = new string[] { endpointUri.AbsoluteUri }; } string[] claims = { ClaimConstants.Manage, ClaimConstants.Send }; var amqpRequestResponseLinkCreator = new AmqpRequestResponseLinkCreator( entityPath, this.ServiceBusConnection, endpointUri, audience, claims, this.CbsTokenProvider, amqpLinkSettings, this.ClientId); Tuple<AmqpObject, DateTime> linkDetails = await amqpRequestResponseLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); var requestResponseAmqpLink = (RequestResponseAmqpLink) linkDetails.Item1; var activeRequestResponseClientLink = new ActiveRequestResponseLink( requestResponseAmqpLink, endpointUri, audience, claims, linkDetails.Item2); this.clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); return requestResponseAmqpLink; } ArraySegment<byte> GetNextDeliveryTag() { var deliveryId = Interlocked.Increment(ref this.deliveryCount); return new ArraySegment<byte>(BitConverter.GetBytes(deliveryId)); } } }
using Lucene.Net.Diagnostics; using Lucene.Net.Search; using Lucene.Net.Util; using Lucene.Net.Util.Automaton; using System; using System.Collections.Generic; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Wraps a <see cref="Index.Fields"/> but with additional asserts /// </summary> public class AssertingFields : FilterAtomicReader.FilterFields { public AssertingFields(Fields input) : base(input) { } public override IEnumerator<string> GetEnumerator() { IEnumerator<string> iterator = base.GetEnumerator(); if (Debugging.AssertsEnabled) Debugging.Assert(iterator != null); return iterator; } public override Terms GetTerms(string field) { Terms terms = base.GetTerms(field); return terms == null ? null : new AssertingTerms(terms); } } /// <summary> /// Wraps a <see cref="Terms"/> but with additional asserts /// </summary> public class AssertingTerms : FilterAtomicReader.FilterTerms { public AssertingTerms(Terms input) : base(input) { } public override TermsEnum Intersect(CompiledAutomaton automaton, BytesRef bytes) { TermsEnum termsEnum = m_input.Intersect(automaton, bytes); if (Debugging.AssertsEnabled) Debugging.Assert(termsEnum != null); if (Debugging.AssertsEnabled) Debugging.Assert(bytes == null || bytes.IsValid()); return new AssertingAtomicReader.AssertingTermsEnum(termsEnum); } public override TermsEnum GetEnumerator() { var termsEnum = base.GetEnumerator(); if (Debugging.AssertsEnabled) Debugging.Assert(termsEnum != null); return new AssertingAtomicReader.AssertingTermsEnum(termsEnum); } public override TermsEnum GetEnumerator(TermsEnum reuse) { // TODO: should we give this thing a random to be super-evil, // and randomly *not* unwrap? if (!(reuse is null) && reuse is AssertingAtomicReader.AssertingTermsEnum reusable) { reuse = reusable.m_input; } TermsEnum termsEnum = base.GetEnumerator(reuse); if (Debugging.AssertsEnabled) Debugging.Assert(termsEnum != null); return new AssertingAtomicReader.AssertingTermsEnum(termsEnum); } } internal enum DocsEnumState { START, ITERATING, FINISHED } /// <summary> /// Wraps a <see cref="DocsEnum"/> with additional checks </summary> public class AssertingDocsEnum : FilterAtomicReader.FilterDocsEnum { private DocsEnumState state = DocsEnumState.START; private int doc; public AssertingDocsEnum(DocsEnum @in) : this(@in, true) { } public AssertingDocsEnum(DocsEnum @in, bool failOnUnsupportedDocID) : base(@in) { try { int docid = @in.DocID; if (Debugging.AssertsEnabled) Debugging.Assert(docid == -1, () => @in.GetType() + ": invalid initial doc id: " + docid); } catch (NotSupportedException /*e*/) { if (failOnUnsupportedDocID) { throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) } } doc = -1; } public override int NextDoc() { if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.FINISHED, "NextDoc() called after NO_MORE_DOCS"); int nextDoc = base.NextDoc(); if (Debugging.AssertsEnabled) Debugging.Assert(nextDoc > doc, () => "backwards NextDoc from " + doc + " to " + nextDoc + " " + m_input); if (nextDoc == DocIdSetIterator.NO_MORE_DOCS) { state = DocsEnumState.FINISHED; } else { state = DocsEnumState.ITERATING; } if (Debugging.AssertsEnabled) Debugging.Assert(base.DocID == nextDoc); return doc = nextDoc; } public override int Advance(int target) { if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.FINISHED, "Advance() called after NO_MORE_DOCS"); if (Debugging.AssertsEnabled) Debugging.Assert(target > doc, () => "target must be > DocID, got " + target + " <= " + doc); int advanced = base.Advance(target); if (Debugging.AssertsEnabled) Debugging.Assert(advanced >= target, () => "backwards advance from: " + target + " to: " + advanced); if (advanced == DocIdSetIterator.NO_MORE_DOCS) { state = DocsEnumState.FINISHED; } else { state = DocsEnumState.ITERATING; } if (Debugging.AssertsEnabled) Debugging.Assert(base.DocID == advanced); return doc = advanced; } public override int DocID { get { if (Debugging.AssertsEnabled) Debugging.Assert(doc == base.DocID, () => " invalid DocID in " + m_input.GetType() + " " + base.DocID + " instead of " + doc); return doc; } } public override int Freq { get { if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.START, "Freq called before NextDoc()/Advance()"); if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.FINISHED, "Freq called after NO_MORE_DOCS"); int freq = base.Freq; if (Debugging.AssertsEnabled) Debugging.Assert(freq > 0); return freq; } } } /// <summary> /// Wraps a <see cref="NumericDocValues"/> but with additional asserts </summary> public class AssertingNumericDocValues : NumericDocValues { private readonly NumericDocValues @in; private readonly int maxDoc; public AssertingNumericDocValues(NumericDocValues @in, int maxDoc) { this.@in = @in; this.maxDoc = maxDoc; } public override long Get(int docID) { if (Debugging.AssertsEnabled) Debugging.Assert(docID >= 0 && docID < maxDoc); return @in.Get(docID); } } /// <summary> /// Wraps a <see cref="BinaryDocValues"/> but with additional asserts </summary> public class AssertingBinaryDocValues : BinaryDocValues { private readonly BinaryDocValues @in; private readonly int maxDoc; public AssertingBinaryDocValues(BinaryDocValues @in, int maxDoc) { this.@in = @in; this.maxDoc = maxDoc; } public override void Get(int docID, BytesRef result) { if (Debugging.AssertsEnabled) Debugging.Assert(docID >= 0 && docID < maxDoc); if (Debugging.AssertsEnabled) Debugging.Assert(result.IsValid()); @in.Get(docID, result); if (Debugging.AssertsEnabled) Debugging.Assert(result.IsValid()); } } /// <summary> /// Wraps a <see cref="SortedDocValues"/> but with additional asserts </summary> public class AssertingSortedDocValues : SortedDocValues { private readonly SortedDocValues @in; private readonly int maxDoc; private readonly int valueCount; public AssertingSortedDocValues(SortedDocValues @in, int maxDoc) { this.@in = @in; this.maxDoc = maxDoc; this.valueCount = @in.ValueCount; if (Debugging.AssertsEnabled) Debugging.Assert(valueCount >= 0 && valueCount <= maxDoc); } public override int GetOrd(int docID) { if (Debugging.AssertsEnabled) Debugging.Assert(docID >= 0 && docID < maxDoc); int ord = @in.GetOrd(docID); if (Debugging.AssertsEnabled) Debugging.Assert(ord >= -1 && ord < valueCount); return ord; } public override void LookupOrd(int ord, BytesRef result) { if (Debugging.AssertsEnabled) Debugging.Assert(ord >= 0 && ord < valueCount); if (Debugging.AssertsEnabled) Debugging.Assert(result.IsValid()); @in.LookupOrd(ord, result); if (Debugging.AssertsEnabled) Debugging.Assert(result.IsValid()); } public override int ValueCount { get { int valueCount = @in.ValueCount; if (Debugging.AssertsEnabled) Debugging.Assert(valueCount == this.valueCount); // should not change return valueCount; } } public override void Get(int docID, BytesRef result) { if (Debugging.AssertsEnabled) Debugging.Assert(docID >= 0 && docID < maxDoc); if (Debugging.AssertsEnabled) Debugging.Assert(result.IsValid()); @in.Get(docID, result); if (Debugging.AssertsEnabled) Debugging.Assert(result.IsValid()); } public override int LookupTerm(BytesRef key) { if (Debugging.AssertsEnabled) Debugging.Assert(key.IsValid()); int result = @in.LookupTerm(key); if (Debugging.AssertsEnabled) Debugging.Assert(result < valueCount); if (Debugging.AssertsEnabled) Debugging.Assert(key.IsValid()); return result; } } /// <summary> /// Wraps a <see cref="SortedSetDocValues"/> but with additional asserts </summary> public class AssertingSortedSetDocValues : SortedSetDocValues { private readonly SortedSetDocValues @in; private readonly int maxDoc; private readonly long valueCount; private long lastOrd = NO_MORE_ORDS; public AssertingSortedSetDocValues(SortedSetDocValues @in, int maxDoc) { this.@in = @in; this.maxDoc = maxDoc; this.valueCount = @in.ValueCount; if (Debugging.AssertsEnabled) Debugging.Assert(valueCount >= 0); } public override long NextOrd() { if (Debugging.AssertsEnabled) Debugging.Assert(lastOrd != NO_MORE_ORDS); long ord = @in.NextOrd(); if (Debugging.AssertsEnabled) Debugging.Assert(ord < valueCount); if (Debugging.AssertsEnabled) Debugging.Assert(ord == NO_MORE_ORDS || ord > lastOrd); lastOrd = ord; return ord; } public override void SetDocument(int docID) { if (Debugging.AssertsEnabled) Debugging.Assert(docID >= 0 && docID < maxDoc, () => "docid=" + docID + ",maxDoc=" + maxDoc); @in.SetDocument(docID); lastOrd = -2; } public override void LookupOrd(long ord, BytesRef result) { if (Debugging.AssertsEnabled) Debugging.Assert(ord >= 0 && ord < valueCount); if (Debugging.AssertsEnabled) Debugging.Assert(result.IsValid()); @in.LookupOrd(ord, result); if (Debugging.AssertsEnabled) Debugging.Assert(result.IsValid()); } public override long ValueCount { get { long valueCount = @in.ValueCount; if (Debugging.AssertsEnabled) Debugging.Assert(valueCount == this.valueCount); // should not change return valueCount; } } public override long LookupTerm(BytesRef key) { if (Debugging.AssertsEnabled) Debugging.Assert(key.IsValid()); long result = @in.LookupTerm(key); if (Debugging.AssertsEnabled) Debugging.Assert(result < valueCount); if (Debugging.AssertsEnabled) Debugging.Assert(key.IsValid()); return result; } } /// <summary> /// Wraps a <see cref="IBits"/> but with additional asserts </summary> public class AssertingBits : IBits { internal readonly IBits @in; public AssertingBits(IBits @in) { this.@in = @in; } public virtual bool Get(int index) { if (Debugging.AssertsEnabled) Debugging.Assert(index >= 0 && index < Length); return @in.Get(index); } public virtual int Length => @in.Length; } /// <summary> /// A <see cref="FilterAtomicReader"/> that can be used to apply /// additional checks for tests. /// </summary> public class AssertingAtomicReader : FilterAtomicReader { public AssertingAtomicReader(AtomicReader @in) : base(@in) { // check some basic reader sanity if (Debugging.AssertsEnabled) Debugging.Assert(@in.MaxDoc >= 0); if (Debugging.AssertsEnabled) Debugging.Assert(@in.NumDocs <= @in.MaxDoc); if (Debugging.AssertsEnabled) Debugging.Assert(@in.NumDeletedDocs + @in.NumDocs == @in.MaxDoc); if (Debugging.AssertsEnabled) Debugging.Assert([email protected] || @in.NumDeletedDocs > 0 && @in.NumDocs < @in.MaxDoc); } public override Fields Fields { get { Fields fields = base.Fields; return fields == null ? null : new AssertingFields(fields); } } public override Fields GetTermVectors(int docID) { Fields fields = base.GetTermVectors(docID); return fields == null ? null : new AssertingFields(fields); } // LUCENENET specific - de-nested AssertingFields // LUCENENET specific - de-nested AssertingTerms // LUCENENET specific - de-nested AssertingTermsEnum internal class AssertingTermsEnum : FilterTermsEnum { private enum State { INITIAL, POSITIONED, UNPOSITIONED } private State state = State.INITIAL; public AssertingTermsEnum(TermsEnum @in) : base(@in) { } public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { if (Debugging.AssertsEnabled) Debugging.Assert(state == State.POSITIONED, "Docs(...) called on unpositioned TermsEnum"); // TODO: should we give this thing a random to be super-evil, // and randomly *not* unwrap? if (reuse is AssertingDocsEnum) { reuse = ((AssertingDocsEnum)reuse).m_input; } DocsEnum docs = base.Docs(liveDocs, reuse, flags); return docs == null ? null : new AssertingDocsEnum(docs); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { if (Debugging.AssertsEnabled) Debugging.Assert(state == State.POSITIONED, "DocsAndPositions(...) called on unpositioned TermsEnum"); // TODO: should we give this thing a random to be super-evil, // and randomly *not* unwrap? if (reuse is AssertingDocsAndPositionsEnum) { reuse = ((AssertingDocsAndPositionsEnum)reuse).m_input; } DocsAndPositionsEnum docs = base.DocsAndPositions(liveDocs, reuse, flags); return docs == null ? null : new AssertingDocsAndPositionsEnum(docs); } public override bool MoveNext() { if (Debugging.AssertsEnabled) Debugging.Assert(state == State.INITIAL || state == State.POSITIONED, "MoveNext() called on unpositioned TermsEnum"); if (!base.MoveNext()) { state = State.UNPOSITIONED; return false; } else { if (Debugging.AssertsEnabled) Debugging.Assert(base.Term.IsValid()); state = State.POSITIONED; return true; } } // TODO: we should separately track if we are 'at the end' ? // someone should not call next() after it returns null!!!! [Obsolete("Use MoveNext() and Term instead. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override BytesRef Next() { if (Debugging.AssertsEnabled) Debugging.Assert(state == State.INITIAL || state == State.POSITIONED, "Next() called on unpositioned TermsEnum"); if (MoveNext()) return base.Term; return null; } public override long Ord { get { if (Debugging.AssertsEnabled) Debugging.Assert(state == State.POSITIONED, "Ord called on unpositioned TermsEnum"); return base.Ord; } } public override int DocFreq { get { if (Debugging.AssertsEnabled) Debugging.Assert(state == State.POSITIONED, "DocFreq called on unpositioned TermsEnum"); return base.DocFreq; } } public override long TotalTermFreq { get { if (Debugging.AssertsEnabled) Debugging.Assert(state == State.POSITIONED, "TotalTermFreq called on unpositioned TermsEnum"); return base.TotalTermFreq; } } public override BytesRef Term { get { if (Debugging.AssertsEnabled) Debugging.Assert(state == State.POSITIONED, "Term called on unpositioned TermsEnum"); BytesRef ret = base.Term; if (Debugging.AssertsEnabled) Debugging.Assert(ret == null || ret.IsValid()); return ret; } } public override void SeekExact(long ord) { base.SeekExact(ord); state = State.POSITIONED; } public override SeekStatus SeekCeil(BytesRef term) { if (Debugging.AssertsEnabled) Debugging.Assert(term.IsValid()); SeekStatus result = base.SeekCeil(term); if (result == SeekStatus.END) { state = State.UNPOSITIONED; } else { state = State.POSITIONED; } return result; } public override bool SeekExact(BytesRef text) { if (Debugging.AssertsEnabled) Debugging.Assert(text.IsValid()); if (base.SeekExact(text)) { state = State.POSITIONED; return true; } else { state = State.UNPOSITIONED; return false; } } public override TermState GetTermState() { if (Debugging.AssertsEnabled) Debugging.Assert(state == State.POSITIONED, "GetTermState() called on unpositioned TermsEnum"); return base.GetTermState(); } public override void SeekExact(BytesRef term, TermState state) { if (Debugging.AssertsEnabled) Debugging.Assert(term.IsValid()); base.SeekExact(term, state); this.state = State.POSITIONED; } } // LUCENENET specific - de-nested DocsEnumState // LUCENENET specific - de-nested AssertingDocsEnum internal class AssertingDocsAndPositionsEnum : FilterDocsAndPositionsEnum { private DocsEnumState state = DocsEnumState.START; private int positionMax = 0; private int positionCount = 0; private int doc; public AssertingDocsAndPositionsEnum(DocsAndPositionsEnum @in) : base(@in) { int docid = @in.DocID; if (Debugging.AssertsEnabled) Debugging.Assert(docid == -1, () => "invalid initial doc id: " + docid); doc = -1; } public override int NextDoc() { if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.FINISHED, "NextDoc() called after NO_MORE_DOCS"); int nextDoc = base.NextDoc(); if (Debugging.AssertsEnabled) Debugging.Assert(nextDoc > doc, () => "backwards nextDoc from " + doc + " to " + nextDoc); positionCount = 0; if (nextDoc == DocIdSetIterator.NO_MORE_DOCS) { state = DocsEnumState.FINISHED; positionMax = 0; } else { state = DocsEnumState.ITERATING; positionMax = base.Freq; } if (Debugging.AssertsEnabled) Debugging.Assert(base.DocID == nextDoc); return doc = nextDoc; } public override int Advance(int target) { if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.FINISHED, "Advance() called after NO_MORE_DOCS"); if (Debugging.AssertsEnabled) Debugging.Assert(target > doc, () => "target must be > DocID, got " + target + " <= " + doc); int advanced = base.Advance(target); if (Debugging.AssertsEnabled) Debugging.Assert(advanced >= target, () => "backwards advance from: " + target + " to: " + advanced); positionCount = 0; if (advanced == DocIdSetIterator.NO_MORE_DOCS) { state = DocsEnumState.FINISHED; positionMax = 0; } else { state = DocsEnumState.ITERATING; positionMax = base.Freq; } if (Debugging.AssertsEnabled) Debugging.Assert(base.DocID == advanced); return doc = advanced; } public override int DocID { get { if (Debugging.AssertsEnabled) Debugging.Assert(doc == base.DocID, () => " invalid DocID in " + m_input.GetType() + " " + base.DocID + " instead of " + doc); return doc; } } public override int Freq { get { if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.START, "Freq called before NextDoc()/Advance()"); if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.FINISHED, "Freq called after NO_MORE_DOCS"); int freq = base.Freq; if (Debugging.AssertsEnabled) Debugging.Assert(freq > 0); return freq; } } public override int NextPosition() { if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.START, "NextPosition() called before NextDoc()/Advance()"); if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.FINISHED, "NextPosition() called after NO_MORE_DOCS"); if (Debugging.AssertsEnabled) Debugging.Assert(positionCount < positionMax, "NextPosition() called more than Freq times!"); int position = base.NextPosition(); if (Debugging.AssertsEnabled) Debugging.Assert(position >= 0 || position == -1, () => "invalid position: " + position); positionCount++; return position; } public override int StartOffset { get { if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.START, "StartOffset called before NextDoc()/Advance()"); if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.FINISHED, "StartOffset called after NO_MORE_DOCS"); if (Debugging.AssertsEnabled) Debugging.Assert(positionCount > 0, "StartOffset called before NextPosition()!"); return base.StartOffset; } } public override int EndOffset { get { if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.START, "EndOffset called before NextDoc()/Advance()"); if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.FINISHED, "EndOffset called after NO_MORE_DOCS"); if (Debugging.AssertsEnabled) Debugging.Assert(positionCount > 0, "EndOffset called before NextPosition()!"); return base.EndOffset; } } public override BytesRef GetPayload() { if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.START, "GetPayload() called before NextDoc()/Advance()"); if (Debugging.AssertsEnabled) Debugging.Assert(state != DocsEnumState.FINISHED, "GetPayload() called after NO_MORE_DOCS"); if (Debugging.AssertsEnabled) Debugging.Assert(positionCount > 0, "GetPayload() called before NextPosition()!"); BytesRef payload = base.GetPayload(); if (Debugging.AssertsEnabled) Debugging.Assert(payload == null || payload.IsValid() && payload.Length > 0, "GetPayload() returned payload with invalid length!"); return payload; } } // LUCENENET specific - de-nested AssertingNumericDocValues // LUCENENET specific - de-nested AssertingBinaryDocValues // LUCENENET specific - de-nested AssertingSortedDocValues // LUCENENET specific - de-nested AssertingSortedSetDocValues public override NumericDocValues GetNumericDocValues(string field) { NumericDocValues dv = base.GetNumericDocValues(field); FieldInfo fi = base.FieldInfos.FieldInfo(field); if (dv != null) { if (Debugging.AssertsEnabled) Debugging.Assert(fi != null); if (Debugging.AssertsEnabled) Debugging.Assert(fi.DocValuesType == DocValuesType.NUMERIC); return new AssertingNumericDocValues(dv, MaxDoc); } else { if (Debugging.AssertsEnabled) Debugging.Assert(fi == null || fi.DocValuesType != DocValuesType.NUMERIC); return null; } } public override BinaryDocValues GetBinaryDocValues(string field) { BinaryDocValues dv = base.GetBinaryDocValues(field); FieldInfo fi = base.FieldInfos.FieldInfo(field); if (dv != null) { if (Debugging.AssertsEnabled) Debugging.Assert(fi != null); if (Debugging.AssertsEnabled) Debugging.Assert(fi.DocValuesType == DocValuesType.BINARY); return new AssertingBinaryDocValues(dv, MaxDoc); } else { if (Debugging.AssertsEnabled) Debugging.Assert(fi == null || fi.DocValuesType != DocValuesType.BINARY); return null; } } public override SortedDocValues GetSortedDocValues(string field) { SortedDocValues dv = base.GetSortedDocValues(field); FieldInfo fi = base.FieldInfos.FieldInfo(field); if (dv != null) { if (Debugging.AssertsEnabled) Debugging.Assert(fi != null); if (Debugging.AssertsEnabled) Debugging.Assert(fi.DocValuesType == DocValuesType.SORTED); return new AssertingSortedDocValues(dv, MaxDoc); } else { if (Debugging.AssertsEnabled) Debugging.Assert(fi == null || fi.DocValuesType != DocValuesType.SORTED); return null; } } public override SortedSetDocValues GetSortedSetDocValues(string field) { SortedSetDocValues dv = base.GetSortedSetDocValues(field); FieldInfo fi = base.FieldInfos.FieldInfo(field); if (dv != null) { if (Debugging.AssertsEnabled) Debugging.Assert(fi != null); if (Debugging.AssertsEnabled) Debugging.Assert(fi.DocValuesType == DocValuesType.SORTED_SET); return new AssertingSortedSetDocValues(dv, MaxDoc); } else { if (Debugging.AssertsEnabled) Debugging.Assert(fi == null || fi.DocValuesType != DocValuesType.SORTED_SET); return null; } } public override NumericDocValues GetNormValues(string field) { NumericDocValues dv = base.GetNormValues(field); FieldInfo fi = base.FieldInfos.FieldInfo(field); if (dv != null) { if (Debugging.AssertsEnabled) Debugging.Assert(fi != null); if (Debugging.AssertsEnabled) Debugging.Assert(fi.HasNorms); return new AssertingNumericDocValues(dv, MaxDoc); } else { if (Debugging.AssertsEnabled) Debugging.Assert(fi == null || fi.HasNorms == false); return null; } } // LUCENENET specific - de-nested AssertingBits public override IBits LiveDocs { get { IBits liveDocs = base.LiveDocs; if (liveDocs != null) { if (Debugging.AssertsEnabled) Debugging.Assert(MaxDoc == liveDocs.Length); liveDocs = new AssertingBits(liveDocs); } else { if (Debugging.AssertsEnabled) Debugging.Assert(MaxDoc == NumDocs); if (Debugging.AssertsEnabled) Debugging.Assert(!HasDeletions); } return liveDocs; } } public override IBits GetDocsWithField(string field) { IBits docsWithField = base.GetDocsWithField(field); FieldInfo fi = base.FieldInfos.FieldInfo(field); if (docsWithField != null) { if (Debugging.AssertsEnabled) Debugging.Assert(fi != null); if (Debugging.AssertsEnabled) Debugging.Assert(fi.HasDocValues); if (Debugging.AssertsEnabled) Debugging.Assert(MaxDoc == docsWithField.Length); docsWithField = new AssertingBits(docsWithField); } else { if (Debugging.AssertsEnabled) Debugging.Assert(fi == null || fi.HasDocValues == false); } return docsWithField; } // this is the same hack as FCInvisible public override object CoreCacheKey => cacheKey; public override object CombinedCoreAndDeletesKey => cacheKey; private readonly object cacheKey = new object(); } }
using Intellisense.Common; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace RoslynIntellisense { public static class RoslynExtensions { public static string ToKindDisplayName(this TypeDeclarationSyntax type) { var kind = type.Kind(); return kind == SyntaxKind.ClassDeclaration ? "class" : kind == SyntaxKind.StructDeclaration ? "struct" : kind == SyntaxKind.EnumDeclaration ? "enum" : kind == SyntaxKind.InterfaceDeclaration ? "interface" : ""; } public static CompletionType ToCompletionType(this SymbolKind kind) { switch (kind) { case SymbolKind.Method: return CompletionType.method; case SymbolKind.Event: return CompletionType._event; case SymbolKind.Field: return CompletionType.field; case SymbolKind.Property: return CompletionType.property; case SymbolKind.NamedType: return CompletionType.type; case SymbolKind.Namespace: return CompletionType._namespace; case SymbolKind.Assembly: return CompletionType._namespace; default: return CompletionType.unresolved; } } public static string ResolveSymbolToTypeName(this ArgumentSyntax arg, Document doc) { string arg_text = arg.ToString(); if (arg_text.IsString()) return "string"; else if (arg_text.IsChar()) return "char"; else if (arg_text.IsChar()) return "char"; else if (arg_text.IsFloat()) return "float"; else if (arg_text.IsDecimal()) return "decimal"; else if (arg_text.IsDouble()) return "double"; else if (arg_text.IsByte()) return "byte"; else if (arg_text.IsLong()) return "long"; else if (arg_text.IsSbyte()) return "sbyte"; else if (arg_text.IsShort()) return "short"; else if (arg_text.IsUlong()) return "ulong"; else if (arg_text.IsInt()) return "int"; else if (arg_text.IsBool()) return "bool"; // if (arg_text.All(c => char.Is c.IsN "'") && arg_text.EndsWith("\'")) // { // return "char"; // } // var pos = arg.FullSpan.End - 1; // var arg_type = SymbolFinder.FindSymbolAtPositionAsync(doc, pos).Result; return ""; } public static string ToDecoratedName(this ITypeSymbol type) { string result = type.ToDisplayString(); if (!result.Contains('.')) return result; //if (clrAliaces.ContainsKey(result)) // return clrAliaces[result]; string nmspace = type.GetNamespace(); if (!string.IsNullOrEmpty(nmspace)) nmspace = "{" + nmspace + "}."; return (nmspace + type.Name); } public static string Reconstruct(this ISymbol symbol, bool includeDoc = true) { int pos; return symbol.Reconstruct(out pos, includeDoc); } public static DomRegion ToDomRegion(this Microsoft.CodeAnalysis.Location location) { //DomRegion is 1-based Editor friendly struct var linePosition = location.GetLineSpan().StartLinePosition; return new DomRegion { FileName = location.SourceTree.FilePath, BeginLine = linePosition.Line + 1, EndLine = linePosition.Line + 1, BeginColumn = linePosition.Character + 1, }; } public static string Reconstruct(this ISymbol symbol, out int startPosition, bool includeDoc = true, string header = "") { var code = new StringBuilder(); code.Append(header); startPosition = -1; int indent = 0; INamedTypeSymbol rootType = symbol.GetRootType(); //itself if it is a type or containing type if a member var usedNamespaces = rootType.UsedNamespaces(); if (usedNamespaces.HasAny()) { code.AppendLine(usedNamespaces.Select(x => $"using {x};").JoinBy(Environment.NewLine)); code.AppendLine(); } string nmsp = rootType.GetNamespace(); if (nmsp.HasAny()) { code.AppendLine(("namespace " + nmsp).IndentBy(indent)); code.AppendLine("{".IndentBy(indent++)); } var parentClasses = rootType.GetParentClasses(); foreach (var parent in parentClasses) //nested classes support code.AppendLine($"public {parent.TypeKind.ToString().ToLower()} ".IndentBy(indent) + parent.Name) .AppendLine("{".IndentBy(indent++)); startPosition = code.Length; var type = rootType.ToReflectedCode(includeDoc); type = type.IndentLinesBy(indent); code.AppendLine(type); //<doc>\r\n<declaration> startPosition += type.LastLineStart(); if (!rootType.IsDelegate()) { code.AppendLine("{".IndentBy(indent++)); string currentGroup = null; var members = rootType.GetMembers() .OrderBy(x => x.GetDisplayGroup()) .ThenByDescending(x => x.DeclaredAccessibility) .ThenBy(x => rootType.IsEnum() ? "" : x.Name); foreach (var item in members) { string memberInfo = item.ToReflectedCode(includeDoc, usePartials: true); if (memberInfo.HasAny()) { if (currentGroup != null && item.GetDisplayGroup() != currentGroup) code.AppendLine(); currentGroup = item.GetDisplayGroup(); var info = memberInfo.IndentLinesBy(indent); if (symbol == item || (symbol is IMethodSymbol && (symbol as IMethodSymbol).ReducedFrom == item)) startPosition = code.Length + info.LastLineStart(); code.AppendLine(info); } } code.AppendLine("}".IndentBy(--indent)); } foreach (var item in parentClasses) code.AppendLine("}".IndentBy(--indent)); if (nmsp.HasAny()) code.AppendLine("}".IndentBy(--indent)); return code.ToString().Trim(); } public static string IndentLinesBy(this string text, int indentLevel, string linePreffix = "") { return string.Join(Environment.NewLine, text.Replace("\r", "") .Split('\n') .Select(x => x.IndentBy(indentLevel, linePreffix)) .ToArray()); } public static string IndentBy(this string text, int indentLevel, string linePreffix = "") { var indent = new string(' ', indentLevel * 4); return indent + linePreffix + text; } public static string GetDocumentationComment(this ISymbol symbol, bool ignoreExceptionsInfo = false) { string xmlDoc = symbol.GetDocumentationCommentXml(); var sections = new List<string>(); var builder = new StringBuilder(); try { using (XmlTextReader reader = new XmlTextReader(new StringReader("<root>" + xmlDoc + "</root>"))) { string lastElementName = null; bool exceptionsStarted = false; reader.XmlResolver = null; while (reader.Read()) { var nodeType = reader.NodeType; switch (nodeType) { case XmlNodeType.Text: if (lastElementName == "summary") { builder.Insert(0, reader.Value.Shrink()); } else { if (exceptionsStarted) builder.Append(" "); if (lastElementName == "code") builder.Append(reader.Value); //need to preserve all formatting (line breaks and indents) else { //if (reflectionDocument) // b.Append(reader.Value.NormalizeLines()); //need to preserve line breaks but not indents //else builder.Append(reader.Value.Shrink()); } } break; case XmlNodeType.Element: { bool silentElement = false; switch (reader.Name) { case "filterpriority": reader.Skip(); break; case "root": case "summary": case "c": silentElement = true; break; case "paramref": silentElement = true; builder.Append(reader.GetAttribute("name")); break; case "param": silentElement = true; builder.AppendLine(); builder.Append(reader.GetAttribute("name") + ": "); break; case "para": silentElement = true; builder.AppendLine(); break; case "remarks": builder.AppendLine(); builder.Append("Remarks: "); break; case "returns": silentElement = true; builder.AppendLine(); builder.Append("Returns: "); break; case "exception": { if (!exceptionsStarted) { builder.AppendLine(); sections.Add(builder.ToString().Trim()); builder.Length = 0; if (!ignoreExceptionsInfo) builder.AppendLine("Exceptions: "); } exceptionsStarted = true; if (!ignoreExceptionsInfo && !reader.IsEmptyElement) { bool printExInfo = false; if (printExInfo) { builder.Append(" " + reader.GetCrefAttribute() + ": "); } else { builder.Append(" " + reader.GetCrefAttribute()); reader.Skip(); } } break; } case "see": silentElement = true; if (reader.IsEmptyElement) { builder.Append(reader.GetCrefAttribute()); } else { reader.MoveToContent(); if (reader.HasValue) { builder.Append(reader.Value); } else { builder.Append(reader.GetCrefAttribute()); } } break; } if (!silentElement) builder.AppendLine(); lastElementName = reader.Name; break; } case XmlNodeType.EndElement: { if (reader.Name == "summary") { builder.AppendLine(); sections.Add(builder.ToString().Trim()); builder.Length = 0; } else if (reader.Name == "returns") { builder.AppendLine(); sections.Add(builder.ToString().Trim()); builder.Length = 0; } break; } } } } sections.Add(builder.ToString().Trim()); string sectionSeparator = "\r\n--------------------------\r\n"; return string.Join(sectionSeparator, sections.Where(x => !string.IsNullOrEmpty(x)).ToArray()); } catch (XmlException) { return xmlDoc; } } static string ToTypeCode(this INamedTypeSymbol type, string modifiers, bool usePartials) { var code = new StringBuilder(150); if ((!type.IsEnum() && !type.IsDelegate()) && type.IsSealed) modifiers += "sealed "; string kind = type.IsInterface() ? "interface" : type.IsReferenceType ? "class" : type.IsEnum() ? "enum" : "struct"; if (type.IsDelegate()) { IMethodSymbol invokeMethod = type.GetMethod("Invoke"); code.Append($"{modifiers}delegate {invokeMethod.ReturnType.ToDisplayString()} {type.Name}") // public delegate int GetIndexDlgt // public class Filter .Append(type.TypeParameters.ToDeclarationString()) // <T, T2> .Append(invokeMethod.GetParametersString()) // (CustomIndex count, int? contextArg, T parent) .Append(type.TypeParameters.GetConstrains(singleLine: type.IsDelegate())) // where T: class .Append(";"); } else { //if (usePartials) // kind = "partial " + kind; code.Append($"{modifiers}{kind} {type.Name}") // public class Filter .Append(type.TypeParameters.ToDeclarationString()) // <T, T2> .Append(type.IsEnum() ? "" : type.ToInheritanceString()) // : IList<int> .Append(type.TypeParameters.GetConstrains(singleLine: type.IsDelegate())); // where T: class if (usePartials) code.Append(" { /*hidden*/ }"); } return code.ToString(); } static string ToPropertyCode(this IPropertySymbol symbol, string modifiers) { var code = new StringBuilder(150); if (symbol.ContainingType.IsInterface()) modifiers = ""; string getter = ""; string setter = ""; if (symbol.GetMethod != null) { if (symbol.GetMethod.DeclaredAccessibility == Accessibility.Protected) getter = "protected get; "; else if (symbol.GetMethod.DeclaredAccessibility == Accessibility.Public) getter = "get; "; } if (symbol.SetMethod != null) { if (symbol.SetMethod.DeclaredAccessibility == Accessibility.Protected) setter = "protected set; "; else if (symbol.SetMethod.DeclaredAccessibility == Accessibility.Public) setter = "set; "; } var body = $"{{ {getter}{setter}}}"; var type = symbol.OriginalDefinition.Type.ToMinimalString(); //if (prop.IsReadOnly) modifiers += "readonly "; if (symbol.IsIndexer) code.Append($"{modifiers}{type} this{symbol.GetIndexerParametersString()} {body}"); else code.Append($"{modifiers}{type} {symbol.Name} {body}"); return code.ToString(); } static string ToEventCode(this IEventSymbol symbol, string modifiers) { var code = new StringBuilder(150); if (symbol.ContainingType.IsInterface()) modifiers = ""; var type = symbol.OriginalDefinition.Type.ToMinimalString(); code.Append($"{modifiers}event {type} {symbol.Name};"); return code.ToString(); } static string ToFieldCode(this IFieldSymbol symbol, string modifiers) { var code = new StringBuilder(150); if (symbol.ContainingType.IsEnum()) { if (symbol.ConstantValue != null) code.Append($"{symbol.Name} = {symbol.ConstantValue},"); else code.Append($"{symbol.Name},"); } else { var type = symbol.OriginalDefinition.Type.ToMinimalString(); if (symbol.IsConst) modifiers += "const "; if (symbol.IsReadOnly) modifiers += "readonly "; var val = ""; if (symbol.ConstantValue != null) { val = symbol.ConstantValue.ToString(); var typeFullName = symbol.OriginalDefinition.Type.GetFullName(); if (typeFullName == "System.Char") val = $" = {symbol.ConstantValue.To<char>().ToLiteral()}"; else if (typeFullName == "System.String") val = $" = {val.ToLiteral()}"; else val = $" = {val}"; } code.Append($"{modifiers}{type} {symbol.Name}{val};"); } return code.ToString(); } static bool HiddenFromUser(this ISymbol symbol) { if (symbol is IMethodSymbol) { var method = symbol as IMethodSymbol; if (method.ContainingType.IsEnum()) //Enum constructor is hidden from user return true; if (method.MethodKind == MethodKind.PropertyGet || method.MethodKind == MethodKind.PropertySet || method.MethodKind == MethodKind.EventAdd || method.MethodKind == MethodKind.EventRemove) return true; //getters, setters and so on are hidden from user if (method.IsConstructor()) { if (!method.Parameters.Any() && method.ContainingType.Constructors.Length == 1 && method.DeclaredAccessibility == Accessibility.Public) return true; //hide default constructors if it is the only public constructor } } return false; } static string ToMethodCode(this IMethodSymbol symbol, string modifiers) { var code = new StringBuilder(150); if (symbol.ContainingType.IsInterface()) modifiers = ""; string returnTypeAndName; var returnType = symbol.OriginalDefinition.ReturnType.ToMinimalString(); if (symbol.IsConstructor()) returnTypeAndName = $"{symbol.ContainingType.Name}"; // Printer else if (symbol.IsDestructor()) returnTypeAndName = $"~{symbol.ContainingType.Name}"; // ~Printer else if (symbol.IsOperator()) returnTypeAndName = $"{returnType} {symbol.GetDisplayName()}"; // operator T? (T value); else if (symbol.IsConversion()) returnTypeAndName = $"{symbol.GetDisplayName()} {returnType}"; // implicit operator DBBool(bool x) else returnTypeAndName = $"{returnType} {symbol.Name}"; //int GetIndex code.Append($"{modifiers.Trim()} ") // public static .Append(returnTypeAndName) // int GetIndex .Append(symbol.TypeParameters.ToDeclarationString()) // <T, T2> .Append(symbol.GetParametersString()) //(int position, int value) .Append(symbol.TypeParameters.GetConstrains(singleLine: true)) // where T: class .Append(";"); return code.ToString(); } public static string ToReflectedCode(this ISymbol symbol, bool includeDoc = true, bool usePartials = false) { var code = new StringBuilder(150); Action<string, int> cosdeAddComment = (text, indent) => { if (text.HasAny()) code.AppendLine(text.IndentLinesBy(indent, "// ")); }; if (includeDoc) { var doc = symbol.GetDocumentationComment(); cosdeAddComment(doc, 0); } if (symbol.DeclaredAccessibility != Accessibility.Public && symbol.DeclaredAccessibility != Accessibility.Protected) return null; string modifiers = $"{symbol.DeclaredAccessibility} ".ToLower(); if (symbol.IsOverride) modifiers += "override "; if (symbol.IsStatic) modifiers += "static "; if (symbol.IsAbstract && !(symbol as INamedTypeSymbol).IsInterface()) modifiers += "abstract "; if (symbol.IsVirtual) modifiers += "virtual "; switch (symbol.Kind) { case SymbolKind.Property: { var prop = (IPropertySymbol)symbol; code.Append(prop.ToPropertyCode(modifiers)); break; } case SymbolKind.Field: { var field = (IFieldSymbol)symbol; code.Append(field.ToFieldCode(modifiers)); break; } case SymbolKind.Event: { var @event = (IEventSymbol)symbol; code.Append(@event.ToEventCode(modifiers)); break; } case SymbolKind.Method: { if (symbol.HiddenFromUser()) return null; var method = (symbol as IMethodSymbol); code.Append(method.ToMethodCode(modifiers)); break; } case SymbolKind.NamedType: { var type = (INamedTypeSymbol)symbol; code.Append(type.ToTypeCode(modifiers, usePartials)); break; } } if (code.Length == 0) code.AppendLine($"{symbol.ToDisplayKind()}: {symbol.ToDisplayString()};"); return code.ToString(); } public static string ToTooltip(this ISymbol symbol, bool showOverloadInfo = false) { string symbolDoc = ""; switch (symbol.Kind) { case SymbolKind.Property: { var member = (IPropertySymbol)symbol; var type = member.Type.ToMinimalString(); var name = $"{member.ContainingType.ToMinimalString()}.{member.Name}"; string body = "{ }"; if (member.GetMethod == null) body = "{ set; }"; else if (member.SetMethod == null) body = "{ get; }"; else body = "{ get; set; }"; symbolDoc = $"Property: {type} {name} {body}"; break; } case SymbolKind.Field: { var member = (IFieldSymbol)symbol; var type = member.Type.ToMinimalString(); var name = $"{member.ContainingType.ToMinimalString()}.{member.Name}"; symbolDoc = $"Field: {type} {name}"; break; } case SymbolKind.Event: { var member = (IEventSymbol)symbol; var type = member.Type.ToMinimalString(); var name = $"{member.ContainingType.ToMinimalString()}.{member.Name}"; symbolDoc = $"Event: {type} {name}"; break; } case SymbolKind.Method: { var method = (symbol as IMethodSymbol); var returnType = method.ReturnType.ToMinimalString(); var name = $"{method.ReceiverType.ToMinimalString()}.{method.Name}"; if (method.TypeArguments.HasAny()) { string prms = string.Join(", ", method.TypeArguments.Select(p => p.ToMinimalString()).ToArray()); name = $"{name}<{prms}>"; } var args = "()"; if (method.Parameters.HasAny()) { string prms = string.Join(", ", method.Parameters.Select(p => p.Type.ToMinimalString() + " " + p.Name).ToArray()); args = $"({prms})"; } var kind = "Method"; if (method.IsConstructor()) { kind = "Constructor"; name = name.Replace("..ctor", ""); symbolDoc = $"{kind}: {name}{args}"; } else { if (method.IsExtensionMethod) kind += " (extension)"; symbolDoc = $"{kind}: {returnType} {name}{args}"; } int overloads = symbol.ContainingType.GetMembers(method.Name).OfType<IMethodSymbol>().Count() - 1; if (overloads > 0 && showOverloadInfo) symbolDoc += $" (+ {overloads} overloads)"; break; } case SymbolKind.ArrayType: case SymbolKind.Local: case SymbolKind.NamedType: case SymbolKind.Parameter: break; default: break; } if (!symbolDoc.HasText()) symbolDoc = $"{symbol.ToDisplayKind()}: {symbol.ToDisplayString()}"; var xmlDoc = symbol.GetDocumentationCommentXml(); if (xmlDoc.HasText()) symbolDoc += "\r\n" + xmlDoc.XmlToPlainText(); return symbolDoc; } public static string ToSignatureInfo(this ISymbol symbol) { string symbolDoc = ""; switch (symbol.Kind) { case SymbolKind.Method: { var method = (symbol as IMethodSymbol); var returnType = method.ReturnType.ToMinimalString(); var name = $"{method.ReceiverType.ToMinimalString()}.{method.Name}"; if (method.TypeArguments.HasAny()) { string prms = string.Join(", ", method.TypeArguments.Select(p => p.ToMinimalString()).ToArray()); name = $"{name}<{prms}>"; } var args = "()"; if (method.Parameters.HasAny()) { string prms = string.Join(", ", method.Parameters.Select(p => p.Type.ToMinimalString() + " " + p.Name).ToArray()); args = $"({prms})"; } if (method.IsConstructor()) symbolDoc = $"label:{name}{args}"; else symbolDoc = $"label:{returnType} {name}{args}"; break; } default: break; } // Console.WriteLine( symbolDoc += "\r\n" + symbol.GetDocumentationCommentXml() .XmlToPlainText(isReflectionDocument: false, ignoreExceptionsInfo: true, vsCodeEncoding: true); return symbolDoc; } public static ICompletionData ToCompletionData(this ISymbol symbol) { if (symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Method) { // Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEMethodSymbol is internal so we cannot explore it var invokeParams = new List<string>(); string invokeReturn = null; try { if (symbol.Kind == SymbolKind.Method && symbol is IMethodSymbol) { var method = (IMethodSymbol)symbol; foreach (var item in method.Parameters) { invokeParams.Add(item.Type.ToDecoratedName() + " " + item.Name); } invokeReturn = method.ReturnType.ToDecoratedName(); } else if (symbol.Kind == SymbolKind.Event && symbol is IEventSymbol) { var method = symbol.To<IEventSymbol>() .Type.To<INamedTypeSymbol>() .DelegateInvokeMethod.To<IMethodSymbol>(); foreach (var item in method.Parameters) { invokeParams.Add(item.Type.ToDecoratedName() + " " + item.Name); } invokeReturn = method.ReturnType.ToDecoratedName(); } } catch { } return new EntityCompletionData { DisplayText = symbol.Name, CompletionText = symbol.Name, CompletionType = symbol.Kind.ToCompletionType(), RawData = symbol, InvokeParameters = invokeParams, InvokeParametersSet = true, InvokeReturn = invokeReturn }; } else { return new CompletionData { DisplayText = symbol.Name, CompletionText = symbol.Name, CompletionType = symbol.Kind.ToCompletionType(), RawData = symbol }; } } } public static class CompletionStringExtensions { public static bool CanComplete(this string completion, string partial) { return completion.StartsWith(partial) || completion.IsSubsequenceMatch(partial); } public static bool IsCamelCaseMatch(this string completion, string partialWord) { return new string(completion.Where(c => char.IsLetter(c) && char.IsUpper(c)).ToArray()).StartsWith(partialWord, StringComparison.OrdinalIgnoreCase); } public static bool IsSubsequenceMatch(this string completion, string partial) { if (!partial.HasText()) return true; if (char.ToUpperInvariant(completion[0]) != char.ToUpperInvariant(partial[0])) return false; else return string.Compare(new string(completion.ToUpper().Intersect(partial.ToUpper()).ToArray()), partial, StringComparison.OrdinalIgnoreCase) == 0; } } /// <summary> /// Ironically Roslyn does not support parsing primitives. /// Thus need to use this very simplistic parser. /// In the future will need to be extended with dynamic /// type detection: /// 0x2340 - int /// 0x23402345 - long /// </summary> internal static class Primitives { // does not do the length of digits sequence checking public static bool HasFloatSuffix(this string text) => text.EndsWith("f", StringComparison.OrdinalIgnoreCase); public static bool HasDoubleSuffix(this string text) => text.EndsWith("d", StringComparison.OrdinalIgnoreCase); public static bool HasDecimalSuffix(this string text) => text.EndsWith("m", StringComparison.OrdinalIgnoreCase); public static string DeflateNumber(this string text) => text.Replace("_", "").Replace("+", "").Replace("-", ""); public static bool EndsWithDigit(this string text) => char.IsDigit(text.Last()); public static bool IsNumeric(this string text) => text.Length > 0 && !text.StartsWith("'") && !text.StartsWith("\"") && !text.StartsWith("@\"") && !text.StartsWith("$\"") && !text.StartsWith("$@\"") && ((text.StartsWith("0x") || text.StartsWith("0b")) || (text.Where(x => x != '_' && x != '+' && x != '-').All(char.IsDigit))); public static bool IsFloat(this string text) => text.Length > 0 && (text.StartsWith("(float)") || text.Substring(0, text.Length - 1).Replace(".", "").IsNumeric() && text.HasFloatSuffix()); public static bool IsDecimal(this string text) => text.Length > 0 && (text.StartsWith("(decimal)") || text.Substring(0, text.Length - 1).Replace(".", "").IsNumeric() && text.HasDecimalSuffix()); public static bool IsDouble(this string text) => text.Length > 0 && (text.StartsWith("(double)") || text.Substring(0, text.Length - 1).Replace(".", "").IsNumeric() && ((text.Contains(".") && text.EndsWithDigit()) || text.HasDoubleSuffix())); public static bool IsByte(this string text) => text.Length > 0 && (text.IsNumeric() && text.StartsWith("(byte)")); public static bool IsChar(this string text) => text.Length > 0 && (text.StartsWith("'") || text.StartsWith("(char)")); // may be incomplete //((text.StartsWith("'") && text.EndsWith("'")) || text.StartsWith("(char)")); public static bool IsLong(this string text) => text.Length > 0 && text.IsNumeric() && (text.StartsWith("(long)") || text.EndsWith("l", StringComparison.OrdinalIgnoreCase)); public static bool IsSbyte(this string text) => text.Length > 0 && text.IsNumeric() && text.StartsWith("(sbyte)"); public static bool IsShort(this string text) => text.Length > 0 && text.IsNumeric() && text.StartsWith("(short)"); public static bool IsUlong(this string text) => text.Length > 0 && text.IsNumeric() && text.StartsWith("(ulong)"); public static bool IsInt(this string text) => text.Length > 0 && (text.IsNumeric() || text.StartsWith("(int)")); public static bool IsBool(this string text) => (text == "true" || text == "false" || text.StartsWith("(bool)")); public static bool IsString(this string text) => text.Length > 0 && (text.StartsWith("\"") || text.StartsWith("@\"") || text.StartsWith("$\"") || text.StartsWith("$@\"")); // the string may not be completed } }
// Copyright (C) 2009-2017 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Reflection; namespace OpenGL.Objects { public partial class ShaderProgram { #region Set/Get Variant Uniforms /// <summary> /// Set uniform state variable (any known object type). /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="value"> /// A <see cref="Object"/> holding the uniform variabile data. /// </param> /// <remarks> /// </remarks> /// <exception cref="ArgumentNullException"> /// This exception is thrown if the parameter <paramref name="ctx"/> is null. /// </exception> /// <exception cref="ArgumentNullException"> /// This exception is thrown if the parameter <paramref name="uniformName"/> is null. /// </exception> public void SetVariantUniform(GraphicsContext ctx, string uniformName, object value) { if (ctx == null) throw new ArgumentNullException("ctx"); if (value == null) throw new ArgumentNullException("value"); MethodInfo setUniformMethod; if (_SetVariantUniformMethods.TryGetValue(value.GetType(), out setUniformMethod) == false) { setUniformMethod = typeof(ShaderProgram).GetMethod("SetVariantUniform", new Type[] { typeof(GraphicsContext), typeof(string), value.GetType() }); _SetVariantUniformMethods[value.GetType()] = setUniformMethod; } if (setUniformMethod != null) { try { setUniformMethod.Invoke(this, new object[] { ctx, uniformName, value }); } catch (TargetInvocationException targetInvocationException) { throw targetInvocationException.InnerException; } } else throw new NotSupportedException(value.GetType() + " is not supported"); } /// <summary> /// Methods used for setting uniform values. /// </summary> private static readonly Dictionary<Type, MethodInfo> _SetVariantUniformMethods = new Dictionary<Type, MethodInfo>(); #endregion #region Set/Get Variant Uniform (single-precision floating-point vector data) /// <summary> /// Set uniform variable from single-precision floating-point data. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="x"> /// A <see cref="Single"/> holding the uniform variabile data (first component). /// </param> /// <remarks> /// <para> /// The uniform variable type could be one of the following : /// - float, vec2, vec3, vec4 /// - double, dvec2, dvec3, dvec4 /// - int, ivec2, ivec3, ivec4 /// - uint, uvec2, uvec3, uvec4 /// </para> /// <para> /// Other components than the first one are reset to 0.0. The single-precision /// floating-point data is converted accordingly to the uniform variable type. /// </para> /// </remarks> public void SetVariantUniform(GraphicsContext ctx, string uniformName, float x) { SetUniform(ctx, uniformName, x, 0.0f, 0.0f, 0.0f); } /// <summary> /// Set uniform variable from single-precision floating-point data. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="x"> /// A <see cref="Single"/> holding the uniform variabile data (first component). /// </param> /// <param name="y"> /// A <see cref="Single"/> holding the uniform variabile data (second component). /// </param> /// <remarks> /// <para> /// The uniform variable type could be one of the following : /// - float, vec2, vec3, vec4 /// - double, dvec2, dvec3, dvec4 /// - int, ivec2, ivec3, ivec4 /// - uint, uvec2, uvec3, uvec4 /// </para> /// <para> /// In the case the uniform variable length is less than 2, the higher components specified as /// arguments are ignored; otherwise, other components are reset to 0.0. The single-precision /// floating-point data is converted accordingly to the uniform variable type. /// </para> /// </remarks> public void SetVariantUniform(GraphicsContext ctx, string uniformName, float x, float y) { SetUniform(ctx, uniformName, x, y, 0.0f, 0.0f); } /// <summary> /// Set uniform variable from single-precision floating-point data. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="x"> /// A <see cref="Single"/> holding the uniform variabile data (first component). /// </param> /// <param name="y"> /// A <see cref="Single"/> holding the uniform variabile data (second component). /// </param> /// <param name="z"> /// A <see cref="Single"/> holding the uniform variabile data (third component). /// </param> /// <remarks> /// <para> /// The uniform variable type could be one of the following : /// - float, vec2, vec3, vec4 /// - double, dvec2, dvec3, dvec4 /// - int, ivec2, ivec3, ivec4 /// - uint, uvec2, uvec3, uvec4 /// </para> /// <para> /// In the case the uniform variable length is less than 3, the higher components specified as /// arguments are ignored; otherwise, other components are reset to 0.0. The single-precision /// floating-point data is converted accordingly to the uniform variable type. /// </para> /// </remarks> public void SetVariantUniform(GraphicsContext ctx, string uniformName, float x, float y, float z) { SetUniform(ctx, uniformName, x, y, z, 0.0f); } /// <summary> /// Set uniform variable from single-precision floating-point data (variant type). /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="x"> /// A <see cref="Single"/> holding the uniform variabile data (first component). /// </param> /// <param name="y"> /// A <see cref="Single"/> holding the uniform variabile data (second component). /// </param> /// <param name="z"> /// A <see cref="Single"/> holding the uniform variabile data (third component). /// </param> /// <param name="w"> /// A <see cref="Single"/> holding the uniform variabile data (fourth component). /// </param> /// <remarks> /// <para> /// The uniform variable type could be one of the following : /// - float, vec2, vec3, vec4 /// - double, dvec2, dvec3, dvec4 /// - int, ivec2, ivec3, ivec4 /// - uint, uvec2, uvec3, uvec4 /// </para> /// <para> /// In the case the uniofmr variable length is less than 4, the higher components specified as /// arguments are ignored. The single-precision floating-point data is converted accordingly /// to the uniform variable type. /// </para> /// </remarks> public void SetVariantUniform(GraphicsContext ctx, string uniformName, float x, float y, float z, float w) { if (ctx == null) throw new ArgumentNullException("ctx"); UniformBinding uniform = GetUniform(ctx, uniformName); switch (uniform.UniformType) { case ShaderUniformType.Float: SetUniform(ctx, uniformName, x); break; case ShaderUniformType.Vec2: SetUniform(ctx, uniformName, x, y); break; case ShaderUniformType.Vec3: SetUniform(ctx, uniformName, x, y, z); break; case ShaderUniformType.Vec4: SetUniform(ctx, uniformName, x, y, z, w); break; #if !MONODROID case ShaderUniformType.Double: SetUniform(ctx, uniformName, (double)x); break; case ShaderUniformType.DoubleVec2: SetUniform(ctx, uniformName, (double)x, (double)y); break; case ShaderUniformType.DoubleVec3: SetUniform(ctx, uniformName, (double)x, (double)y, (double)z); break; case ShaderUniformType.DoubleVec4: SetUniform(ctx, uniformName, (double)x, (double)y, (double)z, (double)w); break; #endif case ShaderUniformType.Int: SetUniform(ctx, uniformName, (int)x); break; case ShaderUniformType.IntVec2: SetUniform(ctx, uniformName, (int)x, (int)y); break; case ShaderUniformType.IntVec3: SetUniform(ctx, uniformName, (int)x, (int)y, (int)z); break; case ShaderUniformType.IntVec4: SetUniform(ctx, uniformName, (int)x, (int)y, (int)z); break; case ShaderUniformType.UInt: SetUniform(ctx, uniformName, (uint)x); break; case ShaderUniformType.UIntVec2: SetUniform(ctx, uniformName, (uint)x, (uint)y); break; case ShaderUniformType.UIntVec3: SetUniform(ctx, uniformName, (uint)x, (uint)y, (uint)z); break; case ShaderUniformType.UIntVec4: SetUniform(ctx, uniformName, (uint)x, (uint)y, (uint)z); break; default: throw new ShaderException("unable to set single-precision floating-point data to uniform of type {0}", uniform.UniformType); } } /// <summary> /// Set uniform state variable (variant type variable). /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="v"> /// A <see cref="Vertex2f"/> holding the uniform variabile data. /// </param> public void SetVariantUniform(GraphicsContext ctx, string uniformName, Vertex2f v) { SetVariantUniform(ctx, uniformName, v.x, v.y); } /// <summary> /// Set uniform state variable (variant type variable). /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="v"> /// A <see cref="Vertex3f"/> holding the uniform variabile data. /// </param> public void SetVariantUniform(GraphicsContext ctx, string uniformName, Vertex3f v) { SetVariantUniform(ctx, uniformName, v.x, v.y, v.z); } /// <summary> /// Set uniform state variable (variant type variable) /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="v"> /// A <see cref="Vertex3f"/> holding the uniform variabile data. /// </param> public void SetVariantUniform(GraphicsContext ctx, string uniformName, Vertex4f v) { SetVariantUniform(ctx, uniformName, v.x, v.y, v.z, v.w); } /// <summary> /// Set uniform state variable (variant type variable) /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="v"> /// A <see cref="ColorRGBAF"/> holding the uniform variabile data. /// </param> public void SetVariantUniform(GraphicsContext ctx, string uniformName, ColorRGBAF v) { SetVariantUniform(ctx, uniformName, v.r, v.g, v.b, v.a); } #endregion #region Set/Get Variant Uniform (double-precision floating-point vector data) /// <summary> /// Set uniform variable from double-precision floating-point data. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="x"> /// A <see cref="Double"/> holding the uniform variabile data (first component). /// </param> /// <remarks> /// <para> /// The uniform variable type could be one of the following : /// - float, vec2, vec3, vec4 /// - double, dvec2, dvec3, dvec4 /// - int, ivec2, ivec3, ivec4 /// - uint, uvec2, uvec3, uvec4 /// </para> /// <para> /// Other components than the first one are reset to 0.0. The single-precision /// floating-point data is converted accordingly to the uniform variable type. /// </para> /// </remarks> public void SetVariantUniform(GraphicsContext ctx, string uniformName, double x) { SetVariantUniform(ctx, uniformName, x, 0.0, 0.0, 0.0); } /// <summary> /// Set uniform variable from double-precision floating-point data. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="x"> /// A <see cref="Double"/> holding the uniform variabile data (first component). /// </param> /// <param name="y"> /// A <see cref="Double"/> holding the uniform variabile data (second component). /// </param> /// <remarks> /// <para> /// The uniform variable type could be one of the following : /// - float, vec2, vec3, vec4 /// - double, dvec2, dvec3, dvec4 /// - int, ivec2, ivec3, ivec4 /// - uint, uvec2, uvec3, uvec4 /// </para> /// <para> /// In the case the uniform variable length is less than 2, the higher components specified as /// arguments are ignored; otherwise, other components are reset to 0.0. The single-precision /// floating-point data is converted accordingly to the uniform variable type. /// </para> /// </remarks> public void SetVariantUniform(GraphicsContext ctx, string uniformName, double x, double y) { SetVariantUniform(ctx, uniformName, x, y, 0.0, 0.0); } /// <summary> /// Set uniform variable from double-precision floating-point data. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="x"> /// A <see cref="Double"/> holding the uniform variabile data (first component). /// </param> /// <param name="y"> /// A <see cref="Double"/> holding the uniform variabile data (second component). /// </param> /// <param name="z"> /// A <see cref="Double"/> holding the uniform variabile data (third component). /// </param> /// <remarks> /// <para> /// The uniform variable type could be one of the following : /// - float, vec2, vec3, vec4 /// - double, dvec2, dvec3, dvec4 /// - int, ivec2, ivec3, ivec4 /// - uint, uvec2, uvec3, uvec4 /// </para> /// <para> /// In the case the uniform variable length is less than 3, the higher components specified as /// arguments are ignored; otherwise, other components are reset to 0.0. The single-precision /// floating-point data is converted accordingly to the uniform variable type. /// </para> /// </remarks> public void SetVariantUniform(GraphicsContext ctx, string uniformName, double x, double y, double z) { SetVariantUniform(ctx, uniformName, x, y, z, 0.00); } /// <summary> /// Set uniform variable from double-precision floating-point data (variant type). /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="x"> /// A <see cref="Double"/> holding the uniform variabile data (first component). /// </param> /// <param name="y"> /// A <see cref="Double"/> holding the uniform variabile data (second component). /// </param> /// <param name="z"> /// A <see cref="Double"/> holding the uniform variabile data (third component). /// </param> /// <param name="w"> /// A <see cref="Double"/> holding the uniform variabile data (fourth component). /// </param> /// <remarks> /// <para> /// The uniform variable type could be one of the following : /// - float, vec2, vec3, vec4 /// - double, dvec2, dvec3, dvec4 /// - int, ivec2, ivec3, ivec4 /// - uint, uvec2, uvec3, uvec4 /// </para> /// <para> /// In the case the uniofmr variable length is less than 4, the higher components specified as /// arguments are ignored. The single-precision floating-point data is converted accordingly /// to the uniform variable type. /// </para> /// </remarks> public void SetVariantUniform(GraphicsContext ctx, string uniformName, double x, double y, double z, double w) { if (ctx == null) throw new ArgumentNullException("ctx"); UniformBinding uniform = GetUniform(ctx, uniformName); switch (uniform.UniformType) { case ShaderUniformType.Float: SetUniform(ctx, uniformName, (float)x); break; case ShaderUniformType.Vec2: SetUniform(ctx, uniformName, (float)x, (float)y); break; case ShaderUniformType.Vec3: SetUniform(ctx, uniformName, (float)x, (float)y, (float)z); break; case ShaderUniformType.Vec4: SetUniform(ctx, uniformName, (float)x, (float)y, (float)z, (float)w); break; #if !MONODROID case ShaderUniformType.Double: SetUniform(ctx, uniformName, x); break; case ShaderUniformType.DoubleVec2: SetUniform(ctx, uniformName, x, y); break; case ShaderUniformType.DoubleVec3: SetUniform(ctx, uniformName, x, y, z); break; case ShaderUniformType.DoubleVec4: SetUniform(ctx, uniformName, x, y, z, w); break; #endif case ShaderUniformType.Int: SetUniform(ctx, uniformName, (int)x); break; case ShaderUniformType.IntVec2: SetUniform(ctx, uniformName, (int)x, (int)y); break; case ShaderUniformType.IntVec3: SetUniform(ctx, uniformName, (int)x, (int)y, (int)z); break; case ShaderUniformType.IntVec4: SetUniform(ctx, uniformName, (int)x, (int)y, (int)z); break; case ShaderUniformType.UInt: SetUniform(ctx, uniformName, (uint)x); break; case ShaderUniformType.UIntVec2: SetUniform(ctx, uniformName, (uint)x, (uint)y); break; case ShaderUniformType.UIntVec3: SetUniform(ctx, uniformName, (uint)x, (uint)y, (uint)z); break; case ShaderUniformType.UIntVec4: SetUniform(ctx, uniformName, (uint)x, (uint)y, (uint)z); break; default: throw new ShaderException("unable to set double-precision floating-point data to uniform os type {0}", uniform.UniformType); } } /// <summary> /// Set uniform state variable (variant type variable). /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="v"> /// A <see cref="Vertex2d"/> holding the uniform variabile data. /// </param> public void SetVariantUniform(GraphicsContext ctx, string uniformName, Vertex2d v) { SetVariantUniform(ctx, uniformName, v.x, v.y); } /// <summary> /// Set uniform state variable (variant type variable). /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="v"> /// A <see cref="Vertex3d"/> holding the uniform variabile data. /// </param> public void SetVariantUniform(GraphicsContext ctx, string uniformName, Vertex3d v) { SetVariantUniform(ctx, uniformName, v.x, v.y, v.z); } /// <summary> /// Set uniform state variable (variant type variable) /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="v"> /// A <see cref="Vertex3f"/> holding the uniform variabile data. /// </param> public void SetVariantUniform(GraphicsContext ctx, string uniformName, Vertex4d v) { SetVariantUniform(ctx, uniformName, v.x, v.y, v.z, v.w); } #endregion #region Set/Get Variant Uniform (single-precision floating-point matrix data) /// <summary> /// Set uniform state variable (variant type). /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="m"> /// A <see cref="Matrix3x3f"/> holding the uniform variabile data. /// </param> public void SetVariantUniform(GraphicsContext ctx, string uniformName, Matrix3x3f m) { if (ctx == null) throw new ArgumentNullException("ctx"); UniformBinding uniform = GetUniform(ctx, uniformName); switch (uniform.UniformType) { case ShaderUniformType.Mat3x3: SetUniform(ctx, uniformName, m); break; #if !MONODROID case ShaderUniformType.DoubleMat3x3: SetUniform(ctx, uniformName, (Matrix3x3d)m); break; #endif default: throw new ShaderException("unable to set single-precision floating-point matrix 3x3 data to uniform of type {0}", uniform.UniformType); } } /// <summary> /// Set uniform state variable (variant type). /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="m"> /// A <see cref="Matrix4x4f"/> holding the uniform variabile data. /// </param> public void SetVariantUniform(GraphicsContext ctx, string uniformName, Matrix4x4f m) { if (ctx == null) throw new ArgumentNullException("ctx"); UniformBinding uniform = GetUniform(ctx, uniformName); switch (uniform.UniformType) { case ShaderUniformType.Mat4x4: SetUniform(ctx, uniformName, m); break; #if !MONODROID case ShaderUniformType.DoubleMat4x4: SetUniform(ctx, uniformName, (Matrix4x4d)m); break; #endif default: throw new ShaderException("unable to set single-precision floating-point matrix 4x4 data to uniform of type {0}", uniform.UniformType); } } #endregion #region Set/Get Variant Uniform (double-precision floating-point matrix data) /// <summary> /// Set uniform state variable (variant type). /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="m"> /// A <see cref="Matrix3x3"/> holding the uniform variabile data. /// </param> public void SetVariantUniform(GraphicsContext ctx, string uniformName, Matrix3x3d m) { if (ctx == null) throw new ArgumentNullException("ctx"); UniformBinding uniform = GetUniform(ctx, uniformName); switch (uniform.UniformType) { case ShaderUniformType.Mat3x3: SetUniform(ctx, uniformName, (Matrix3x3f)m); break; #if !MONODROID case ShaderUniformType.DoubleMat3x3: SetUniform(ctx, uniformName, m); break; #endif default: throw new ShaderException("unable to set double-precision floating-point matrix 3x3 data to uniform of type {0}", uniform.UniformType); } } /// <summary> /// Set uniform state variable (variant type). /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for operations. /// </param> /// <param name="uniformName"> /// A <see cref="String"/> that specify the variable name in the shader source. /// </param> /// <param name="m"> /// A <see cref="Matrix4x4d"/> holding the uniform variabile data. /// </param> public void SetVariantUniform(GraphicsContext ctx, string uniformName, Matrix4x4d m) { if (ctx == null) throw new ArgumentNullException("ctx"); UniformBinding uniform = GetUniform(ctx, uniformName); switch (uniform.UniformType) { case ShaderUniformType.Mat4x4: SetUniform(ctx, uniformName, (Matrix4x4f)m); break; #if !MONODROID case ShaderUniformType.DoubleMat4x4: SetUniform(ctx, uniformName, m); break; #endif default: throw new ShaderException("unable to set double-precision floating-point matrix 4x4 data to uniform of type {0}", uniform.UniformType); } } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using Microsoft.WindowsAzure.Management.Sql; namespace Microsoft.WindowsAzure.Management.Sql.Models { /// <summary> /// Response containing the database operation for a given operation Guid. /// </summary> public partial class DatabaseOperationGetResponse : OperationResponse { private string _databaseName; /// <summary> /// Gets or sets the name of the SQL Database on which the operation is /// performed. /// </summary> public string DatabaseName { get { return this._databaseName; } set { this._databaseName = value; } } private string _error; /// <summary> /// Gets or sets the description of the error that occurred during a /// failed operation. /// </summary> public string Error { get { return this._error; } set { this._error = value; } } private int _errorCode; /// <summary> /// Gets or sets the code indicating the error that occurred during a /// failed operation. /// </summary> public int ErrorCode { get { return this._errorCode; } set { this._errorCode = value; } } private int _errorSeverity; /// <summary> /// Gets or sets the severity level of the error that occurred during a /// failed operation. /// </summary> public int ErrorSeverity { get { return this._errorSeverity; } set { this._errorSeverity = value; } } private int _errorState; /// <summary> /// Gets or sets the error state. /// </summary> public int ErrorState { get { return this._errorState; } set { this._errorState = value; } } private string _id; /// <summary> /// Gets or sets unique identifier of the operation. /// </summary> public string Id { get { return this._id; } set { this._id = value; } } private DateTime _lastModifyTime; /// <summary> /// Gets or sets the timestamp when the record was last modified for a /// long running operation. /// </summary> public DateTime LastModifyTime { get { return this._lastModifyTime; } set { this._lastModifyTime = value; } } private string _name; /// <summary> /// Gets or sets the name of the operation. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _parentLink; /// <summary> /// Gets or sets the ParentLink of the operation. /// </summary> public string ParentLink { get { return this._parentLink; } set { this._parentLink = value; } } private int _percentComplete; /// <summary> /// Gets or sets the percentage of operation that has completed. /// </summary> public int PercentComplete { get { return this._percentComplete; } set { this._percentComplete = value; } } private string _selfLink; /// <summary> /// Gets or sets the SelfLink of the operation. /// </summary> public string SelfLink { get { return this._selfLink; } set { this._selfLink = value; } } private string _sessionActivityId; /// <summary> /// Gets or sets session scoped ID of the operation. /// </summary> public string SessionActivityId { get { return this._sessionActivityId; } set { this._sessionActivityId = value; } } private DateTime _startTime; /// <summary> /// Gets or sets the timestamp when the operation started. /// </summary> public DateTime StartTime { get { return this._startTime; } set { this._startTime = value; } } private string _state; /// <summary> /// Gets or sets the state of the operation. /// </summary> public string State { get { return this._state; } set { this._state = value; } } private int _stateId; /// <summary> /// Gets or sets the current state of the long running operation in /// numeric format. /// </summary> public int StateId { get { return this._stateId; } set { this._stateId = value; } } private string _type; /// <summary> /// Gets or sets the type of resource. /// </summary> public string Type { get { return this._type; } set { this._type = value; } } /// <summary> /// Initializes a new instance of the DatabaseOperationGetResponse /// class. /// </summary> public DatabaseOperationGetResponse() { } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using log4net; using NetGore; using NetGore.Features.Shops; using NetGore.IO; using NetGore.Stats; using NetGore.World; using SFML.Graphics; namespace DemoGame { /// <summary> /// Extensions for handling I/O of specialized types in the <see cref="BitStream"/>. /// </summary> public static class BitStreamExtensions { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static readonly int _clientPacketIDBits; static readonly int _gameMessageIDBits; static readonly int _serverPacketIDBits; /// <summary> /// Initializes the <see cref="BitStreamExtensions"/> class. /// </summary> /// <exception cref="TypeLoadException">Invalid required bit amount on <see cref="_clientPacketIDBits"/>.</exception> /// <exception cref="TypeLoadException">Invalid required bit amount on <see cref="_serverPacketIDBits"/>.</exception> static BitStreamExtensions() { _clientPacketIDBits = EnumHelper<ClientPacketID>.BitsRequired; _serverPacketIDBits = EnumHelper<ServerPacketID>.BitsRequired; _gameMessageIDBits = EnumHelper<GameMessage>.BitsRequired; if (_clientPacketIDBits <= 0) throw new TypeLoadException("Invalid required bit amount on _clientPacketIDBits: " + _clientPacketIDBits); if (_serverPacketIDBits <= 0) throw new TypeLoadException("Invalid required bit amount on _serverPacketIDBits: " + _serverPacketIDBits); } /// <summary> /// Reads a GameMessage from the BitStream. /// </summary> /// <param name="bitStream">BitStream to read from.</param> /// <param name="gameMessages">Collection of GameMessages to use to grab the message.</param> /// <returns>String of the parsed GameMessage read from the BitStream.</returns> /// <exception cref="ArgumentNullException"><paramref name="gameMessages" /> is <c>null</c>.</exception> public static string ReadGameMessage(this BitStream bitStream, GameMessageCollection gameMessages) { if (gameMessages == null) throw new ArgumentNullException("gameMessages"); var messageID = bitStream.ReadUInt(_gameMessageIDBits); var paramCount = bitStream.ReadByte(); // Parse the parameters string[] parameters = null; if (paramCount > 0) { parameters = new string[paramCount]; for (var i = 0; i < paramCount; i++) { parameters[i] = bitStream.ReadString(GameData.MaxServerMessageParameterLength); } } // Parse the message and return it var gameMessage = (GameMessage)messageID; var message = gameMessages.GetMessage(gameMessage, parameters); return message; } /// <summary> /// Reads a MapEntityIndex from the BitStream. /// </summary> /// <param name="bitStream">BitStream to read from.</param> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static MapEntityIndex ReadMapEntityIndex(this BitStream bitStream) { return bitStream.ReadMapEntityIndex(null); } /// <summary> /// Reads a <see cref="MapID"/> from the BitStream. /// </summary> /// <param name="bitStream">BitStream to read from.</param> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static MapID ReadMapID(this BitStream bitStream) { return bitStream.ReadMapID(null); } /// <summary> /// Reads a ShopItemIndex from the BitStream. /// </summary> /// <param name="bitStream">BitStream to read from.</param> public static ShopItemIndex ReadShopItemIndex(this BitStream bitStream) { return new ShopItemIndex(bitStream.ReadByte()); } /// <summary> /// Reads a Vector2 from the BitStream. /// </summary> /// <param name="bitStream">BitStream to read from.</param> /// <returns>Vector2 read from the BitStream.</returns> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static Vector2 ReadVector2(this BitStream bitStream) { return bitStream.ReadVector2(null); } /// <summary> /// Writes a Vector2 to the BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="vector2">Vector2 to write.</param> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static void Write(this BitStream bitStream, Vector2 vector2) { bitStream.Write(null, vector2); } /// <summary> /// Writes a GameMessage to the BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="gameMessage">GameMessage to write.</param> public static void Write(this BitStream bitStream, GameMessage gameMessage) { bitStream.Write((uint)gameMessage, _gameMessageIDBits); bitStream.Write((byte)0); } /// <summary> /// Writes a GameMessage to the BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="gameMessage">GameMessage to write.</param> /// <param name="args">Arguments for the message.</param> public static void Write(this BitStream bitStream, GameMessage gameMessage, params object[] args) { // Write the message ID bitStream.Write((uint)gameMessage, _gameMessageIDBits); // Write the parameter count and all of the parameters if (args == null || args.Length < 1) { // No parameters makes our life easy bitStream.Write((byte)0); } else { // One or more parameters are present, so start by writing the count bitStream.Write((byte)args.Length); // Write each parameter for (var i = 0; i < args.Length; i++) { // Make sure the object isn't null var obj = args[i]; if (obj == null) { const string errmsg = "Null object argument found when writing GameMessage."; Debug.Fail(errmsg); if (log.IsErrorEnabled) log.Error(errmsg); // Write out an error string instead for the parameter bitStream.Write("NULL_PARAMETER_ERROR", GameData.MaxServerMessageParameterLength); continue; } // Convert to a string, and ensure the string is short enough (trimming if it is too long) var str = obj.ToString(); if (str.Length > GameData.MaxServerMessageParameterLength) str = str.Substring(0, GameData.MaxServerMessageParameterLength); // Write the string bitStream.Write(str, GameData.MaxServerMessageParameterLength); } } } /// <summary> /// Writes a ShopItemIndex to the BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="shopItemIndex">ShopItemIndex to write.</param> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static void Write(this BitStream bitStream, ShopItemIndex shopItemIndex) { ((IValueWriter)bitStream).Write(null, shopItemIndex); } /// <summary> /// Writes a MapEntityIndex to the BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="mapEntityIndex">MapEntityIndex to write.</param> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static void Write(this BitStream bitStream, MapEntityIndex mapEntityIndex) { bitStream.Write(null, mapEntityIndex); } /// <summary> /// Writes a <see cref="ServerPacketID"/> to the BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="serverPacketID">ServerPacketID to write.</param> public static void Write(this BitStream bitStream, ServerPacketID serverPacketID) { bitStream.Write((uint)serverPacketID, _serverPacketIDBits); } /// <summary> /// Writes a <see cref="ClientPacketID"/> to the BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="clientPacketID">ClientPacketID to write.</param> public static void Write(this BitStream bitStream, ClientPacketID clientPacketID) { bitStream.Write((uint)clientPacketID, _clientPacketIDBits); } /// <summary> /// Writes a <see cref="MapID"/> to the BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="mapID">MapID to write.</param> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static void Write(this BitStream bitStream, MapID mapID) { bitStream.Write(null, mapID); } /// <summary> /// Writes a collection of stats to the BitStream. Only non-zero value stats are written since since the reader /// will zero all stat values first. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="statCollection">IStatCollection containing the stat values to write.</param> public static void Write(this BitStream bitStream, IEnumerable<Stat<StatType>> statCollection) { // Get the IEnumerable of all the non-zero stats var nonZeroStats = statCollection.Where(stat => stat.Value != 0); // Get the number of stats var numStats = (byte)nonZeroStats.Count(); Debug.Assert(numStats == nonZeroStats.Count(), "Too many stats in the collection - byte overflow! numStats may need to be raised to a ushort."); // Write the number of stats so the reader knows how many stats to read bitStream.Write(numStats); // Write each individual non-zero stat foreach (var stat in nonZeroStats) { bitStream.Write(stat); } } } }
//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. <[email protected]> // // // // 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. // // // //////////////////////////////////////////////////////////////////////////////// namespace Diva.Widgets { using System; using Gtk; public abstract class Task { // Events ///////////////////////////////////////////////////// public event EventHandler Started; public event EventHandler Running; public event EventHandler Finished; public event EventHandler Exception; public event EventHandler CustomFinish; // Fields ///////////////////////////////////////////////////// protected int step = 0; protected TaskStatus status = TaskStatus.Zero; protected Exception exception = null; object customData = null; // Properties ///////////////////////////////////////////////// public Exception CatchedException { get { return exception; } } public TaskStatus Status { get { return status; } } public object CustomData { get { return customData; } set { customData = value; } } public virtual bool SuggestCursor { get { return false; } } public virtual bool SuggestProgressBar { get { return false; } } // Public methods ///////////////////////////////////////////// public Task () { Reset (); } public void Start () { GLib.Idle.Add (RunIdle); } public virtual void Reset () { step = 0; status = TaskStatus.Zero; } public void Abort () { if (status == TaskStatus.Running) status = TaskStatus.Aborted; else { // We "wake" the task for a second status = TaskStatus.Aborted; GLib.Idle.Add (RunIdle); } } public void Exceptionize () { if (exception != null) throw exception; } public void ScheduleCustomFinish () { if (CustomFinish != null) GLib.Idle.Add (CustomFinishIdle); } // Private methods //////////////////////////////////////////// protected void Ressurect () { // FIXME: Not sure if this is correct if (status != TaskStatus.Aborted) status = TaskStatus.Running; step++; GLib.Idle.Add (RunIdle); } bool RunIdle () { bool retval = true; // Main body try { Gdk.Threads.Enter (); switch (status) { case TaskStatus.Zero: if (Started != null) Started (this, EventArgs.Empty); status = TaskStatus.Running; break; case TaskStatus.Blocked: retval = false; break; case TaskStatus.Running: status = ExecuteStep (step); if (status == TaskStatus.Running) step++; else retval = false; break; default: retval = false; break; } } catch (Exception excp) { exception = excp; retval = false; status = TaskStatus.Exception; if (Exception != null) Exception (this, EventArgs.Empty); } finally { if (! retval && Finished != null && status != TaskStatus.Blocked) Finished (this, EventArgs.Empty); else if (Running != null) Running (this, EventArgs.Empty); Gdk.Threads.Leave (); } return retval; } bool CustomFinishIdle () { try { Gdk.Threads.Enter (); if (CustomFinish != null) CustomFinish (this, EventArgs.Empty); } catch (Exception excp) { exception = excp; status = TaskStatus.Exception; if (Exception != null) Exception (this, EventArgs.Empty); } finally { Gdk.Threads.Leave (); } return false; } protected abstract TaskStatus ExecuteStep (int step); } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Presentation.Debug { using System; using System.Activities; using System.Activities.Debugger; using System.Activities.Presentation; using System.Activities.Presentation.Hosting; using System.Activities.Presentation.Model; using System.Activities.Presentation.Services; using System.Activities.Presentation.Validation; using System.Activities.Presentation.View; using System.Activities.Presentation.Xaml; using System.Activities.XamlIntegration; using System.Collections.Generic; using System.Linq; using System.Runtime; using System.Windows.Documents; using System.Windows.Threading; [Fx.Tag.XamlVisible(false)] public class DebuggerService : IDesignerDebugView { EditingContext context; ModelItem selectedModelItem; SourceLocation currentLocation; SourceLocation currentContext; ModelItem currentModelItem; ModelItem currentModelItemContext; WorkflowViewService viewService; ModelSearchServiceImpl modelSearchService; ModelTreeManager modelTreeManager; const string unresolvedPrefix = "unresolved:"; AttachedProperty<bool> isBreakpointEnabledProperty; AttachedProperty<bool> isBreakpointBoundedProperty; AttachedProperty<bool> isBreakpointConditionalProperty; AttachedProperty<bool> isCurrentLocationProperty; AttachedProperty<bool> isCurrentContextProperty; Dictionary<object, SourceLocation> instanceToSourceLocationMapping; Dictionary<ModelItem, SourceLocation> modelItemToSourceLocation; Dictionary<SourceLocation, ModelItem> sourceLocationToModelItem; Dictionary<ModelItem, BreakpointTypes> breakpoints; // The map contains breakpoint that has its ModelItem on the modelTree. Dictionary<ModelItem, BreakpointTypes> transientBreakpoints; // The map contains breakpoint that has its ModelItem not on the modelTree. Dictionary<SourceLocation, BreakpointTypes> unmappedBreakpoints; // The map contains breakpoint that has no ModelItem // This is used to generate unique source line no when the view element does not have a source location int lastSourceLineNo = 1; bool isReadOnly = false; bool isDebugging = false; private string fileName; private bool requiresUpdateSourceLocation; // Storing background BringToViewCurrentLocation operation. DispatcherOperation bringToViewCurrentLocationOperation = null; public DebuggerService(EditingContext context) { if (context == null) { throw FxTrace.Exception.ArgumentNull("context"); } this.context = context; this.modelItemToSourceLocation = new Dictionary<ModelItem, SourceLocation>(); this.sourceLocationToModelItem = new Dictionary<SourceLocation, ModelItem>(); this.breakpoints = new Dictionary<ModelItem, BreakpointTypes>(); // Breakpoints transiently removed from the document (copy/paste/undo/redo). this.transientBreakpoints = new Dictionary<ModelItem, BreakpointTypes>(); this.unmappedBreakpoints = new Dictionary<SourceLocation, BreakpointTypes>(4); this.instanceToSourceLocationMapping = new Dictionary<object, SourceLocation>(); this.context.Items.Subscribe<Selection>(new SubscribeContextCallback<Selection>(this.SelectionChanged)); this.context.Services.Subscribe<ViewService>(new SubscribeServiceCallback<ViewService>(this.OnViewServiceAvailable)); this.context.Services.Subscribe<ModelSearchService>(new SubscribeServiceCallback<ModelSearchService>(this.OnModelSearchServiceAvailable)); this.context.Services.Subscribe<AttachedPropertiesService>(new SubscribeServiceCallback<AttachedPropertiesService>(this.OnAttachedPropertiesServiceAvailable)); this.context.Services.Subscribe<ModelTreeManager>(new SubscribeServiceCallback<ModelTreeManager>(this.OnModelTreeManagerServiceAvailable)); this.requiresUpdateSourceLocation = true; } // IDesignerDebugView // Get the currently selected location from the designer // generally this is the location of the object currently selected by the user public SourceLocation SelectedLocation { get { return (this.selectedModelItem != null && AllowBreakpointAttribute.IsBreakpointAllowed(this.selectedModelItem.ItemType)) ? this.GetSourceLocationFromModelItem(this.selectedModelItem) : null; } } // Set current location of execution. // The location to shown the "yellow" arrow. public SourceLocation CurrentLocation { get { return this.currentLocation; } set { this.currentLocation = value; ModelItem previousModelItem = this.currentModelItem; UpdateCurrentModelItem(); if (this.currentLocation != null && this.currentModelItem == null) { // This is a rare case but it happens when the designer is not all done with bringing up the view but // Debugger already set this location. PostBringToViewCurrentLocation(previousModelItem); } else { BringToViewCurrentLocation(previousModelItem); } } } public void EnsureVisible(SourceLocation sourceLocation) { SourceLocation exactLocation = GetExactLocation(sourceLocation); ModelItem mi = this.GetModelItemFromSourceLocation(exactLocation, /* forceCreate */ true); if (mi != null) { BringToView(mi); } } void BringToViewCurrentLocation(ModelItem previousModelItem) { SetPropertyValue(previousModelItem, isCurrentLocationProperty, this.currentModelItem); if (this.currentModelItem != this.currentModelItemContext) { BringToView(this.currentModelItem); } } // Post new BringToViewCurrentLocation operation void PostBringToViewCurrentLocation(ModelItem previousModelItem) { // Abort pending operation. if (this.bringToViewCurrentLocationOperation != null) { this.bringToViewCurrentLocationOperation.Abort(); this.bringToViewCurrentLocationOperation = null; } // Post a new background operation. this.bringToViewCurrentLocationOperation = Dispatcher.CurrentDispatcher.BeginInvoke( DispatcherPriority.Background, (DispatcherOperationCallback)delegate(object arg) { this.UpdateCurrentModelItem(); this.BringToViewCurrentLocation(previousModelItem); this.bringToViewCurrentLocationOperation = null; return null; }, null); } // Set current context (stack frame scope). // The highlighted scope of execution. public SourceLocation CurrentContext { get { return this.currentContext; } set { this.currentContext = value; ModelItem previousModelItem = this.currentModelItemContext; UpdateCurrentModelItemContext(); SetPropertyValue(previousModelItem, this.isCurrentContextProperty, this.currentModelItemContext); BringToView(this.currentModelItemContext); } } // Set to true while debugging public bool IsDebugging { get { return this.isDebugging; } set { ReadOnlyState readOnlyState = this.context.Items.GetValue<ReadOnlyState>(); if (readOnlyState != null) { // start debugging if (value && !this.isDebugging) { this.isDebugging = true; // backup the read-only state this.isReadOnly = readOnlyState.IsReadOnly; readOnlyState.IsReadOnly = true; } // finish debugging else if (!value && this.isDebugging) { this.isDebugging = false; // restore to previous state before debugging readOnlyState.IsReadOnly = this.isReadOnly; } this.context.Items.SetValue(new ReadOnlyState() { IsReadOnly = readOnlyState.IsReadOnly }); } } } public bool HideSourceFileName { get; set; } void UpdateCurrentModelItem() { this.currentModelItem = this.GetModelItemFromSourceLocation(this.currentLocation, /* forceCreate */ true); } void UpdateCurrentModelItemContext() { this.currentModelItemContext = this.GetModelItemFromSourceLocation(this.currentContext, /* forceCreate */ true); } void BringToView(ModelItem modelItem) { if (modelItem != null) { modelItem.Focus(); } } void OnAttachedPropertiesServiceAvailable(AttachedPropertiesService attachedPropertiesService) { this.isBreakpointEnabledProperty = new AttachedProperty<bool>() { Getter = (modelItem) => IsBreakpointOfType(modelItem, BreakpointTypes.Enabled), Name = "IsBreakpointEnabled", OwnerType = typeof(object) }; this.isBreakpointBoundedProperty = new AttachedProperty<bool>() { Getter = (modelItem) => IsBreakpointOfType(modelItem, BreakpointTypes.Bounded), Name = "IsBreakpointBounded", OwnerType = typeof(object) }; this.isBreakpointConditionalProperty = new AttachedProperty<bool>() { Getter = (modelItem) => IsBreakpointOfType(modelItem, BreakpointTypes.Conditional), Name = "IsBreakpointConditional", OwnerType = typeof(object) }; this.isCurrentLocationProperty = new AttachedProperty<bool>() { Getter = (modelItem) => IsCurrentLocation(modelItem), Name = "IsCurrentLocation", OwnerType = typeof(object) }; this.isCurrentContextProperty = new AttachedProperty<bool>() { Getter = (modelItem) => IsCurrentContext(modelItem), Name = "IsCurrentContext", OwnerType = typeof(object) }; attachedPropertiesService.AddProperty(isBreakpointEnabledProperty); attachedPropertiesService.AddProperty(isBreakpointBoundedProperty); attachedPropertiesService.AddProperty(isBreakpointConditionalProperty); attachedPropertiesService.AddProperty(isCurrentLocationProperty); attachedPropertiesService.AddProperty(isCurrentContextProperty); } void OnModelTreeManagerServiceAvailable(ModelTreeManager modelTreeManager) { this.modelTreeManager = modelTreeManager; this.modelTreeManager.EditingScopeCompleted += OnEditingScopeCompleted; } private void OnEditingScopeCompleted(object sender, EditingScopeEventArgs e) { Fx.Assert(e.EditingScope != null, "e.EditingScope should not be null."); foreach (ModelItem removedModelItem in e.EditingScope.ItemsRemoved) { DeleteModelItem(removedModelItem); } } private void DeleteModelItem(ModelItem modelItem) { if (modelItem != null) { BreakpointTypes breakpointType; if (this.breakpoints.TryGetValue(modelItem, out breakpointType)) { this.transientBreakpoints[modelItem] = breakpointType; // cache it in case it's added later (move case). SetBreakpointType(modelItem, BreakpointTypes.None); // clear breakpoint } DeleteFromMapping(modelItem.GetCurrentValue()); } } // Delete a single object from the mappings. // We only delete unresolved object, i.e. object that never been // saved. We leave the resolved object untouch (otherwise undoing // the removed object will make it as "unresolved" the next time around). void DeleteFromMapping(object unresolvedObject) { SourceLocation sourceLocation; if (this.instanceToSourceLocationMapping.TryGetValue(unresolvedObject, out sourceLocation)) { if (IsUnresolved(sourceLocation)) { this.instanceToSourceLocationMapping.Remove(unresolvedObject); ModelItem modelItem; if (this.sourceLocationToModelItem.TryGetValue(sourceLocation, out modelItem)) { this.sourceLocationToModelItem.Remove(sourceLocation); this.modelItemToSourceLocation.Remove(modelItem); } } } } bool IsCurrentLocation(ModelItem modelItem) { UpdateCurrentModelItem(); return this.currentModelItem == modelItem; } bool IsCurrentContext(ModelItem modelItem) { UpdateCurrentModelItemContext(); return this.currentModelItemContext == modelItem; } void SelectionChanged(Selection selection) { this.selectedModelItem = selection.PrimarySelection; } // Check if unmapped breakpoint exists for the given sourceLocation, // if so, mapped it to the given model item & remove it from unmapped breakpoints. void TryActivateUnmappedBreakpoint(SourceLocation sourceLocation, ModelItem modelItem) { BreakpointTypes breakpointType; if (this.unmappedBreakpoints.TryGetValue(sourceLocation, out breakpointType)) { this.SetBreakpointType(modelItem, breakpointType); this.unmappedBreakpoints.Remove(sourceLocation); } } void TryActivateAllUnmappedBreakpoints() { if (this.unmappedBreakpoints.Count > 0) { List<SourceLocation> unmappedLocations = new List<SourceLocation>(); unmappedLocations.AddRange(this.unmappedBreakpoints.Keys); foreach (SourceLocation unmappedLocation in unmappedLocations) { ModelItem modelItem = this.GetModelItemFromSourceLocation(unmappedLocation); if (modelItem != null) { TryActivateUnmappedBreakpoint(unmappedLocation, modelItem); } } } } bool IsBreakpointOfType(ModelItem modelItem, BreakpointTypes breakpointType) { bool result = false; BreakpointTypes actualBreakpointType; TryActivateAllUnmappedBreakpoints(); if (this.breakpoints.TryGetValue(modelItem, out actualBreakpointType)) { result = (actualBreakpointType & breakpointType) > 0; } return result; } void SetBreakpointType(ModelItem modelItem, BreakpointTypes newBreakpointType) { BreakpointTypes oldBreakpointType = BreakpointTypes.None; if (this.breakpoints.TryGetValue(modelItem, out oldBreakpointType)) { Fx.Assert(oldBreakpointType != BreakpointTypes.None, "Should not store BreakpointType.None"); if (newBreakpointType == BreakpointTypes.None) { this.breakpoints.Remove(modelItem); } else { this.breakpoints[modelItem] = newBreakpointType; } } else if (newBreakpointType != BreakpointTypes.None) { this.breakpoints.Add(modelItem, newBreakpointType); } // Now notifying corresponding properties. if ((oldBreakpointType & BreakpointTypes.Bounded) != (newBreakpointType & BreakpointTypes.Bounded)) { this.isBreakpointBoundedProperty.NotifyPropertyChanged(modelItem); } if ((oldBreakpointType & BreakpointTypes.Enabled) != (newBreakpointType & BreakpointTypes.Enabled)) { this.isBreakpointEnabledProperty.NotifyPropertyChanged(modelItem); } if ((oldBreakpointType & BreakpointTypes.Conditional) != (newBreakpointType & BreakpointTypes.Conditional)) { this.isBreakpointConditionalProperty.NotifyPropertyChanged(modelItem); } } // Return exact source location given approximate location. public SourceLocation GetExactLocation(SourceLocation approximateLocation) { this.EnsureSourceLocationUpdated(); if (approximateLocation == null) { throw FxTrace.Exception.ArgumentNull("approximateLocation"); } SourceLocation exactLocation = null; foreach (SourceLocation sourceLocation in this.instanceToSourceLocationMapping.Values) { if (sourceLocation.StartLine == approximateLocation.StartLine) { exactLocation = sourceLocation; break; } } if (exactLocation == null) { exactLocation = FindClosestSourceLocation(approximateLocation, this.instanceToSourceLocationMapping.Values); } return exactLocation; } // This method tries to find the inner most outer source location from a list // The outer source locations of a source location is ones that contains it // The inner most outer source location is the one nested most deeply, right outside of the source location being contained. private static SourceLocation FindInnerMostContainer(SourceLocation approximateLocation, IEnumerable<SourceLocation> availableSourceLocations) { Fx.Assert(approximateLocation != null && availableSourceLocations != null, "Argument should not be null"); SourceLocation innerMostOuterSourceLocation = null; foreach (SourceLocation sourceLocation in availableSourceLocations) { if (sourceLocation.Contains(approximateLocation)) { if (innerMostOuterSourceLocation == null) { innerMostOuterSourceLocation = sourceLocation; } else { if (innerMostOuterSourceLocation.Contains(sourceLocation)) { innerMostOuterSourceLocation = sourceLocation; } } } } return innerMostOuterSourceLocation; } internal static SourceLocation FindClosestSourceLocation(SourceLocation approximateLocation, IEnumerable<SourceLocation> availableSourceLocations) { Fx.Assert(approximateLocation != null && availableSourceLocations != null, "Argument should not be null"); SourceLocation exactLocation = null; SourceLocation innerMostOuterSourceLocation = FindInnerMostContainer(approximateLocation, availableSourceLocations); if (innerMostOuterSourceLocation != null) { exactLocation = innerMostOuterSourceLocation; } else { // Find the next line of the approximateLocation. int minimumDistance = int.MaxValue; foreach (SourceLocation sourceLocation in availableSourceLocations) { int lineDistance = sourceLocation.StartLine - approximateLocation.StartLine; if ((lineDistance > 0) && ((lineDistance < minimumDistance) || ((lineDistance == minimumDistance) && (sourceLocation.StartColumn < exactLocation.StartColumn)))) // if same distance, then compare the start column { exactLocation = sourceLocation; minimumDistance = lineDistance; } } } return exactLocation; } // Called after a Save by AddIn to update breakpoints with new locations public IDictionary<SourceLocation, BreakpointTypes> GetBreakpointLocations() { IDictionary<SourceLocation, BreakpointTypes> breakpointLocations = new Dictionary<SourceLocation, BreakpointTypes>(); // Collect source locations of model items with breakpoints if (this.breakpoints.Count > 0 || this.unmappedBreakpoints.Count > 0) { foreach (KeyValuePair<ModelItem, BreakpointTypes> entry in this.breakpoints) { SourceLocation breakpointLocation = this.GetSourceLocationFromModelItem(entry.Key); // BreakpointLocation can be null, if the model item is deleted but without notification // through OnModelChanged. This happens when the breakpoint is located inside child // of a deleted object. if (breakpointLocation != null) { breakpointLocations.Add(breakpointLocation, entry.Value); } } foreach (KeyValuePair<SourceLocation, BreakpointTypes> entry in this.unmappedBreakpoints) { breakpointLocations.Add(entry.Key, entry.Value); } } return breakpointLocations; } // Inserting a new breakpoint of a given type. public void InsertBreakpoint(SourceLocation sourceLocation, BreakpointTypes breakpointType) { this.UpdateBreakpoint(sourceLocation, breakpointType); } // Update the appearance of a given breakpoint to show the given type. public void UpdateBreakpoint(SourceLocation sourceLocation, BreakpointTypes newBreakpointType) { ModelItem modelItem = this.GetModelItemFromSourceLocation(sourceLocation); if (modelItem != null) { SetBreakpointType(modelItem, newBreakpointType); } else { BreakpointTypes oldBreakpointType; if (this.unmappedBreakpoints.TryGetValue(sourceLocation, out oldBreakpointType)) { if (newBreakpointType == BreakpointTypes.None) { this.unmappedBreakpoints.Remove(sourceLocation); } else { this.unmappedBreakpoints[sourceLocation] = newBreakpointType; } } else if (newBreakpointType != BreakpointTypes.None) { this.unmappedBreakpoints.Add(sourceLocation, newBreakpointType); } } } // Delete a breakpoint. public void DeleteBreakpoint(SourceLocation sourceLocation) { UpdateBreakpoint(sourceLocation, BreakpointTypes.None); } // Reset breakpoints: delete and prepare for breakpoint refresh. public void ResetBreakpoints() { ModelItem[] oldModelItems = new ModelItem[this.breakpoints.Keys.Count]; this.breakpoints.Keys.CopyTo(oldModelItems, 0); this.breakpoints.Clear(); this.unmappedBreakpoints.Clear(); // Now notifying update to corresponding properties. foreach (ModelItem modelItem in oldModelItems) { this.isBreakpointBoundedProperty.NotifyPropertyChanged(modelItem); this.isBreakpointEnabledProperty.NotifyPropertyChanged(modelItem); this.isBreakpointConditionalProperty.NotifyPropertyChanged(modelItem); } } public void UpdateSourceLocations(Dictionary<object, SourceLocation> newSourceLocationMapping) { if (newSourceLocationMapping == null) { throw FxTrace.Exception.ArgumentNull("newSourceLocationMapping"); } // Update unmappedBreakpoints before refreshing the instanceToSourceLocationMapping. if (this.unmappedBreakpoints.Count > 0) { Dictionary<SourceLocation, BreakpointTypes> newUnmappedBreakpoints = new Dictionary<SourceLocation, BreakpointTypes>(this.unmappedBreakpoints.Count); foreach (KeyValuePair<object, SourceLocation> kvpEntry in this.instanceToSourceLocationMapping) { if (this.unmappedBreakpoints.ContainsKey(kvpEntry.Value)) { if (newSourceLocationMapping.ContainsKey(kvpEntry.Key)) { newUnmappedBreakpoints.Add(newSourceLocationMapping[kvpEntry.Key], this.unmappedBreakpoints[kvpEntry.Value]); } } } this.unmappedBreakpoints = newUnmappedBreakpoints; } // It is possible that after InvalidateSourceLocationMapping, before UpdateSourceLocations, we introduced new unresolvedEntries. // These entries should not be dropped, or we will not be able to add breakpoint before UpdateSourceLocation. List<KeyValuePair<object, SourceLocation>> unresolvedEntries = this.instanceToSourceLocationMapping.Where(entry => IsUnresolved(entry.Value)).ToList(); this.instanceToSourceLocationMapping = newSourceLocationMapping; this.sourceLocationToModelItem.Clear(); this.modelItemToSourceLocation.Clear(); this.transientBreakpoints.Clear(); if (this.modelTreeManager != null) { foreach (KeyValuePair<object, SourceLocation> kvp in newSourceLocationMapping) { ModelItem modelItem = this.modelTreeManager.GetModelItem(kvp.Key); if (modelItem != null) { SourceLocation sourceLocation = kvp.Value; this.modelItemToSourceLocation.Add(modelItem, sourceLocation); this.sourceLocationToModelItem.Add(sourceLocation, modelItem); } } foreach (KeyValuePair<object, SourceLocation> unresolvedEntry in unresolvedEntries) { object unresolvedObject = unresolvedEntry.Key; SourceLocation sourceLocation = unresolvedEntry.Value; if (!this.instanceToSourceLocationMapping.ContainsKey(unresolvedObject)) { this.instanceToSourceLocationMapping.Add(unresolvedObject, sourceLocation); ModelItem modelItem = this.modelTreeManager.GetModelItem(unresolvedObject); if (modelItem != null) { this.modelItemToSourceLocation.Add(modelItem, sourceLocation); this.sourceLocationToModelItem.Add(sourceLocation, modelItem); } } } } TryActivateAllUnmappedBreakpoints(); } // Called by View Service when a new view element is created private void ViewCreated(object sender, ViewCreatedEventArgs e) { if (e.View != null) { ModelItem modelItem = e.View.ModelItem; object addedObject = modelItem.GetCurrentValue(); // Create a mapping between SourceLocation and this View Element SourceLocation sourceLocation = this.GetSourceLocationFromModelItemInstance(addedObject); if (sourceLocation == null) { // The current view element has not been saved yet to the Xaml file sourceLocation = GenerateUnresolvedLocation(); this.instanceToSourceLocationMapping.Add(addedObject, sourceLocation); } this.modelItemToSourceLocation[modelItem] = sourceLocation; this.sourceLocationToModelItem[sourceLocation] = modelItem; BreakpointTypes breakpointType; // check if it's in the transient breakpoint list. if (this.transientBreakpoints.TryGetValue(modelItem, out breakpointType)) { this.transientBreakpoints.Remove(modelItem); SetBreakpointType(modelItem, breakpointType); } else { TryActivateUnmappedBreakpoint(sourceLocation, modelItem); } } } private SourceLocation GenerateUnresolvedLocation() { return new SourceLocation(unresolvedPrefix + this.context.Items.GetValue<WorkflowFileItem>().LoadedFile, this.lastSourceLineNo++); } private static bool IsUnresolved(SourceLocation sourceLocation) { return !string.IsNullOrEmpty(sourceLocation.FileName) && sourceLocation.FileName.StartsWith(unresolvedPrefix, StringComparison.OrdinalIgnoreCase); } // This method is called during Load/Save - the resolved mapping should be invalidated. internal void InvalidateSourceLocationMapping(string fileName) { this.fileName = fileName; this.requiresUpdateSourceLocation = true; // Remove, from the SourceLocationMappings, the entries with resolved SourceLocation - they are no longer valid and should be refreshed. List<KeyValuePair<ModelItem, SourceLocation>> resolvedEntries = this.modelItemToSourceLocation.Where(entry => !IsUnresolved(entry.Value)).ToList(); foreach (KeyValuePair<ModelItem, SourceLocation> resolvedEntry in resolvedEntries) { this.modelItemToSourceLocation.Remove(resolvedEntry.Key); this.sourceLocationToModelItem.Remove(resolvedEntry.Value); this.instanceToSourceLocationMapping.Remove(resolvedEntry.Key.GetCurrentValue()); } // All breakpoint should simply stay - unmappedBreakpoint will get updated to newSourceLocation when we have the newSourceLocation. } private void EnsureSourceLocationUpdated() { Fx.Assert(this.modelSearchService != null, "ModelSearchService should be available and is ensured in WorkflowDesigner constructor"); if (this.requiresUpdateSourceLocation) { Dictionary<object, SourceLocation> updatedSourceLocations = new Dictionary<object, SourceLocation>(); foreach (ModelItem key in this.modelSearchService.GetObjectsWithSourceLocation()) { // disallow expressions if (AllowBreakpointAttribute.IsBreakpointAllowed(key.ItemType) && !typeof(IValueSerializableExpression).IsAssignableFrom(key.ItemType)) { SourceLocation sourceLocationWithoutFileName = this.modelSearchService.FindSourceLocation(key); // Appending the fileName SourceLocation sourceLocationWithFileName = new SourceLocation(this.fileName, sourceLocationWithoutFileName.StartLine, sourceLocationWithoutFileName.StartColumn, sourceLocationWithoutFileName.EndLine, sourceLocationWithoutFileName.EndColumn); updatedSourceLocations.Add(key.GetCurrentValue(), sourceLocationWithFileName); } } this.UpdateSourceLocations(updatedSourceLocations); this.requiresUpdateSourceLocation = false; } } private void OnModelSearchServiceAvailable(ModelSearchService modelSearchService) { this.modelSearchService = (ModelSearchServiceImpl)modelSearchService; } private void OnViewServiceAvailable(ViewService viewService) { this.viewService = (WorkflowViewService)viewService; this.viewService.ViewCreated += this.ViewCreated; } private SourceLocation GetSourceLocationFromModelItemInstance(object instance) { SourceLocation sourceLocation; // instanceToSourceLocationMapping contains source locations for all instances // immediately after a Load or save. For instances that have been just dropped into // the Designer from the Toolbox, we want to return null from here and treat them // as "Unresolved" in the caller. if (this.instanceToSourceLocationMapping.TryGetValue(instance, out sourceLocation)) { return sourceLocation; } else { return null; } } private void SetPropertyValue(ModelItem oldModelItem, AttachedProperty property, ModelItem newModelItem) { // update the previous ModelItem (what was current before) if (oldModelItem != null) { property.NotifyPropertyChanged(oldModelItem); } // update the current Modelitem if (newModelItem != null) { property.NotifyPropertyChanged(newModelItem); } } private SourceLocation GetSourceLocationFromModelItem(ModelItem modelItem) { this.EnsureSourceLocationUpdated(); SourceLocation sourceLocation = null; if (modelItem != null) { this.modelItemToSourceLocation.TryGetValue(modelItem, out sourceLocation); } return sourceLocation; } private ModelItem GetModelItemFromSourceLocation(SourceLocation sourceLocation) { return GetModelItemFromSourceLocation(sourceLocation, /* forceCreate = */ false); } private ModelItem GetModelItemFromSourceLocation(SourceLocation sourceLocation, bool forceCreate) { ModelItem modelItem = null; if (sourceLocation != null) { if (!this.sourceLocationToModelItem.TryGetValue(sourceLocation, out modelItem)) { if (forceCreate) { object foundElement = null; foreach (KeyValuePair<object, SourceLocation> kvp in this.instanceToSourceLocationMapping) { if (kvp.Value.Equals(sourceLocation)) { foundElement = kvp.Key; break; } } if (foundElement != null) { modelItem = Validation.ValidationService.FindModelItem(this.modelTreeManager, foundElement); if (modelItem != null) { this.modelItemToSourceLocation.Add(modelItem, sourceLocation); this.sourceLocationToModelItem.Add(sourceLocation, modelItem); } } } } } return modelItem; } } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; #if !NETCF using System.Text.RegularExpressions; #endif namespace NAssert.Constraints { #region StringConstraint /// <summary> /// StringConstraint is the abstract base for constraints /// that operate on strings. It supports the IgnoreCase /// modifier for string operations. /// </summary> public abstract class StringConstraint : Constraint { /// <summary> /// The expected value /// </summary> protected string expected; /// <summary> /// Indicates whether tests should be case-insensitive /// </summary> protected bool caseInsensitive; /// <summary> /// Constructs a StringConstraint given an expected value /// </summary> /// <param name="expected">The expected value</param> public StringConstraint(string expected) : base(expected) { this.expected = expected; } /// <summary> /// Modify the constraint to ignore case in matching. /// </summary> public StringConstraint IgnoreCase { get { caseInsensitive = true; return this; } } } #endregion #region EmptyStringConstraint /// <summary> /// EmptyStringConstraint tests whether a string is empty. /// </summary> public class EmptyStringConstraint : Constraint { /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public override bool Matches(object actual) { this.actual = actual; if (!(actual is string)) return false; return (string)actual == string.Empty; } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public override void WriteDescriptionTo(MessageWriter writer) { writer.Write("<empty>"); } } #endregion #region NullOrEmptyStringConstraint /// <summary> /// NullEmptyStringConstraint tests whether a string is either null or empty. /// </summary> public class NullOrEmptyStringConstraint : Constraint { /// <summary> /// Constructs a new NullOrEmptyStringConstraint /// </summary> public NullOrEmptyStringConstraint() { this.DisplayName = "nullorempty"; } /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public override bool Matches(object actual) { this.actual = actual; if (actual == null) return true; if (!(actual is string)) throw new ArgumentException("Actual value must be a string", "actual"); return (string)actual == string.Empty; } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public override void WriteDescriptionTo(MessageWriter writer) { writer.Write("null or empty string"); } } #endregion #region Substring Constraint /// <summary> /// SubstringConstraint can test whether a string contains /// the expected substring. /// </summary> public class SubstringConstraint : StringConstraint { /// <summary> /// Initializes a new instance of the <see cref="T:SubstringConstraint"/> class. /// </summary> /// <param name="expected">The expected.</param> public SubstringConstraint(string expected) : base(expected) { } /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public override bool Matches(object actual) { this.actual = actual; if ( !(actual is string) ) return false; if (this.caseInsensitive) return ((string)actual).ToLower().IndexOf(expected.ToLower()) >= 0; else return ((string)actual).IndexOf(expected) >= 0; } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("String containing"); writer.WriteExpectedValue(expected); if ( this.caseInsensitive ) writer.WriteModifier( "ignoring case" ); } } #endregion #region StartsWithConstraint /// <summary> /// StartsWithConstraint can test whether a string starts /// with an expected substring. /// </summary> public class StartsWithConstraint : StringConstraint { /// <summary> /// Initializes a new instance of the <see cref="T:StartsWithConstraint"/> class. /// </summary> /// <param name="expected">The expected string</param> public StartsWithConstraint(string expected) : base(expected) { } /// <summary> /// Test whether the constraint is matched by the actual value. /// This is a template method, which calls the IsMatch method /// of the derived class. /// </summary> /// <param name="actual"></param> /// <returns></returns> public override bool Matches(object actual) { this.actual = actual; if (!(actual is string)) return false; if ( this.caseInsensitive ) return ((string)actual).ToLower().StartsWith(expected.ToLower()); else return ((string)actual).StartsWith(expected); } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("String starting with"); writer.WriteExpectedValue( MsgUtils.ClipString(expected, writer.MaxLineLength - 40, 0) ); if ( this.caseInsensitive ) writer.WriteModifier( "ignoring case" ); } } #endregion #region EndsWithConstraint /// <summary> /// EndsWithConstraint can test whether a string ends /// with an expected substring. /// </summary> public class EndsWithConstraint : StringConstraint { /// <summary> /// Initializes a new instance of the <see cref="T:EndsWithConstraint"/> class. /// </summary> /// <param name="expected">The expected string</param> public EndsWithConstraint(string expected) : base(expected) { } /// <summary> /// Test whether the constraint is matched by the actual value. /// This is a template method, which calls the IsMatch method /// of the derived class. /// </summary> /// <param name="actual"></param> /// <returns></returns> public override bool Matches(object actual) { this.actual = actual; if (!(actual is string)) return false; if ( this.caseInsensitive ) return ((string)actual).ToLower().EndsWith(expected.ToLower()); else return ((string)actual).EndsWith(expected); } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("String ending with"); writer.WriteExpectedValue(expected); if ( this.caseInsensitive ) writer.WriteModifier( "ignoring case" ); } } #endregion #region RegexConstraint #if !NETCF /// <summary> /// RegexConstraint can test whether a string matches /// the pattern provided. /// </summary> public class RegexConstraint : StringConstraint { /// <summary> /// Initializes a new instance of the <see cref="T:RegexConstraint"/> class. /// </summary> /// <param name="pattern">The pattern.</param> public RegexConstraint(string pattern) : base(pattern) { } /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public override bool Matches(object actual) { this.actual = actual; return actual is string && Regex.IsMatch( (string)actual, this.expected, this.caseInsensitive ? RegexOptions.IgnoreCase : RegexOptions.None ); } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("String matching"); writer.WriteExpectedValue(this.expected); if ( this.caseInsensitive ) writer.WriteModifier( "ignoring case" ); } } #endif #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; internal partial class Interop { internal partial class NtDll { // https://msdn.microsoft.com/en-us/library/bb432380.aspx // https://msdn.microsoft.com/en-us/library/windows/hardware/ff566424.aspx [DllImport(Libraries.NtDll, CharSet = CharSet.Unicode, ExactSpelling = true)] private static extern unsafe int NtCreateFile( out IntPtr FileHandle, DesiredAccess DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes, out IO_STATUS_BLOCK IoStatusBlock, long* AllocationSize, System.IO.FileAttributes FileAttributes, System.IO.FileShare ShareAccess, CreateDisposition CreateDisposition, CreateOptions CreateOptions, void* EaBuffer, uint EaLength); internal static unsafe (int status, IntPtr handle) CreateFile( ReadOnlySpan<char> path, IntPtr rootDirectory, CreateDisposition createDisposition, DesiredAccess desiredAccess = DesiredAccess.FILE_GENERIC_READ | DesiredAccess.SYNCHRONIZE, System.IO.FileShare shareAccess = System.IO.FileShare.ReadWrite | System.IO.FileShare.Delete, System.IO.FileAttributes fileAttributes = 0, CreateOptions createOptions = CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT, ObjectAttributes objectAttributes = ObjectAttributes.OBJ_CASE_INSENSITIVE, void* eaBuffer = null, uint eaLength = 0) { fixed (char* c = &MemoryMarshal.GetReference(path)) { UNICODE_STRING name = new UNICODE_STRING { Length = checked((ushort)(path.Length * sizeof(char))), MaximumLength = checked((ushort)(path.Length * sizeof(char))), Buffer = (IntPtr)c }; OBJECT_ATTRIBUTES attributes = new OBJECT_ATTRIBUTES( &name, objectAttributes, rootDirectory); int status = NtCreateFile( out IntPtr handle, desiredAccess, ref attributes, out IO_STATUS_BLOCK statusBlock, AllocationSize: null, fileAttributes, shareAccess, createDisposition, createOptions, eaBuffer, eaLength); return (status, handle); } } /// <summary> /// File creation disposition when calling directly to NT APIs. /// </summary> public enum CreateDisposition : uint { /// <summary> /// Default. Replace or create. Deletes existing file instead of overwriting. /// </summary> /// <remarks> /// As this potentially deletes it requires that DesiredAccess must include Delete. /// This has no equivalent in CreateFile. /// </remarks> FILE_SUPERSEDE = 0, /// <summary> /// Open if exists or fail if doesn't exist. Equivalent to OPEN_EXISTING or /// <see cref="System.IO.FileMode.Open"/>. /// </summary> /// <remarks> /// TruncateExisting also uses Open and then manually truncates the file /// by calling NtSetInformationFile with FileAllocationInformation and an /// allocation size of 0. /// </remarks> FILE_OPEN = 1, /// <summary> /// Create if doesn't exist or fail if does exist. Equivalent to CREATE_NEW /// or <see cref="System.IO.FileMode.CreateNew"/>. /// </summary> FILE_CREATE = 2, /// <summary> /// Open if exists or create if doesn't exist. Equivalent to OPEN_ALWAYS or /// <see cref="System.IO.FileMode.OpenOrCreate"/>. /// </summary> FILE_OPEN_IF = 3, /// <summary> /// Open and overwrite if exists or fail if doesn't exist. Equivalent to /// TRUNCATE_EXISTING or <see cref="System.IO.FileMode.Truncate"/>. /// </summary> FILE_OVERWRITE = 4, /// <summary> /// Open and overwrite if exists or create if doesn't exist. Equivalent to /// CREATE_ALWAYS or <see cref="System.IO.FileMode.Create"/>. /// </summary> FILE_OVERWRITE_IF = 5 } /// <summary> /// Options for creating/opening files with NtCreateFile. /// </summary> public enum CreateOptions : uint { /// <summary> /// File being created or opened must be a directory file. Disposition must be FILE_CREATE, FILE_OPEN, /// or FILE_OPEN_IF. /// </summary> /// <remarks> /// Can only be used with FILE_SYNCHRONOUS_IO_ALERT/NONALERT, FILE_WRITE_THROUGH, FILE_OPEN_FOR_BACKUP_INTENT, /// and FILE_OPEN_BY_FILE_ID flags. /// </remarks> FILE_DIRECTORY_FILE = 0x00000001, /// <summary> /// Applications that write data to the file must actually transfer the data into /// the file before any requested write operation is considered complete. This flag /// is set automatically if FILE_NO_INTERMEDIATE_BUFFERING is set. /// </summary> FILE_WRITE_THROUGH = 0x00000002, /// <summary> /// All accesses to the file are sequential. /// </summary> FILE_SEQUENTIAL_ONLY = 0x00000004, /// <summary> /// File cannot be cached in driver buffers. Cannot use with AppendData desired access. /// </summary> FILE_NO_INTERMEDIATE_BUFFERING = 0x00000008, /// <summary> /// All operations are performed synchronously. Any wait on behalf of the caller is /// subject to premature termination from alerts. /// </summary> /// <remarks> /// Cannot be used with FILE_SYNCHRONOUS_IO_NONALERT. /// Synchronous DesiredAccess flag is required. I/O system will maintain file position context. /// </remarks> FILE_SYNCHRONOUS_IO_ALERT = 0x00000010, /// <summary> /// All operations are performed synchronously. Waits in the system to synchronize I/O queuing /// and completion are not subject to alerts. /// </summary> /// <remarks> /// Cannot be used with FILE_SYNCHRONOUS_IO_ALERT. /// Synchronous DesiredAccess flag is required. I/O system will maintain file position context. /// </remarks> FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020, /// <summary> /// File being created or opened must not be a directory file. Can be a data file, device, /// or volume. /// </summary> FILE_NON_DIRECTORY_FILE = 0x00000040, /// <summary> /// Create a tree connection for this file in order to open it over the network. /// </summary> /// <remarks> /// Not used by device and intermediate drivers. /// </remarks> FILE_CREATE_TREE_CONNECTION = 0x00000080, /// <summary> /// Complete the operation immediately with a success code of STATUS_OPLOCK_BREAK_IN_PROGRESS if /// the target file is oplocked. /// </summary> /// <remarks> /// Not compatible with ReserveOpfilter or OpenRequiringOplock. /// Not used by device and intermediate drivers. /// </remarks> FILE_COMPLETE_IF_OPLOCKED = 0x00000100, /// <summary> /// If the extended attributes on an existing file being opened indicate that the caller must /// understand extended attributes to properly interpret the file, fail the request. /// </summary> /// <remarks> /// Not used by device and intermediate drivers. /// </remarks> FILE_NO_EA_KNOWLEDGE = 0x00000200, // Behavior undocumented, defined in headers // FILE_OPEN_REMOTE_INSTANCE = 0x00000400, /// <summary> /// Accesses to the file can be random, so no sequential read-ahead operations should be performed /// on the file by FSDs or the system. /// </summary> FILE_RANDOM_ACCESS = 0x00000800, /// <summary> /// Delete the file when the last handle to it is passed to NtClose. Requires Delete flag in /// DesiredAccess parameter. /// </summary> FILE_DELETE_ON_CLOSE = 0x00001000, /// <summary> /// Open the file by reference number or object ID. The file name that is specified by the ObjectAttributes /// name parameter includes the 8 or 16 byte file reference number or ID for the file in the ObjectAttributes /// name field. The device name can optionally be prefixed. /// </summary> /// <remarks> /// NTFS supports both reference numbers and object IDs. 16 byte reference numbers are 8 byte numbers padded /// with zeros. ReFS only supports reference numbers (not object IDs). 8 byte and 16 byte reference numbers /// are not related. Note that as the UNICODE_STRING will contain raw byte data, it may not be a "valid" string. /// Not used by device and intermediate drivers. /// </remarks> /// <example> /// \??\C:\{8 bytes of binary FileID} /// \device\HardDiskVolume1\{16 bytes of binary ObjectID} /// {8 bytes of binary FileID} /// </example> FILE_OPEN_BY_FILE_ID = 0x00002000, /// <summary> /// The file is being opened for backup intent. Therefore, the system should check for certain access rights /// and grant the caller the appropriate access to the file before checking the DesiredAccess parameter /// against the file's security descriptor. /// </summary> /// <remarks> /// Not used by device and intermediate drivers. /// </remarks> FILE_OPEN_FOR_BACKUP_INTENT = 0x00004000, /// <summary> /// When creating a file, specifies that it should not inherit the compression bit from the parent directory. /// </summary> FILE_NO_COMPRESSION = 0x00008000, /// <summary> /// The file is being opened and an opportunistic lock (oplock) on the file is being requested as a single atomic /// operation. /// </summary> /// <remarks> /// The file system checks for oplocks before it performs the create operation and will fail the create with a /// return code of STATUS_CANNOT_BREAK_OPLOCK if the result would be to break an existing oplock. /// Not compatible with CompleteIfOplocked or ReserveOpFilter. Windows 7 and up. /// </remarks> FILE_OPEN_REQUIRING_OPLOCK = 0x00010000, /// <summary> /// CreateFile2 uses this flag to prevent opening a file that you don't have access to without specifying /// FILE_SHARE_READ. (Preventing users that can only read a file from denying access to other readers.) /// </summary> /// <remarks> /// Windows 7 and up. /// </remarks> FILE_DISALLOW_EXCLUSIVE = 0x00020000, /// <summary> /// The client opening the file or device is session aware and per session access is validated if necessary. /// </summary> /// <remarks> /// Windows 8 and up. /// </remarks> FILE_SESSION_AWARE = 0x00040000, /// <summary> /// This flag allows an application to request a filter opportunistic lock (oplock) to prevent other applications /// from getting share violations. /// </summary> /// <remarks> /// Not compatible with CompleteIfOplocked or OpenRequiringOplock. /// If there are already open handles, the create request will fail with STATUS_OPLOCK_NOT_GRANTED. /// </remarks> FILE_RESERVE_OPFILTER = 0x00100000, /// <summary> /// Open a file with a reparse point attribute, bypassing the normal reparse point processing. /// </summary> FILE_OPEN_REPARSE_POINT = 0x00200000, /// <summary> /// Causes files that are marked with the Offline attribute not to be recalled from remote storage. /// </summary> /// <remarks> /// More details can be found in Remote Storage documentation (see Basic Concepts). /// https://technet.microsoft.com/en-us/library/cc938459.aspx /// </remarks> FILE_OPEN_NO_RECALL = 0x00400000 // Behavior undocumented, defined in headers // FILE_OPEN_FOR_FREE_SPACE_QUERY = 0x00800000 } /// <summary> /// System.IO.FileAccess looks up these values when creating handles /// </summary> /// <remarks> /// File Security and Access Rights /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399.aspx /// </remarks> [Flags] public enum DesiredAccess : uint { // File Access Rights Constants // https://msdn.microsoft.com/en-us/library/windows/desktop/gg258116.aspx /// <summary> /// For a file, the right to read data from the file. /// </summary> /// <remarks> /// Directory version of this flag is <see cref="FILE_LIST_DIRECTORY"/>. /// </remarks> FILE_READ_DATA = 0x0001, /// <summary> /// For a directory, the right to list the contents. /// </summary> /// <remarks> /// File version of this flag is <see cref="FILE_READ_DATA"/>. /// </remarks> FILE_LIST_DIRECTORY = 0x0001, /// <summary> /// For a file, the right to write data to the file. /// </summary> /// <remarks> /// Directory version of this flag is <see cref="FILE_ADD_FILE"/>. /// </remarks> FILE_WRITE_DATA = 0x0002, /// <summary> /// For a directory, the right to create a file in a directory. /// </summary> /// <remarks> /// File version of this flag is <see cref="FILE_WRITE_DATA"/>. /// </remarks> FILE_ADD_FILE = 0x0002, /// <summary> /// For a file, the right to append data to a file. <see cref="FILE_WRITE_DATA"/> is needed /// to overwrite existing data. /// </summary> /// <remarks> /// Directory version of this flag is <see cref="FILE_ADD_SUBDIRECTORY"/>. /// </remarks> FILE_APPEND_DATA = 0x0004, /// <summary> /// For a directory, the right to create a subdirectory. /// </summary> /// <remarks> /// File version of this flag is <see cref="FILE_APPEND_DATA"/>. /// </remarks> FILE_ADD_SUBDIRECTORY = 0x0004, /// <summary> /// For a named pipe, the right to create a pipe instance. /// </summary> FILE_CREATE_PIPE_INSTANCE = 0x0004, /// <summary> /// The right to read extended attributes. /// </summary> FILE_READ_EA = 0x0008, /// <summary> /// The right to write extended attributes. /// </summary> FILE_WRITE_EA = 0x0010, /// <summary> /// The right to execute the file. /// </summary> /// <remarks> /// Directory version of this flag is <see cref="FILE_TRAVERSE"/>. /// </remarks> FILE_EXECUTE = 0x0020, /// <summary> /// For a directory, the right to traverse the directory. /// </summary> /// <remarks> /// File version of this flag is <see cref="FILE_EXECUTE"/>. /// </remarks> FILE_TRAVERSE = 0x0020, /// <summary> /// For a directory, the right to delete a directory and all /// the files it contains, including read-only files. /// </summary> FILE_DELETE_CHILD = 0x0040, /// <summary> /// The right to read attributes. /// </summary> FILE_READ_ATTRIBUTES = 0x0080, /// <summary> /// The right to write attributes. /// </summary> FILE_WRITE_ATTRIBUTES = 0x0100, /// <summary> /// All standard and specific rights. [FILE_ALL_ACCESS] /// </summary> FILE_ALL_ACCESS = DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER | 0x1FF, /// <summary> /// The right to delete the object. /// </summary> DELETE = 0x00010000, /// <summary> /// The right to read the information in the object's security descriptor. /// Doesn't include system access control list info (SACL). /// </summary> READ_CONTROL = 0x00020000, /// <summary> /// The right to modify the discretionary access control list (DACL) in the /// object's security descriptor. /// </summary> WRITE_DAC = 0x00040000, /// <summary> /// The right to change the owner in the object's security descriptor. /// </summary> WRITE_OWNER = 0x00080000, /// <summary> /// The right to use the object for synchronization. Enables a thread to wait until the object /// is in the signaled state. This is required if opening a synchronous handle. /// </summary> SYNCHRONIZE = 0x00100000, /// <summary> /// Same as READ_CONTROL. /// </summary> STANDARD_RIGHTS_READ = READ_CONTROL, /// <summary> /// Same as READ_CONTROL. /// </summary> STANDARD_RIGHTS_WRITE = READ_CONTROL, /// <summary> /// Same as READ_CONTROL. /// </summary> STANDARD_RIGHTS_EXECUTE = READ_CONTROL, /// <summary> /// Maps internally to <see cref="FILE_READ_ATTRIBUTES"/> | <see cref="FILE_READ_DATA"/> | <see cref="FILE_READ_EA"/> /// | <see cref="STANDARD_RIGHTS_READ"/> | <see cref="SYNCHRONIZE"/>. /// (For directories, <see cref="FILE_READ_ATTRIBUTES"/> | <see cref="FILE_LIST_DIRECTORY"/> | <see cref="FILE_READ_EA"/> /// | <see cref="STANDARD_RIGHTS_READ"/> | <see cref="SYNCHRONIZE"/>.) /// </summary> FILE_GENERIC_READ = 0x80000000, // GENERIC_READ /// <summary> /// Maps internally to <see cref="FILE_APPEND_DATA"/> | <see cref="FILE_WRITE_ATTRIBUTES"/> | <see cref="FILE_WRITE_DATA"/> /// | <see cref="FILE_WRITE_EA"/> | <see cref="STANDARD_RIGHTS_READ"/> | <see cref="SYNCHRONIZE"/>. /// (For directories, <see cref="FILE_ADD_SUBDIRECTORY"/> | <see cref="FILE_WRITE_ATTRIBUTES"/> | <see cref="FILE_ADD_FILE"/> AddFile /// | <see cref="FILE_WRITE_EA"/> | <see cref="STANDARD_RIGHTS_READ"/> | <see cref="SYNCHRONIZE"/>.) /// </summary> FILE_GENERIC_WRITE = 0x40000000, // GENERIC WRITE /// <summary> /// Maps internally to <see cref="FILE_EXECUTE"/> | <see cref="FILE_READ_ATTRIBUTES"/> | <see cref="STANDARD_RIGHTS_EXECUTE"/> /// | <see cref="SYNCHRONIZE"/>. /// (For directories, <see cref="FILE_DELETE_CHILD"/> | <see cref="FILE_READ_ATTRIBUTES"/> | <see cref="STANDARD_RIGHTS_EXECUTE"/> /// | <see cref="SYNCHRONIZE"/>.) /// </summary> FILE_GENERIC_EXECUTE = 0x20000000 // GENERIC_EXECUTE } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Text; namespace SocketHttpListener.Net { [Serializable] [ComVisible(true)] public class WebHeaderCollection : NameValueCollection, ISerializable { [Flags] internal enum HeaderInfo { Request = 1, Response = 1 << 1, MultiValue = 1 << 10 } static readonly bool[] allowed_chars = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, true, true, true, false, false, false, true, true, false, true, true, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, false }; static readonly Dictionary<string, HeaderInfo> headers; HeaderInfo? headerRestriction; HeaderInfo? headerConsistency; static WebHeaderCollection() { headers = new Dictionary<string, HeaderInfo>(StringComparer.OrdinalIgnoreCase) { { "Allow", HeaderInfo.MultiValue }, { "Accept", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Accept-Charset", HeaderInfo.MultiValue }, { "Accept-Encoding", HeaderInfo.MultiValue }, { "Accept-Language", HeaderInfo.MultiValue }, { "Accept-Ranges", HeaderInfo.MultiValue }, { "Age", HeaderInfo.Response }, { "Authorization", HeaderInfo.MultiValue }, { "Cache-Control", HeaderInfo.MultiValue }, { "Cookie", HeaderInfo.MultiValue }, { "Connection", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Content-Encoding", HeaderInfo.MultiValue }, { "Content-Length", HeaderInfo.Request | HeaderInfo.Response }, { "Content-Type", HeaderInfo.Request }, { "Content-Language", HeaderInfo.MultiValue }, { "Date", HeaderInfo.Request }, { "Expect", HeaderInfo.Request | HeaderInfo.MultiValue}, { "Host", HeaderInfo.Request }, { "If-Match", HeaderInfo.MultiValue }, { "If-Modified-Since", HeaderInfo.Request }, { "If-None-Match", HeaderInfo.MultiValue }, { "Keep-Alive", HeaderInfo.Response }, { "Pragma", HeaderInfo.MultiValue }, { "Proxy-Authenticate", HeaderInfo.MultiValue }, { "Proxy-Authorization", HeaderInfo.MultiValue }, { "Proxy-Connection", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Range", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Referer", HeaderInfo.Request }, { "Set-Cookie", HeaderInfo.MultiValue }, { "Set-Cookie2", HeaderInfo.MultiValue }, { "Server", HeaderInfo.Response }, { "TE", HeaderInfo.MultiValue }, { "Trailer", HeaderInfo.MultiValue }, { "Transfer-Encoding", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo.MultiValue }, { "Translate", HeaderInfo.Request | HeaderInfo.Response }, { "Upgrade", HeaderInfo.MultiValue }, { "User-Agent", HeaderInfo.Request }, { "Vary", HeaderInfo.MultiValue }, { "Via", HeaderInfo.MultiValue }, { "Warning", HeaderInfo.MultiValue }, { "WWW-Authenticate", HeaderInfo.Response | HeaderInfo. MultiValue }, { "SecWebSocketAccept", HeaderInfo.Response }, { "SecWebSocketExtensions", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo. MultiValue }, { "SecWebSocketKey", HeaderInfo.Request }, { "Sec-WebSocket-Protocol", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo. MultiValue }, { "SecWebSocketVersion", HeaderInfo.Response | HeaderInfo. MultiValue } }; } // Constructors public WebHeaderCollection() { } protected WebHeaderCollection(SerializationInfo serializationInfo, StreamingContext streamingContext) { int count; try { count = serializationInfo.GetInt32("Count"); for (int i = 0; i < count; i++) this.Add(serializationInfo.GetString(i.ToString()), serializationInfo.GetString((count + i).ToString())); } catch (SerializationException) { count = serializationInfo.GetInt32("count"); for (int i = 0; i < count; i++) this.Add(serializationInfo.GetString("k" + i), serializationInfo.GetString("v" + i)); } } internal WebHeaderCollection(HeaderInfo headerRestriction) { this.headerRestriction = headerRestriction; } // Methods public void Add(string header) { if (header == null) throw new ArgumentNullException("header"); int pos = header.IndexOf(':'); if (pos == -1) throw new ArgumentException("no colon found", "header"); this.Add(header.Substring(0, pos), header.Substring(pos + 1)); } public override void Add(string name, string value) { if (name == null) throw new ArgumentNullException("name"); CheckRestrictedHeader(name); this.AddWithoutValidate(name, value); } protected void AddWithoutValidate(string headerName, string headerValue) { if (!IsHeaderName(headerName)) throw new ArgumentException("invalid header name: " + headerName, "headerName"); if (headerValue == null) headerValue = String.Empty; else headerValue = headerValue.Trim(); if (!IsHeaderValue(headerValue)) throw new ArgumentException("invalid header value: " + headerValue, "headerValue"); AddValue(headerName, headerValue); } internal void AddValue(string headerName, string headerValue) { base.Add(headerName, headerValue); } internal string[] GetValues_internal(string header, bool split) { if (header == null) throw new ArgumentNullException("header"); string[] values = base.GetValues(header); if (values == null || values.Length == 0) return null; if (split && IsMultiValue(header)) { List<string> separated = null; foreach (var value in values) { if (value.IndexOf(',') < 0) continue; if (separated == null) { separated = new List<string>(values.Length + 1); foreach (var v in values) { if (v == value) break; separated.Add(v); } } var slices = value.Split(','); var slices_length = slices.Length; if (value[value.Length - 1] == ',') --slices_length; for (int i = 0; i < slices_length; ++i) { separated.Add(slices[i].Trim()); } } if (separated != null) return separated.ToArray(); } return values; } public override string[] GetValues(string header) { return GetValues_internal(header, true); } public override string[] GetValues(int index) { string[] values = base.GetValues(index); if (values == null || values.Length == 0) { return null; } return values; } public static bool IsRestricted(string headerName) { return IsRestricted(headerName, false); } public static bool IsRestricted(string headerName, bool response) { if (headerName == null) throw new ArgumentNullException("headerName"); if (headerName.Length == 0) throw new ArgumentException("empty string", "headerName"); if (!IsHeaderName(headerName)) throw new ArgumentException("Invalid character in header"); HeaderInfo info; if (!headers.TryGetValue(headerName, out info)) return false; var flag = response ? HeaderInfo.Response : HeaderInfo.Request; return (info & flag) != 0; } public override void OnDeserialization(object sender) { } public override void Remove(string name) { if (name == null) throw new ArgumentNullException("name"); CheckRestrictedHeader(name); base.Remove(name); } public override void Set(string name, string value) { if (name == null) throw new ArgumentNullException("name"); if (!IsHeaderName(name)) throw new ArgumentException("invalid header name"); if (value == null) value = String.Empty; else value = value.Trim(); if (!IsHeaderValue(value)) throw new ArgumentException("invalid header value"); CheckRestrictedHeader(name); base.Set(name, value); } public byte[] ToByteArray() { return Encoding.UTF8.GetBytes(ToString()); } internal string ToStringMultiValue() { StringBuilder sb = new StringBuilder(); int count = base.Count; for (int i = 0; i < count; i++) { string key = GetKey(i); if (IsMultiValue(key)) { foreach (string v in GetValues(i)) { sb.Append(key) .Append(": ") .Append(v) .Append("\r\n"); } } else { sb.Append(key) .Append(": ") .Append(Get(i)) .Append("\r\n"); } } return sb.Append("\r\n").ToString(); } public override string ToString() { StringBuilder sb = new StringBuilder(); int count = base.Count; for (int i = 0; i < count; i++) sb.Append(GetKey(i)) .Append(": ") .Append(Get(i)) .Append("\r\n"); return sb.Append("\r\n").ToString(); } #if !TARGET_JVM void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { GetObjectData(serializationInfo, streamingContext); } #endif public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { int count = base.Count; serializationInfo.AddValue("Count", count); for (int i = 0; i < count; i++) { serializationInfo.AddValue(i.ToString(), GetKey(i)); serializationInfo.AddValue((count + i).ToString(), Get(i)); } } public override string[] AllKeys { get { return base.AllKeys; } } public override int Count { get { return base.Count; } } public override KeysCollection Keys { get { return base.Keys; } } public override string Get(int index) { return base.Get(index); } public override string Get(string name) { return base.Get(name); } public override string GetKey(int index) { return base.GetKey(index); } public void Add(HttpRequestHeader header, string value) { Add(RequestHeaderToString(header), value); } public void Remove(HttpRequestHeader header) { Remove(RequestHeaderToString(header)); } public void Set(HttpRequestHeader header, string value) { Set(RequestHeaderToString(header), value); } public void Add(HttpResponseHeader header, string value) { Add(ResponseHeaderToString(header), value); } public void Remove(HttpResponseHeader header) { Remove(ResponseHeaderToString(header)); } public void Set(HttpResponseHeader header, string value) { Set(ResponseHeaderToString(header), value); } public string this[HttpRequestHeader header] { get { return Get(RequestHeaderToString(header)); } set { Set(header, value); } } public string this[HttpResponseHeader header] { get { return Get(ResponseHeaderToString(header)); } set { Set(header, value); } } public override void Clear() { base.Clear(); } public override IEnumerator GetEnumerator() { return base.GetEnumerator(); } // Internal Methods // With this we don't check for invalid characters in header. See bug #55994. internal void SetInternal(string header) { int pos = header.IndexOf(':'); if (pos == -1) throw new ArgumentException("no colon found", "header"); SetInternal(header.Substring(0, pos), header.Substring(pos + 1)); } internal void SetInternal(string name, string value) { if (value == null) value = String.Empty; else value = value.Trim(); if (!IsHeaderValue(value)) throw new ArgumentException("invalid header value"); if (IsMultiValue(name)) { base.Add(name, value); } else { base.Remove(name); base.Set(name, value); } } internal void RemoveAndAdd(string name, string value) { if (value == null) value = String.Empty; else value = value.Trim(); base.Remove(name); base.Set(name, value); } internal void RemoveInternal(string name) { if (name == null) throw new ArgumentNullException("name"); base.Remove(name); } // Private Methods string RequestHeaderToString(HttpRequestHeader value) { CheckHeaderConsistency(HeaderInfo.Request); switch (value) { case HttpRequestHeader.CacheControl: return "Cache-Control"; case HttpRequestHeader.Connection: return "Connection"; case HttpRequestHeader.Date: return "Date"; case HttpRequestHeader.KeepAlive: return "Keep-Alive"; case HttpRequestHeader.Pragma: return "Pragma"; case HttpRequestHeader.Trailer: return "Trailer"; case HttpRequestHeader.TransferEncoding: return "Transfer-Encoding"; case HttpRequestHeader.Upgrade: return "Upgrade"; case HttpRequestHeader.Via: return "Via"; case HttpRequestHeader.Warning: return "Warning"; case HttpRequestHeader.Allow: return "Allow"; case HttpRequestHeader.ContentLength: return "Content-Length"; case HttpRequestHeader.ContentType: return "Content-Type"; case HttpRequestHeader.ContentEncoding: return "Content-Encoding"; case HttpRequestHeader.ContentLanguage: return "Content-Language"; case HttpRequestHeader.ContentLocation: return "Content-Location"; case HttpRequestHeader.ContentMd5: return "Content-MD5"; case HttpRequestHeader.ContentRange: return "Content-Range"; case HttpRequestHeader.Expires: return "Expires"; case HttpRequestHeader.LastModified: return "Last-Modified"; case HttpRequestHeader.Accept: return "Accept"; case HttpRequestHeader.AcceptCharset: return "Accept-Charset"; case HttpRequestHeader.AcceptEncoding: return "Accept-Encoding"; case HttpRequestHeader.AcceptLanguage: return "accept-language"; case HttpRequestHeader.Authorization: return "Authorization"; case HttpRequestHeader.Cookie: return "Cookie"; case HttpRequestHeader.Expect: return "Expect"; case HttpRequestHeader.From: return "From"; case HttpRequestHeader.Host: return "Host"; case HttpRequestHeader.IfMatch: return "If-Match"; case HttpRequestHeader.IfModifiedSince: return "If-Modified-Since"; case HttpRequestHeader.IfNoneMatch: return "If-None-Match"; case HttpRequestHeader.IfRange: return "If-Range"; case HttpRequestHeader.IfUnmodifiedSince: return "If-Unmodified-Since"; case HttpRequestHeader.MaxForwards: return "Max-Forwards"; case HttpRequestHeader.ProxyAuthorization: return "Proxy-Authorization"; case HttpRequestHeader.Referer: return "Referer"; case HttpRequestHeader.Range: return "Range"; case HttpRequestHeader.Te: return "TE"; case HttpRequestHeader.Translate: return "Translate"; case HttpRequestHeader.UserAgent: return "User-Agent"; default: throw new InvalidOperationException(); } } string ResponseHeaderToString(HttpResponseHeader value) { CheckHeaderConsistency(HeaderInfo.Response); switch (value) { case HttpResponseHeader.CacheControl: return "Cache-Control"; case HttpResponseHeader.Connection: return "Connection"; case HttpResponseHeader.Date: return "Date"; case HttpResponseHeader.KeepAlive: return "Keep-Alive"; case HttpResponseHeader.Pragma: return "Pragma"; case HttpResponseHeader.Trailer: return "Trailer"; case HttpResponseHeader.TransferEncoding: return "Transfer-Encoding"; case HttpResponseHeader.Upgrade: return "Upgrade"; case HttpResponseHeader.Via: return "Via"; case HttpResponseHeader.Warning: return "Warning"; case HttpResponseHeader.Allow: return "Allow"; case HttpResponseHeader.ContentLength: return "Content-Length"; case HttpResponseHeader.ContentType: return "Content-Type"; case HttpResponseHeader.ContentEncoding: return "Content-Encoding"; case HttpResponseHeader.ContentLanguage: return "Content-Language"; case HttpResponseHeader.ContentLocation: return "Content-Location"; case HttpResponseHeader.ContentMd5: return "Content-MD5"; case HttpResponseHeader.ContentRange: return "Content-Range"; case HttpResponseHeader.Expires: return "Expires"; case HttpResponseHeader.LastModified: return "Last-Modified"; case HttpResponseHeader.AcceptRanges: return "Accept-Ranges"; case HttpResponseHeader.Age: return "Age"; case HttpResponseHeader.ETag: return "ETag"; case HttpResponseHeader.Location: return "Location"; case HttpResponseHeader.ProxyAuthenticate: return "Proxy-Authenticate"; case HttpResponseHeader.RetryAfter: return "Retry-After"; case HttpResponseHeader.Server: return "Server"; case HttpResponseHeader.SetCookie: return "Set-Cookie"; case HttpResponseHeader.Vary: return "Vary"; case HttpResponseHeader.WwwAuthenticate: return "WWW-Authenticate"; default: throw new InvalidOperationException(); } } void CheckRestrictedHeader(string headerName) { if (!headerRestriction.HasValue) return; HeaderInfo info; if (!headers.TryGetValue(headerName, out info)) return; if ((info & headerRestriction.Value) != 0) throw new ArgumentException("This header must be modified with the appropiate property."); } void CheckHeaderConsistency(HeaderInfo value) { if (!headerConsistency.HasValue) { headerConsistency = value; return; } if ((headerConsistency & value) == 0) throw new InvalidOperationException(); } internal static bool IsMultiValue(string headerName) { if (headerName == null) return false; HeaderInfo info; return headers.TryGetValue(headerName, out info) && (info & HeaderInfo.MultiValue) != 0; } internal static bool IsHeaderValue(string value) { // TEXT any 8 bit value except CTL's (0-31 and 127) // but including \r\n space and \t // after a newline at least one space or \t must follow // certain header fields allow comments () int len = value.Length; for (int i = 0; i < len; i++) { char c = value[i]; if (c == 127) return false; if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t')) return false; if (c == '\n' && ++i < len) { c = value[i]; if (c != ' ' && c != '\t') return false; } } return true; } internal static bool IsHeaderName(string name) { if (name == null || name.Length == 0) return false; int len = name.Length; for (int i = 0; i < len; i++) { char c = name[i]; if (c > 126 || !allowed_chars[c]) return false; } return true; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: supply/rpc/ota_base_supply_svc.proto #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace HOLMS.Types.Supply.RPC { public static partial class OtaBaseSupplySvc { static readonly string __ServiceName = "holms.types.supply.rpc.OtaBaseSupplySvc"; static readonly grpc::Marshaller<global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest> __Marshaller_OtaSupplyDetailsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsResponse> __Marshaller_OtaSupplyDetailsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest> __Marshaller_ChannelAllocationUpdateRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> __Marshaller_ChannelAllocationUpdateResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Supply.RPC.ChannelStopSellUpdateRequest> __Marshaller_ChannelStopSellUpdateRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.RPC.ChannelStopSellUpdateRequest.Parser.ParseFrom); static readonly grpc::Method<global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest, global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsResponse> __Method_AllForDates = new grpc::Method<global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest, global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsResponse>( grpc::MethodType.Unary, __ServiceName, "AllForDates", __Marshaller_OtaSupplyDetailsRequest, __Marshaller_OtaSupplyDetailsResponse); static readonly grpc::Method<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest, global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> __Method_InsertOrUpdateSupply = new grpc::Method<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest, global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse>( grpc::MethodType.Unary, __ServiceName, "InsertOrUpdateSupply", __Marshaller_ChannelAllocationUpdateRequest, __Marshaller_ChannelAllocationUpdateResponse); static readonly grpc::Method<global::HOLMS.Types.Supply.RPC.ChannelStopSellUpdateRequest, global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> __Method_UpdateStopSell = new grpc::Method<global::HOLMS.Types.Supply.RPC.ChannelStopSellUpdateRequest, global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse>( grpc::MethodType.Unary, __ServiceName, "UpdateStopSell", __Marshaller_ChannelStopSellUpdateRequest, __Marshaller_ChannelAllocationUpdateResponse); static readonly grpc::Method<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest, global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> __Method_UpdatePrice = new grpc::Method<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest, global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse>( grpc::MethodType.Unary, __ServiceName, "UpdatePrice", __Marshaller_ChannelAllocationUpdateRequest, __Marshaller_ChannelAllocationUpdateResponse); static readonly grpc::Method<global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest, global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> __Method_SyncChannelRush = new grpc::Method<global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest, global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse>( grpc::MethodType.Unary, __ServiceName, "SyncChannelRush", __Marshaller_OtaSupplyDetailsRequest, __Marshaller_ChannelAllocationUpdateResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.OtaBaseSupplySvcReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of OtaBaseSupplySvc</summary> public abstract partial class OtaBaseSupplySvcBase { public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsResponse> AllForDates(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> InsertOrUpdateSupply(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> UpdateStopSell(global::HOLMS.Types.Supply.RPC.ChannelStopSellUpdateRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> UpdatePrice(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> SyncChannelRush(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for OtaBaseSupplySvc</summary> public partial class OtaBaseSupplySvcClient : grpc::ClientBase<OtaBaseSupplySvcClient> { /// <summary>Creates a new client for OtaBaseSupplySvc</summary> /// <param name="channel">The channel to use to make remote calls.</param> public OtaBaseSupplySvcClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for OtaBaseSupplySvc that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public OtaBaseSupplySvcClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected OtaBaseSupplySvcClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected OtaBaseSupplySvcClient(ClientBaseConfiguration configuration) : base(configuration) { } public virtual global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsResponse AllForDates(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AllForDates(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsResponse AllForDates(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AllForDates, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsResponse> AllForDatesAsync(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AllForDatesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsResponse> AllForDatesAsync(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AllForDates, null, options, request); } public virtual global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse InsertOrUpdateSupply(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return InsertOrUpdateSupply(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse InsertOrUpdateSupply(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_InsertOrUpdateSupply, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> InsertOrUpdateSupplyAsync(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return InsertOrUpdateSupplyAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> InsertOrUpdateSupplyAsync(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_InsertOrUpdateSupply, null, options, request); } public virtual global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse UpdateStopSell(global::HOLMS.Types.Supply.RPC.ChannelStopSellUpdateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateStopSell(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse UpdateStopSell(global::HOLMS.Types.Supply.RPC.ChannelStopSellUpdateRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateStopSell, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> UpdateStopSellAsync(global::HOLMS.Types.Supply.RPC.ChannelStopSellUpdateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateStopSellAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> UpdateStopSellAsync(global::HOLMS.Types.Supply.RPC.ChannelStopSellUpdateRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateStopSell, null, options, request); } public virtual global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse UpdatePrice(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdatePrice(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse UpdatePrice(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdatePrice, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> UpdatePriceAsync(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdatePriceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> UpdatePriceAsync(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdatePrice, null, options, request); } public virtual global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse SyncChannelRush(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SyncChannelRush(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse SyncChannelRush(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_SyncChannelRush, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> SyncChannelRushAsync(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SyncChannelRushAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse> SyncChannelRushAsync(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_SyncChannelRush, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override OtaBaseSupplySvcClient NewInstance(ClientBaseConfiguration configuration) { return new OtaBaseSupplySvcClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(OtaBaseSupplySvcBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_AllForDates, serviceImpl.AllForDates) .AddMethod(__Method_InsertOrUpdateSupply, serviceImpl.InsertOrUpdateSupply) .AddMethod(__Method_UpdateStopSell, serviceImpl.UpdateStopSell) .AddMethod(__Method_UpdatePrice, serviceImpl.UpdatePrice) .AddMethod(__Method_SyncChannelRush, serviceImpl.SyncChannelRush).Build(); } } } #endregion
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; using System.Security.Claims; using System.Security.Cryptography; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Testing; using Moq; using Xunit; namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTokenGeneratorProviderTest { [Fact] public void GenerateCookieToken() { // Arrange var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); // Act var token = tokenProvider.GenerateCookieToken(); // Assert Assert.NotNull(token); } [Fact] public void GenerateRequestToken_InvalidCookieToken() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = false }; var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); Assert.False(httpContext.User.Identity.IsAuthenticated); var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); // Act & Assert ExceptionAssert.ThrowsArgument( () => tokenProvider.GenerateRequestToken(httpContext, cookieToken), "cookieToken", "The antiforgery cookie token is invalid."); } [Fact] public void GenerateRequestToken_AnonymousUser() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); Assert.False(httpContext.User.Identity.IsAuthenticated); var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); // Act var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); Assert.False(fieldToken.IsCookieToken); Assert.Empty(fieldToken.Username); Assert.Null(fieldToken.ClaimUid); Assert.Empty(fieldToken.AdditionalData); } [Fact] public void GenerateRequestToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); var options = new AntiforgeryOptions(); var claimUidExtractor = new Mock<IClaimUidExtractor>().Object; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: claimUidExtractor, additionalDataProvider: null); // Act & assert var exception = Assert.Throws<InvalidOperationException>( () => tokenProvider.GenerateRequestToken(httpContext, cookieToken)); Assert.Equal( "The provided identity of type " + $"'{typeof(MyAuthenticatedIdentityWithoutUsername).FullName}' " + "is marked IsAuthenticated = true but does not have a value for Name. " + "By default, the antiforgery system requires that all authenticated identities have a unique Name. " + "If it is not possible to provide a unique Name for this identity, " + "consider extending IAntiforgeryAdditionalDataProvider by overriding the " + "DefaultAntiforgeryAdditionalDataProvider " + "or a custom type that can provide some form of unique identifier for the current user.", exception.Message); } [Fact] public void GenerateRequestToken_AuthenticatedWithoutUsername_WithAdditionalData() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); var mockAdditionalDataProvider = new Mock<IAntiforgeryAdditionalDataProvider>(); mockAdditionalDataProvider.Setup(o => o.GetAdditionalData(httpContext)) .Returns("additional-data"); var claimUidExtractor = new Mock<IClaimUidExtractor>().Object; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: claimUidExtractor, additionalDataProvider: mockAdditionalDataProvider.Object); // Act var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); Assert.False(fieldToken.IsCookieToken); Assert.Empty(fieldToken.Username); Assert.Null(fieldToken.ClaimUid); Assert.Equal("additional-data", fieldToken.AdditionalData); } [Fact] public void GenerateRequestToken_ClaimsBasedIdentity() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var identity = GetAuthenticatedIdentity("some-identity"); var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(identity); byte[] data = new byte[256 / 8]; RandomNumberGenerator.Fill(data); var base64ClaimUId = Convert.ToBase64String(data); var expectedClaimUid = new BinaryBlob(256, data); var mockClaimUidExtractor = new Mock<IClaimUidExtractor>(); mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is<ClaimsPrincipal>(c => c.Identity == identity))) .Returns(base64ClaimUId); var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); // Act var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); Assert.False(fieldToken.IsCookieToken); Assert.Equal("", fieldToken.Username); Assert.Equal(expectedClaimUid, fieldToken.ClaimUid); Assert.Equal("", fieldToken.AdditionalData); } [Fact] public void GenerateRequestToken_RegularUserWithUsername() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var httpContext = new DefaultHttpContext(); var mockIdentity = new Mock<ClaimsIdentity>(); mockIdentity.Setup(o => o.IsAuthenticated) .Returns(true); mockIdentity.Setup(o => o.Name) .Returns("my-username"); httpContext.User = new ClaimsPrincipal(mockIdentity.Object); var claimUidExtractor = new Mock<IClaimUidExtractor>().Object; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: claimUidExtractor, additionalDataProvider: null); // Act var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); Assert.False(fieldToken.IsCookieToken); Assert.Equal("my-username", fieldToken.Username); Assert.Null(fieldToken.ClaimUid); Assert.Empty(fieldToken.AdditionalData); } [Fact] public void IsCookieTokenValid_FieldToken_ReturnsFalse() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = false }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); // Act var isValid = tokenProvider.IsCookieTokenValid(cookieToken); // Assert Assert.False(isValid); } [Fact] public void IsCookieTokenValid_NullToken_ReturnsFalse() { // Arrange AntiforgeryToken cookieToken = null; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); // Act var isValid = tokenProvider.IsCookieTokenValid(cookieToken); // Assert Assert.False(isValid); } [Fact] public void IsCookieTokenValid_ValidToken_ReturnsTrue() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); // Act var isValid = tokenProvider.IsCookieTokenValid(cookieToken); // Assert Assert.True(isValid); } [Fact] public void TryValidateTokenSet_CookieTokenMissing() { // Arrange var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); // Act & Assert string message; var ex = Assert.Throws<ArgumentNullException>( () => tokenProvider.TryValidateTokenSet(httpContext, null, fieldtoken, out message)); Assert.StartsWith(@"The required antiforgery cookie token must be provided.", ex.Message); } [Fact] public void TryValidateTokenSet_FieldTokenMissing() { // Arrange var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); // Act & Assert string message; var ex = Assert.Throws<ArgumentNullException>( () => tokenProvider.TryValidateTokenSet(httpContext, cookieToken, null, out message)); Assert.StartsWith("The required antiforgery request token must be provided.", ex.Message); } [Fact] public void TryValidateTokenSet_FieldAndCookieTokensSwapped_FieldTokenDuplicated() { // Arrange var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); string expectedMessage = "Validation of the provided antiforgery token failed. " + "The cookie token and the request token were swapped."; // Act string message; var result = tokenProvider.TryValidateTokenSet(httpContext, fieldtoken, fieldtoken, out message); // Assert Assert.False(result); Assert.Equal(expectedMessage, message); } [Fact] public void TryValidateTokenSet_FieldAndCookieTokensSwapped_CookieDuplicated() { // Arrange var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); string expectedMessage = "Validation of the provided antiforgery token failed. " + "The cookie token and the request token were swapped."; // Act string message; var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, cookieToken, out message); // Assert Assert.False(result); Assert.Equal(expectedMessage, message); } [Fact] public void TryValidateTokenSet_FieldAndCookieTokensHaveDifferentSecurityKeys() { // Arrange var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); string expectedMessage = "The antiforgery cookie token and request token do not match."; // Act string message; var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.False(result); Assert.Equal(expectedMessage, message); } [Theory] [InlineData("the-user", "the-other-user")] [InlineData("http://example.com/uri-casing", "http://example.com/URI-casing")] [InlineData("https://example.com/secure-uri-casing", "https://example.com/secure-URI-casing")] public void TryValidateTokenSet_UsernameMismatch(string identityUsername, string embeddedUsername) { // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity(identityUsername); httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { SecurityToken = cookieToken.SecurityToken, Username = embeddedUsername, IsCookieToken = false }; var mockClaimUidExtractor = new Mock<IClaimUidExtractor>(); mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is<ClaimsPrincipal>(c => c.Identity == identity))) .Returns((string)null); var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); string expectedMessage = $"The provided antiforgery token was meant for user \"{embeddedUsername}\", " + $"but the current user is \"{identityUsername}\"."; // Act string message; var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.False(result); Assert.Equal(expectedMessage, message); } [Fact] public void TryValidateTokenSet_ClaimUidMismatch() { // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { SecurityToken = cookieToken.SecurityToken, IsCookieToken = false, ClaimUid = new BinaryBlob(256) }; var differentToken = new BinaryBlob(256); var mockClaimUidExtractor = new Mock<IClaimUidExtractor>(); mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is<ClaimsPrincipal>(c => c.Identity == identity))) .Returns(Convert.ToBase64String(differentToken.GetData())); var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); string expectedMessage = "The provided antiforgery token was meant for a different " + "claims-based user than the current user."; // Act string message; var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.False(result); Assert.Equal(expectedMessage, message); } [Fact] public void TryValidateTokenSet_AdditionalDataRejected() { // Arrange var httpContext = new DefaultHttpContext(); var identity = new ClaimsIdentity(); httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { SecurityToken = cookieToken.SecurityToken, Username = String.Empty, IsCookieToken = false, AdditionalData = "some-additional-data" }; var mockAdditionalDataProvider = new Mock<IAntiforgeryAdditionalDataProvider>(); mockAdditionalDataProvider .Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) .Returns(false); var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: mockAdditionalDataProvider.Object); string expectedMessage = "The provided antiforgery token failed a custom data check."; // Act string message; var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.False(result); Assert.Equal(expectedMessage, message); } [Fact] public void TryValidateTokenSet_Success_AnonymousUser() { // Arrange var httpContext = new DefaultHttpContext(); var identity = new ClaimsIdentity(); httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { SecurityToken = cookieToken.SecurityToken, Username = String.Empty, IsCookieToken = false, AdditionalData = "some-additional-data" }; var mockAdditionalDataProvider = new Mock<IAntiforgeryAdditionalDataProvider>(); mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) .Returns(true); var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: mockAdditionalDataProvider.Object); // Act string message; var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.True(result); Assert.Null(message); } [Fact] public void TryValidateTokenSet_Success_AuthenticatedUserWithUsername() { // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { SecurityToken = cookieToken.SecurityToken, Username = "THE-USER", IsCookieToken = false, AdditionalData = "some-additional-data" }; var mockAdditionalDataProvider = new Mock<IAntiforgeryAdditionalDataProvider>(); mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) .Returns(true); var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: new Mock<IClaimUidExtractor>().Object, additionalDataProvider: mockAdditionalDataProvider.Object); // Act string message; var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.True(result); Assert.Null(message); } [Fact] public void TryValidateTokenSet_Success_ClaimsBasedUser() { // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { SecurityToken = cookieToken.SecurityToken, IsCookieToken = false, ClaimUid = new BinaryBlob(256) }; var mockClaimUidExtractor = new Mock<IClaimUidExtractor>(); mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is<ClaimsPrincipal>(c => c.Identity == identity))) .Returns(Convert.ToBase64String(fieldtoken.ClaimUid.GetData())); var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); // Act string message; var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.True(result); Assert.Null(message); } private static ClaimsIdentity GetAuthenticatedIdentity(string identityUsername) { var claim = new Claim(ClaimsIdentity.DefaultNameClaimType, identityUsername); return new ClaimsIdentity(new[] { claim }, "Some-Authentication"); } private sealed class MyAuthenticatedIdentityWithoutUsername : ClaimsIdentity { public override bool IsAuthenticated { get { return true; } } public override string Name { get { return String.Empty; } } } } } #nullable restore
/* * Copyright (c) 2009, Stefan Simek * * 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.Collections.Generic; using System.Diagnostics; using System.Text; using System.Reflection; using System.Reflection.Emit; namespace TriAxis.RunSharp { using Operands; interface ICodeGenContext : IMemberInfo, ISignatureGen, IDelayedDefinition, IDelayedCompletion { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Typical implementation invokes XxxBuilder.GetILGenerator() which is a method as well.")] ILGenerator GetILGenerator(); Type OwnerType { get; } } public partial class CodeGen { ILGenerator il; ICodeGenContext context; ConstructorGen cg; bool chainCalled = false; bool reachable = true; bool hasRetVar = false, hasRetLabel = false; LocalBuilder retVar = null; Label retLabel; Stack<Block> blocks = new Stack<Block>(); internal ILGenerator IL { get { return il; } } internal ICodeGenContext Context { get { return context; } } internal CodeGen(ICodeGenContext context) { this.context = context; this.cg = context as ConstructorGen; il = context.GetILGenerator(); } /*public static CodeGen CreateDynamicMethod(string name, Type returnType, params Type[] parameterTypes, Type owner, bool skipVisibility) { DynamicMethod dm = new DynamicMethod(name, returnType, parameterTypes, owner, skipVisibility); return new CodeGen(method.GetILGenerator(), defaultType, method.ReturnType, method.IsStatic, parameterTypes); } public static CodeGen FromMethodBuilder(MethodBuilder builder, params Type[] parameterTypes) { return new CodeGen(builder.GetILGenerator(), builder.DeclaringType, builder.ReturnType, builder.IsStatic, parameterTypes); } public static CodeGen FromConstructorBuilder(ConstructorBuilder builder, params Type[] parameterTypes) { return new CodeGen(builder.GetILGenerator(), builder.DeclaringType, builder.ReturnType, builder.IsStatic, parameterTypes); }*/ #region Arguments public Operand This() { if (context.IsStatic) throw new InvalidOperationException(Properties.Messages.ErrCodeStaticThis); return new _Arg(0, context.OwnerType); } public Operand Base() { if (context.IsStatic) return new _StaticTarget(context.OwnerType.BaseType); else return new _Base(context.OwnerType.BaseType); } int _ThisOffset { get { return context.IsStatic ? 0 : 1; } } public Operand PropertyValue() { Type[] parameterTypes = context.ParameterTypes; return new _Arg(_ThisOffset + parameterTypes.Length - 1, parameterTypes[parameterTypes.Length - 1]); } public Operand Arg(string name) { ParameterGen param = context.GetParameterByName(name); return new _Arg(_ThisOffset + param.Position - 1, param.Type); } #endregion #region Locals public Operand Local() { return new _Local(this); } public Operand Local(Operand init) { Operand var = Local(); Assign(var, init); return var; } public Operand Local(Type type) { return new _Local(this, type); } public Operand Local(Type type, Operand init) { Operand var = Local(type); Assign(var, init); return var; } #endregion bool HasReturnValue { get { Type returnType = context.ReturnType; return returnType != null && returnType != typeof(void); } } void EnsureReturnVariable() { if (hasRetVar) return; retLabel = il.DefineLabel(); if (HasReturnValue) retVar = il.DeclareLocal(context.ReturnType); hasRetVar = true; } public bool IsCompleted { get { return blocks.Count == 0 && !reachable && hasRetVar == hasRetLabel; } } internal void Complete() { if (blocks.Count > 0) throw new InvalidOperationException(Properties.Messages.ErrOpenBlocksRemaining); if (reachable) { if (HasReturnValue) throw new InvalidOperationException(string.Format(null, Properties.Messages.ErrMethodMustReturnValue, context)); else Return(); } if (hasRetVar && !hasRetLabel) { il.MarkLabel(retLabel); if (retVar != null) il.Emit(OpCodes.Ldloc, retVar); il.Emit(OpCodes.Ret); hasRetLabel = true; } } class _Base : _Arg { public _Base(Type type) : base(0, type) { } internal override bool SuppressVirtual { get { return true; } } } class _Arg : Operand { ushort index; Type type; public _Arg(int index, Type type) { this.index = checked((ushort)index); this.type = type; } internal override void EmitGet(CodeGen g) { g.EmitLdargHelper(index); if (IsReference) g.EmitLdindHelper(Type); } internal override void EmitSet(CodeGen g, Operand value, bool allowExplicitConversion) { if (IsReference) { g.EmitLdargHelper(index); g.EmitStindHelper(Type, value, allowExplicitConversion); } else { g.EmitGetHelper(value, Type, allowExplicitConversion); g.EmitStargHelper(index); } } internal override void EmitAddressOf(CodeGen g) { if (IsReference) { g.EmitLdargHelper(index); } else { if (index <= byte.MaxValue) g.il.Emit(OpCodes.Ldarga_S, (byte)index); else g.il.Emit(OpCodes.Ldarga, index); } } bool IsReference { get { return type.IsByRef; } } public override Type Type { get { return IsReference ? type.GetElementType() : type; } } internal override bool TrivialAccess { get { return true; } } } internal class _Local : Operand { CodeGen owner; LocalBuilder var; Block scope; Type t, tHint; public _Local(CodeGen owner) { this.owner = owner; scope = owner.GetBlockForVariable(); } public _Local(CodeGen owner, Type t) { this.owner = owner; this.t = t; scope = owner.GetBlockForVariable(); } public _Local(CodeGen owner, LocalBuilder var) { this.owner = owner; this.var = var; this.t = var.LocalType; } void CheckScope(CodeGen g) { if (g != owner) throw new InvalidOperationException(Properties.Messages.ErrInvalidVariableContext); if (scope != null && !owner.blocks.Contains(scope)) throw new InvalidOperationException(Properties.Messages.ErrInvalidVariableScope); } internal override void EmitGet(CodeGen g) { CheckScope(g); if (var == null) throw new InvalidOperationException(Properties.Messages.ErrUninitializedVarAccess); g.il.Emit(OpCodes.Ldloc, var); } internal override void EmitSet(CodeGen g, Operand value, bool allowExplicitConversion) { CheckScope(g); if (t == null) t = value.Type; if (var == null) var = g.il.DeclareLocal(t); g.EmitGetHelper(value, t, allowExplicitConversion); g.il.Emit(OpCodes.Stloc, var); } internal override void EmitAddressOf(CodeGen g) { CheckScope(g); if (var == null) { RequireType(); var = g.il.DeclareLocal(t); } g.il.Emit(OpCodes.Ldloca, var); } public override Type Type { get { RequireType(); return t; } } void RequireType() { if (t == null) { if (tHint != null) t = tHint; else throw new InvalidOperationException(Properties.Messages.ErrUntypedVarAccess); } } internal override bool TrivialAccess { get { return true; } } internal override void AssignmentHint(Operand op) { if (tHint == null) tHint = Operand.GetType(op); } } class _StaticTarget : Operand { Type t; public _StaticTarget(Type t) { this.t = t; } public override Type Type { get { return t; } } internal override bool IsStaticTarget { get { return true; } } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using ProBuilder2.Common; using ProBuilder2.Math; using ProBuilder2.MeshOperations; using System.Linq; [RequireComponent(typeof(pb_Object))] [RequireComponent(typeof(MeshCollider))] public class Pipe : MonoBehaviour { #region Members int maximumPipeTurns = 200; ///< How many turns to make before ending this pipe. const int MAX_TURNS_PER_SEGMENT = 10; ///< Extruding from large pb_Objects can be slow - so every 10 turns detach to a new object. float minimumStretchDistance = 1f; ///< Minimum distance a pipe stretch can be. float maximumStretchDistance = 10f; ///< Maximum distance a pipe stretch can be. float speed = 3f; ///< Meters per second. pb_Object pb; ///< Cache the pb_Object component pb_Face[] movingFaces; ///< The faces we're current extruding pb_Face[] neighborFaces = new pb_Face[0]; ///< All faces connected to the extruded faces (they'll need to have their UVs refreshed) float size = 1f; int[] selectedTriangles; ///< All the triangles contained in the movingFaces array. Vector3 nrm = Vector3.zero; ///< The normal of the currently extruding face. float extrudeDist = 0f; ///< How far to extrude to the current faces. float currentDistanceTraveled = 0f; // How far this pipe has extruded. bool isPaused = false; ///< Is this segment paused? protected bool isTurn = false; ///< Used to toggle the traveling distance of faces. If is a turn, only go one meter ///< then choose a new direction. Otherwise, choose a random distance and direction. Bounds bounds; ///< How far in any direction to go before turning back. int turnCount = 0; Pipe parent = null; ///< If this pipe is a child, keep track of the parent so we can call OnPipeFinished for only the top. Pipe child = null; public delegate void OnPipeFinishedEvent(Pipe pipe); public event OnPipeFinishedEvent OnPipeFinished; #endregion #region Initialization /** * Sets things in motion! */ public void Start() { pb = GetComponent<pb_Object>(); // When detaching, we're going right into a turn so we won't get the opportunity to set this in the usual Turn() spot. // Set it here. If this is the first segment in a pipe, this value will be overwritten by Turn(). movingFaces = new pb_Face[1] { pb.faces[0] }; selectedTriangles = pb_Face.AllTriangles(movingFaces); nrm = pb_Math.Normal(pb, movingFaces[0]); Turn(); } #endregion #region Get /** * Is this segment finished running? */ public bool IsPaused() { return isPaused; } #endregion #region Set /** * Stops new appendages from sprouting and fires the OnPipeFinished event. */ public void EndPipe() { Pipe p = this; while(p.child != null) p = p.child; p.EndPipe_Internal(); } /** * We only ever really want to call EndPipe from the most recent child in the chain, so expose * that in EndPipe() and keep the actual endpipe call here where we know it's being called * correctly. */ protected void EndPipe_Internal() { Pause(); if( OnPipeFinished != null) OnPipeFinished(this); this.enabled = false; } /** * OnPipeFinished should only be called once, from the first spawned pipe in this chain. * This allows instance objects to keep track of who's top. */ public void SetParent(Pipe parent) { this.parent = parent; } /** * Pause extrusion. This segment is finished. */ void Pause() { isPaused = true; } /** * Set the size of the pipe. Used when creating elbows for turns. */ public void SetSize(float size) { this.size = size; } /** * Set the maximum bounds within which appendages may roam. */ public void SetBounds(Bounds bounds) { this.bounds = bounds; } /** * Set the speed with which this pipe will be elongated. */ public void SetSpeed(float speed) { this.speed = speed; } /** * Set the minimum and maximum distance that pipe lengths may travel before turning. */ public void SetStretchRange(float min, float max) { this.minimumStretchDistance = min; this.maximumStretchDistance = max; } /** * If the pipe doesn't run out of turns before this value, complete the pipe. */ public void SetMaxTurns(int maxTurns) { this.maximumPipeTurns = maxTurns; } #endregion #region Loop /** * The Update loop. Moves vertices using TranslateVertices and updates the UVs where necesary. */ void Update() { // If paused, don't do anything. if(isPaused) return; float delta = speed * Time.deltaTime; // Check if we're going to overshoot our target extrude distance, and if so clip the delta if(currentDistanceTraveled + delta >= extrudeDist) delta = extrudeDist - currentDistanceTraveled; // Increment the currentDistanceTraveled var currentDistanceTraveled += delta; // Move the selected faces. pb.TranslateVertices(selectedTriangles, nrm * delta); // When moving faces, you also need to update the UVs that would be affected by movement. // RefreshUVs() accepts an array of faces so that you can control exactly which UVs are // updated. This is important because re-projecting UVs can be expensive, so you want to // keep these calls to as few faces as is necessary. pb.RefreshUV(neighborFaces.ToArray()); // If we've traveled as far as necessary, turn! if(currentDistanceTraveled >= extrudeDist) Turn(); } #endregion #region Branching /** * Extrudes a faces out from the current arm, then picks * a new face to extrude from and determines how far it should extrude. */ void Turn() { if(turnCount > MAX_TURNS_PER_SEGMENT && isTurn) { DetachChild(); return; } // Check to see if this object is out of turns. if(turnCount > maximumPipeTurns) EndPipe_Internal(); // Set the extrude distance to either elbow distance, or a new pipe distance. extrudeDist = isTurn ? size : Random.Range(minimumStretchDistance, maximumStretchDistance); // Assign the MeshCollider's mesh to match the currently rendering mesh. `pb.msh` is just // an alias for `pb.gameObject.GetComponent<MeshFilter>().sharedMesh`. GetComponent<MeshCollider>().sharedMesh = pb.msh; // If this is a turning peice, just extrude and move the faces along the same normal for an additional 1m. if(!isTurn) { bool invalidDirection = true; List<int> invalidFaces = new List<int>(); int faceCount = neighborFaces.Length > 0 ? neighborFaces.Length : pb.faces.Length; /** * If the face chosen to extrude from will collide with either the bounds or another pipe, try extruding from a different face. * In the event that no face can be extruded safely, end the pipe. */ while( invalidDirection && invalidFaces.Count < faceCount ) { //If this is the first turn, just grab any face on the object. Otherwise, use //one of the neighbor faces. int faceIndex; // Get a face that hasn't already failed collision detection. int n = 0; do { faceIndex = (int)Random.Range(0, faceCount); if(n++ > 20) { // this shouldn't happen often, but when it does it's crazy annoying and Unity freezes. EndPipe_Internal(); return; } } while(invalidFaces.Contains(faceIndex)); // If this is the first run, neighborFaces won't be populated yet, so just choose a random face to start with. if(neighborFaces.Length > 0) movingFaces = new pb_Face[] { neighborFaces[ faceIndex ] }; else movingFaces = new pb_Face[] { pb.faces[ faceIndex ] }; // Get all the triangles contained in the currently moving faces array. TranslateVertices // does not contain overloads for moving faces or edges, you'll always need to feed it // triangle data. selectedTriangles = pb_Face.AllTriangles(movingFaces); // Get the direction vector for the first face. We could get the average of all selected // faces, but in this case it's safe to assume that the faces are all sharing a normal // (because we wrote it that way!). nrm = pb_Math.Normal(pb, movingFaces[0]); // Check that the selected face won't be extending into another pipe (or itself), and will remain within the bounds. invalidDirection = DetectCollision( pb_Math.Average(pb.VerticesInWorldSpace(selectedTriangles)), pb.transform.TransformDirection(nrm), extrudeDist ); // Keep track of faces that failed collision detection (a collision was detected). if(invalidDirection) invalidFaces.Add(faceIndex); } // There's nowhere for this pipe to go. Destroy it and tell the PipeSpawner // that it needs to create a new one. if(invalidFaces.Count >= faceCount) { EndPipe_Internal(); return; } } // Extrude the movingFaces out a tiny distance to avoid popping graphics, but enough to allow // normals and tangents to calculate properly (the Refresh() call does this for you). The last // out param in Extrude is optional, and is populated with the newly created faces on each // perimeter edge of the extuded faces. pb.Extrude(movingFaces, .0001f, true, out neighborFaces); // As of 2.4, mesh operation calls no longer rebuild the mesh. It is necessary to call ToMesh() // after any elements are added or removed prior to Refresh() now. pb.ToMesh(); // Refresh the normals, tangents, and uvs. In the Editor, you should also call pb.GenerateUV2(), // but since this is runtime we don't care about UV2 channels. pb.Refresh(); // Remove the currently moving faces from the connectedFaces array, since we don't want to go // direction twice. // neighborFaces.RemoveAll(x => System.Array.IndexOf(movingFaces, x) > -1); neighborFaces = neighborFaces.Where( x => System.Array.IndexOf(movingFaces, x) < 0 ).ToArray(); // Reset currentDistanceTraveled currentDistanceTraveled = .0001f; // If this is a turn, increment the turn count. if(isTurn) turnCount++; // Now toggle isTurn. isTurn = !isTurn; } /** * Extruding can get expensive when an object has many faces. This creates a new * pb_Object pipe by detaching the currently moving faces into a new object, then * sets that pipe in motion. */ void DetachChild() { // First order of business - stop extruding from this segment. Pause(); // DetachFacesToObject can fail, so it returns a bool with the success status. // If it fails, end this pipe tree. Otherwise, copy will be set to the new // pb_Object. pb_Object copy; if(DetachFacesToObject(pb, movingFaces, out copy)) { // Huzzah! DetachFacesToObject worked, and we now have 2 separate pb_Objects. // The first gets all the faces in movingFaces deleted, and the duplicate gets // all faces that *aren't* movingFaces deleted. child = copy.gameObject.AddComponent<Pipe>(); child.gameObject.name = "ChildPipe: " + child.gameObject.GetInstanceID(); // Let the child know who's boss. child.SetParent(this); // Aaand child inherits all the same paremeters that this branch has. child.SetSpeed(this.speed); child.SetSize(this.size); child.SetBounds(this.bounds); child.SetStretchRange(this.minimumStretchDistance, maximumStretchDistance); child.SetMaxTurns(this.maximumPipeTurns - turnCount); // Unlike the first segment, children should start with a turn. child.isTurn = true; // Now pass a reference to PipeSpawner's OnPipeFinished delegate to the child's OnPipeFinished event handler. child.OnPipeFinished += OnPipeFinished; } else { // Poop. DetachFacesToObject failed. Put this branch out of it's misery now. EndPipe_Internal(); } } /** * Deletes @faces from the passed pb_Object, and creates a new pb_Object using @faces. On success, * detachedObject will be set to the new pb_Object. * * NOTE - As of 2.3, `DetachFacesToObject` was not publicly available in the pbMeshOps. This method * was made available in 2.3.1 as an extension method to pb_Object: * `pbMeshOps::DetachFacesToObject(this pb_Object pb, pb_Face[] faces, out pb_Object detachedObject)` */ static bool DetachFacesToObject(pb_Object pb, pb_Face[] faces, out pb_Object detachedObject) { detachedObject = null; if(faces.Length < 1 || faces.Length == pb.faces.Length) return false; int[] primary = new int[faces.Length]; for(int i = 0; i < primary.Length; i++) primary[i] = System.Array.IndexOf(pb.faces, faces[i]); int[] inverse = new int[pb.faces.Length - primary.Length]; int n = 0; for(int i = 0; i < pb.faces.Length; i++) if(System.Array.IndexOf(primary, i) < 0) inverse[n++] = i; detachedObject = pb_Object.InitWithObject(pb); detachedObject.transform.position = pb.transform.position; detachedObject.transform.localScale = pb.transform.localScale; detachedObject.transform.localRotation = pb.transform.localRotation; pb.DeleteFaces(primary); detachedObject.DeleteFaces(inverse); pb.ToMesh(); detachedObject.ToMesh(); pb.Refresh(); detachedObject.Refresh(); detachedObject.gameObject.name = pb.gameObject.name + "-detach"; return true; } #endregion #region Collision Logic /** * Given a point and direction in normal space, casts a ray checking for possible collision * with either itself or the pipe's bounding box. * @todo - Return the distance from position to collision point so that we can adjust the * extrude distance. This way we'd see a lot less failed collision detections. */ bool DetectCollision(Vector3 position, Vector3 direction, float distance) { distance += size; /** * First check if the ending position will be inside the pipe's bounds. */ Vector3 end = position + direction * distance; if(!bounds.Contains(end)) { Debug.DrawRay(position, direction * distance, new Color( Mathf.Abs(direction.x), Mathf.Abs(direction.y), Mathf.Abs(direction.z), 1f), 2f, true); return true; } Ray ray = new Ray(position, direction); RaycastHit hit; if(Physics.Raycast(ray, out hit, distance)) { return true; } return false; } #endregion #region Cleanup /** * Begin fading out this object. At the end of the fade, destroy this gameObject. */ public void FadeOut(float fadeTime, float delay, Material fadeMaterial) { if(parent != null) parent.FadeOut(fadeTime, delay, fadeMaterial); pb.SetFaceMaterial(pb.faces, fadeMaterial); pb.ToMesh(); pb.Refresh(); this.enabled = true; StartCoroutine( Fade(fadeTime, delay) ); } /** * Lerp the material's alpha channel down to 0f over @time. Then destroy the object. */ IEnumerator Fade(float time, float delay) { yield return new WaitForSeconds(delay); // we *do* want to instance the material in this case. Material mat = GetComponent<MeshRenderer>().material; Color col = mat.color; float timer = 0f; while(timer < 1f) { timer += Time.deltaTime / time; col.a = Mathf.Lerp(1f, 0f, timer); mat.color = col; yield return null; } GameObject.Destroy(mat); GameObject.Destroy(gameObject); yield return null; } #endregion }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.IO.Abstractions; using System.Linq; using System.Threading; using System.Threading.Tasks; using TSQLLint.Common; using TSQLLint.Core.Interfaces; using TSQLLint.Infrastructure.Plugins; using TSQLLint.Infrastructure.Rules.RuleExceptions; namespace TSQLLint.Infrastructure.Parser { public class SqlFileProcessor : ISqlFileProcessor { private readonly IRuleVisitor ruleVisitor; private readonly IReporter reporter; private readonly IFileSystem fileSystem; private readonly IPluginHandler pluginHandler; private readonly IRuleExceptionFinder ruleExceptionFinder; private ConcurrentDictionary<string, Stream> fileStreams = new ConcurrentDictionary<string, Stream>(); public SqlFileProcessor(IRuleVisitor ruleVisitor, IPluginHandler pluginHandler, IReporter reporter, IFileSystem fileSystem) { this.ruleVisitor = ruleVisitor; this.pluginHandler = pluginHandler; this.reporter = reporter; this.fileSystem = fileSystem; ruleExceptionFinder = new RuleExceptionFinder(); } private int _fileCount; public int FileCount { get { return _fileCount; } } public void ProcessList(List<string> filePaths) { Parallel.ForEach(filePaths, (path) => { processPath(path); }); foreach (var sqlFile in fileStreams) { HandleProcessing(sqlFile.Key, sqlFile.Value); sqlFile.Value.Dispose(); } } public void ProcessPath(string path) { processPath(path); foreach (var sqlFile in fileStreams) { HandleProcessing(sqlFile.Key, sqlFile.Value); sqlFile.Value.Dispose(); } } private void processPath(string path) { // remove quotes from filePaths path = path.Replace("\"", string.Empty); var filePathList = path.Split(','); for (var index = 0; index < filePathList.Length; index++) { // remove leading and trailing whitespace filePathList[index] = filePathList[index].Trim(); } Parallel.ForEach(filePathList, (filePath) => { if (!fileSystem.File.Exists(filePath)) { if (fileSystem.Directory.Exists(filePath)) { ProcessDirectory(filePath); } else { ProcessWildCard(filePath); } } else { ProcessFile(filePath); } }); } private void ProcessFile(string filePath) { var fileStream = GetFileContents(filePath); AddToProcessing(filePath, fileStream); Interlocked.Increment(ref _fileCount); } private bool IsWholeFileIgnored(string filePath, IEnumerable<IExtendedRuleException> ignoredRules) { var ignoredRulesEnum = ignoredRules.ToArray(); if (!ignoredRulesEnum.Any()) { return false; } var lineOneRuleIgnores = ignoredRulesEnum.OfType<GlobalRuleException>().Where(x => 1 == x.StartLine).ToArray(); if (!lineOneRuleIgnores.Any()) { return false; } var lineCount = 0; using (var reader = new StreamReader(GetFileContents(filePath))) { while (reader.ReadLine() != null) { lineCount++; } } return lineOneRuleIgnores.Any(x => x.EndLine == lineCount); } private void AddToProcessing(string filePath, Stream fileStream) { fileStreams.TryAdd(filePath, fileStream); } private void HandleProcessing(string filePath, Stream fileStream) { var ignoredRules = ruleExceptionFinder.GetIgnoredRuleList(fileStream).ToList(); if (IsWholeFileIgnored(filePath, ignoredRules)) { return; } ProcessRules(fileStream, ignoredRules, filePath); ProcessPlugins(fileStream, ignoredRules, filePath); } private void ProcessDirectory(string path) { var subDirectories = fileSystem.Directory.GetDirectories(path); Parallel.ForEach(subDirectories, (filePath) => { processPath(filePath); }); var fileEntries = fileSystem.Directory.GetFiles(path); Parallel.ForEach(fileEntries, (file) => { ProcessIfSqlFile(file); }); } private void ProcessIfSqlFile(string fileName) { if (fileSystem.Path.GetExtension(fileName).Equals(".sql", StringComparison.InvariantCultureIgnoreCase)) { ProcessFile(fileName); } } private void ProcessWildCard(string filePath) { var containsWildCard = filePath.Contains("*") || filePath.Contains("?"); if (!containsWildCard) { reporter.Report($"{filePath} is not a valid file path."); return; } var dirPath = fileSystem.Path.GetDirectoryName(filePath); if (string.IsNullOrEmpty(dirPath)) { dirPath = fileSystem.Directory.GetCurrentDirectory(); } if (!fileSystem.Directory.Exists(dirPath)) { reporter.Report($"Directory does not exist: {dirPath}"); return; } var searchPattern = fileSystem.Path.GetFileName(filePath); var files = fileSystem.Directory.EnumerateFiles(dirPath, searchPattern, SearchOption.TopDirectoryOnly); Parallel.ForEach(files, (file) => { ProcessIfSqlFile(file); }); } private void ProcessRules(Stream fileStream, IEnumerable<IRuleException> ignoredRules, string filePath) { ruleVisitor.VisitRules(filePath, ignoredRules, fileStream); } private void ProcessPlugins(Stream fileStream, IEnumerable<IRuleException> ignoredRules, string filePath) { TextReader textReader = new StreamReader(fileStream); pluginHandler.ActivatePlugins(new PluginContext(filePath, ignoredRules, textReader)); } private Stream GetFileContents(string filePath) { return fileSystem.File.OpenRead(filePath); } } }
using LinFx.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; namespace LinFx.Linq; [Service(ServiceLifetime.Singleton)] public class AsyncQueryableExecuter : IAsyncQueryableExecuter { protected IEnumerable<IAsyncQueryableProvider> Providers { get; } public AsyncQueryableExecuter(IEnumerable<IAsyncQueryableProvider> providers) { Providers = providers; } protected virtual IAsyncQueryableProvider FindProvider<T>(IQueryable<T> queryable) { return Providers.FirstOrDefault(p => p.CanExecute(queryable)); } public Task<bool> ContainsAsync<T>(IQueryable<T> queryable, T item, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.ContainsAsync(queryable, item, cancellationToken) : Task.FromResult(queryable.Contains(item)); } public Task<bool> AnyAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AnyAsync(queryable, cancellationToken) : Task.FromResult(queryable.Any()); } public Task<bool> AnyAsync<T>(IQueryable<T> queryable, Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AnyAsync(queryable, predicate, cancellationToken) : Task.FromResult(queryable.Any(predicate)); } public Task<bool> AllAsync<T>(IQueryable<T> queryable, Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AllAsync(queryable, predicate, cancellationToken) : Task.FromResult(queryable.All(predicate)); } public Task<int> CountAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.CountAsync(queryable, cancellationToken) : Task.FromResult(queryable.Count()); } public Task<int> CountAsync<T>(IQueryable<T> queryable, Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.CountAsync(queryable, predicate, cancellationToken) : Task.FromResult(queryable.Count(predicate)); } public Task<long> LongCountAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.LongCountAsync(queryable, cancellationToken) : Task.FromResult(queryable.LongCount()); } public Task<long> LongCountAsync<T>(IQueryable<T> queryable, Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.LongCountAsync(queryable, predicate, cancellationToken) : Task.FromResult(queryable.LongCount(predicate)); } public Task<T> FirstAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.FirstAsync(queryable, cancellationToken) : Task.FromResult(queryable.First()); } public Task<T> FirstAsync<T>(IQueryable<T> queryable, Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.FirstAsync(queryable, predicate, cancellationToken) : Task.FromResult(queryable.First(predicate)); } public Task<T> FirstOrDefaultAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.FirstOrDefaultAsync(queryable, cancellationToken) : Task.FromResult(queryable.FirstOrDefault()); } public Task<T> FirstOrDefaultAsync<T>(IQueryable<T> queryable, Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.FirstOrDefaultAsync(queryable, predicate, cancellationToken) : Task.FromResult(queryable.FirstOrDefault(predicate)); } public Task<T> LastAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.LastAsync(queryable, cancellationToken) : Task.FromResult(queryable.Last()); } public Task<T> LastAsync<T>(IQueryable<T> queryable, Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.LastAsync(queryable, predicate, cancellationToken) : Task.FromResult(queryable.Last(predicate)); } public Task<T> LastOrDefaultAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.LastOrDefaultAsync(queryable, cancellationToken) : Task.FromResult(queryable.LastOrDefault()); } public Task<T> LastOrDefaultAsync<T>(IQueryable<T> queryable, Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.LastOrDefaultAsync(queryable, predicate, cancellationToken) : Task.FromResult(queryable.LastOrDefault(predicate)); } public Task<T> SingleAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SingleAsync(queryable, cancellationToken) : Task.FromResult(queryable.Single()); } public Task<T> SingleAsync<T>(IQueryable<T> queryable, Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SingleAsync(queryable, predicate, cancellationToken) : Task.FromResult(queryable.Single(predicate)); } public Task<T> SingleOrDefaultAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SingleOrDefaultAsync(queryable, cancellationToken) : Task.FromResult(queryable.SingleOrDefault()); } public Task<T> SingleOrDefaultAsync<T>(IQueryable<T> queryable, Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SingleOrDefaultAsync(queryable, predicate, cancellationToken) : Task.FromResult(queryable.SingleOrDefault(predicate)); } public Task<T> MinAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.MinAsync(queryable, cancellationToken) : Task.FromResult(queryable.Min()); } public Task<TResult> MinAsync<T, TResult>(IQueryable<T> queryable, Expression<Func<T, TResult>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.MinAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Min(selector)); } public Task<T> MaxAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.MaxAsync(queryable, cancellationToken) : Task.FromResult(queryable.Max()); } public Task<TResult> MaxAsync<T, TResult>(IQueryable<T> queryable, Expression<Func<T, TResult>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.MaxAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Max(selector)); } public Task<decimal> SumAsync(IQueryable<decimal> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, cancellationToken) : Task.FromResult(queryable.Sum()); } public Task<decimal?> SumAsync(IQueryable<decimal?> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, cancellationToken) : Task.FromResult(queryable.Sum()); } public Task<decimal> SumAsync<T>(IQueryable<T> queryable, Expression<Func<T, decimal>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Sum(selector)); } public Task<decimal?> SumAsync<T>(IQueryable<T> queryable, Expression<Func<T, decimal?>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Sum(selector)); } public Task<int> SumAsync(IQueryable<int> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, cancellationToken) : Task.FromResult(queryable.Sum()); } public Task<int?> SumAsync(IQueryable<int?> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, cancellationToken) : Task.FromResult(queryable.Sum()); } public Task<int> SumAsync<T>(IQueryable<T> queryable, Expression<Func<T, int>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Sum(selector)); } public Task<int?> SumAsync<T>(IQueryable<T> queryable, Expression<Func<T, int?>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Sum(selector)); } public Task<long> SumAsync(IQueryable<long> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, cancellationToken) : Task.FromResult(queryable.Sum()); } public Task<long?> SumAsync(IQueryable<long?> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, cancellationToken) : Task.FromResult(queryable.Sum()); } public Task<long> SumAsync<T>(IQueryable<T> queryable, Expression<Func<T, long>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Sum(selector)); } public Task<long?> SumAsync<T>(IQueryable<T> queryable, Expression<Func<T, long?>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Sum(selector)); } public Task<double> SumAsync(IQueryable<double> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, cancellationToken) : Task.FromResult(queryable.Sum()); } public Task<double?> SumAsync(IQueryable<double?> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, cancellationToken) : Task.FromResult(queryable.Sum()); } public Task<double> SumAsync<T>(IQueryable<T> queryable, Expression<Func<T, double>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Sum(selector)); } public Task<double?> SumAsync<T>(IQueryable<T> queryable, Expression<Func<T, double?>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Sum(selector)); } public Task<float> SumAsync(IQueryable<float> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, cancellationToken) : Task.FromResult(queryable.Sum()); } public Task<float?> SumAsync(IQueryable<float?> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, cancellationToken) : Task.FromResult(queryable.Sum()); } public Task<float> SumAsync<T>(IQueryable<T> queryable, Expression<Func<T, float>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Sum(selector)); } public Task<float?> SumAsync<T>(IQueryable<T> queryable, Expression<Func<T, float?>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.SumAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Sum(selector)); } public Task<decimal> AverageAsync(IQueryable<decimal> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, cancellationToken) : Task.FromResult(queryable.Average()); } public Task<decimal?> AverageAsync(IQueryable<decimal?> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, cancellationToken) : Task.FromResult(queryable.Average()); } public Task<decimal> AverageAsync<T>(IQueryable<T> queryable, Expression<Func<T, decimal>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Average(selector)); } public Task<decimal?> AverageAsync<T>(IQueryable<T> queryable, Expression<Func<T, decimal?>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Average(selector)); } public Task<double> AverageAsync(IQueryable<int> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, cancellationToken) : Task.FromResult(queryable.Average()); } public Task<double?> AverageAsync(IQueryable<int?> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, cancellationToken) : Task.FromResult(queryable.Average()); } public Task<double> AverageAsync<T>(IQueryable<T> queryable, Expression<Func<T, int>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Average(selector)); } public Task<double?> AverageAsync<T>(IQueryable<T> queryable, Expression<Func<T, int?>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Average(selector)); } public Task<double> AverageAsync(IQueryable<long> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, cancellationToken) : Task.FromResult(queryable.Average()); } public Task<double?> AverageAsync(IQueryable<long?> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, cancellationToken) : Task.FromResult(queryable.Average()); } public Task<double> AverageAsync<T>(IQueryable<T> queryable, Expression<Func<T, long>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Average(selector)); } public Task<double?> AverageAsync<T>(IQueryable<T> queryable, Expression<Func<T, long?>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Average(selector)); } public Task<double> AverageAsync(IQueryable<double> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, cancellationToken) : Task.FromResult(queryable.Average()); } public Task<double?> AverageAsync(IQueryable<double?> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, cancellationToken) : Task.FromResult(queryable.Average()); } public Task<double> AverageAsync<T>(IQueryable<T> queryable, Expression<Func<T, double>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Average(selector)); } public Task<double?> AverageAsync<T>(IQueryable<T> queryable, Expression<Func<T, double?>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Average(selector)); } public Task<float> AverageAsync(IQueryable<float> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, cancellationToken) : Task.FromResult(queryable.Average()); } public Task<float?> AverageAsync(IQueryable<float?> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, cancellationToken) : Task.FromResult(queryable.Average()); } public Task<float> AverageAsync<T>(IQueryable<T> queryable, Expression<Func<T, float>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Average(selector)); } public Task<float?> AverageAsync<T>(IQueryable<T> queryable, Expression<Func<T, float?>> selector, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.AverageAsync(queryable, selector, cancellationToken) : Task.FromResult(queryable.Average(selector)); } public Task<List<T>> ToListAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.ToListAsync(queryable, cancellationToken) : Task.FromResult(queryable.ToList()); } public Task<T[]> ToArrayAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { var provider = FindProvider(queryable); return provider != null ? provider.ToArrayAsync(queryable, cancellationToken) : Task.FromResult(queryable.ToArray()); } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Holds the patch between two trees. /// <para>The individual patches for each file can be accessed through the indexer of this class.</para> /// <para>Building a patch is an expensive operation. If you only need to know which files have been added, /// deleted, modified, ..., then consider using a simpler <see cref="TreeChanges"/>.</para> /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Patch : IEnumerable<PatchEntryChanges>, IDiffResult { private readonly StringBuilder fullPatchBuilder = new StringBuilder(); private readonly IDictionary<FilePath, PatchEntryChanges> changes = new Dictionary<FilePath, PatchEntryChanges>(); private int linesAdded; private int linesDeleted; /// <summary> /// Needed for mocking purposes. /// </summary> protected Patch() { } internal unsafe Patch(DiffHandle diff) { using (diff) { int count = Proxy.git_diff_num_deltas(diff); for (int i = 0; i < count; i++) { using (var patch = Proxy.git_patch_from_diff(diff, i)) { var delta = Proxy.git_diff_get_delta(diff, i); AddFileChange(delta); Proxy.git_patch_print(patch, PrintCallBack); } } } } private unsafe void AddFileChange(git_diff_delta* delta) { var treeEntryChanges = new TreeEntryChanges(delta); changes.Add(treeEntryChanges.Path, new PatchEntryChanges(delta->flags.HasFlag(GitDiffFlags.GIT_DIFF_FLAG_BINARY), treeEntryChanges)); } private unsafe int PrintCallBack(git_diff_delta* delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload) { string patchPart = LaxUtf8Marshaler.FromNative(line.content, (int)line.contentLen); // Deleted files mean no "new file" path var pathPtr = delta->new_file.Path != null ? delta->new_file.Path : delta->old_file.Path; var filePath = LaxFilePathMarshaler.FromNative(pathPtr); PatchEntryChanges currentChange = this[filePath]; string prefix = string.Empty; switch (line.lineOrigin) { case GitDiffLineOrigin.GIT_DIFF_LINE_CONTEXT: prefix = " "; break; case GitDiffLineOrigin.GIT_DIFF_LINE_ADDITION: linesAdded++; currentChange.LinesAdded++; currentChange.AddedLines.Add(new Line(line.NewLineNo, patchPart)); prefix = "+"; break; case GitDiffLineOrigin.GIT_DIFF_LINE_DELETION: linesDeleted++; currentChange.LinesDeleted++; currentChange.DeletedLines.Add(new Line(line.OldLineNo, patchPart)); prefix = "-"; break; } string formattedOutput = string.Concat(prefix, patchPart); fullPatchBuilder.Append(formattedOutput); currentChange.AppendToPatch(formattedOutput); return 0; } #region IEnumerable<PatchEntryChanges> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the collection.</returns> public virtual IEnumerator<PatchEntryChanges> GetEnumerator() { return changes.Values.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion /// <summary> /// Gets the <see cref="ContentChanges"/> corresponding to the specified <paramref name="path"/>. /// </summary> public virtual PatchEntryChanges this[string path] { get { return this[(FilePath)path]; } } private PatchEntryChanges this[FilePath path] { get { PatchEntryChanges entryChanges; if (changes.TryGetValue(path, out entryChanges)) { return entryChanges; } return null; } } /// <summary> /// The total number of lines added in this diff. /// </summary> public virtual int LinesAdded { get { return linesAdded; } } /// <summary> /// The total number of lines deleted in this diff. /// </summary> public virtual int LinesDeleted { get { return linesDeleted; } } /// <summary> /// The full patch file of this diff. /// </summary> public virtual string Content { get { return fullPatchBuilder.ToString(); } } /// <summary> /// Implicit operator for string conversion. /// </summary> /// <param name="patch"><see cref="Patch"/>.</param> /// <returns>The patch content as string.</returns> public static implicit operator string(Patch patch) { return patch.fullPatchBuilder.ToString(); } private string DebuggerDisplay { get { return string.Format(CultureInfo.InvariantCulture, "+{0} -{1}", linesAdded, linesDeleted); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { // This doesn't do anything yet because it loads everything // eagerly and disposes of the diff handle in the constructor. } } }
using Fody; using Xunit; public class TypeNameParserTests { [Fact] public void Simple() { var parsedTypeName = TypeNameParser.Parse("a"); Assert.Equal("a", parsedTypeName.TypeName); Assert.Null(parsedTypeName.Assembly); Assert.Null(parsedTypeName.GenericParameters); } [Fact] public void SimpleWithSpecialChars() { var parsedTypeName = TypeNameParser.Parse(@"\<\>\|\,\\\ "); Assert.Equal(@"<>|,\ ", parsedTypeName.TypeName); Assert.Null(parsedTypeName.Assembly); Assert.Null(parsedTypeName.GenericParameters); } [Fact] public void SimpleIgnoresWhiteSpace() { var parsedTypeName = TypeNameParser.Parse(" \ta\r\n"); Assert.Equal("a", parsedTypeName.TypeName); Assert.Null(parsedTypeName.Assembly); Assert.Null(parsedTypeName.GenericParameters); } [Fact] public void Generic() { var parsedTypeName = TypeNameParser.Parse("a<b|c>"); Assert.Equal("a", parsedTypeName.TypeName); Assert.Null(parsedTypeName.Assembly); var parameters = parsedTypeName.GenericParameters; Assert.NotNull(parameters); Assert.NotEmpty(parameters); Assert.Equal(1, parameters.Count); Assert.Equal("b", parameters[0].Assembly); Assert.Equal("c", parameters[0].TypeName); Assert.Null(parameters[0].GenericParameters); } [Fact] public void MultipleGeneric() { var parsedTypeName = TypeNameParser.Parse("a<b|c,d|e>"); Assert.Equal("a", parsedTypeName.TypeName); Assert.Null(parsedTypeName.Assembly); var parameters = parsedTypeName.GenericParameters; Assert.NotNull(parameters); Assert.NotEmpty(parameters); Assert.Equal(2, parameters.Count); Assert.Equal("b", parameters[0].Assembly); Assert.Equal("c", parameters[0].TypeName); Assert.Null(parameters[0].GenericParameters); Assert.Equal("d", parameters[1].Assembly); Assert.Equal("e", parameters[1].TypeName); Assert.Null(parameters[1].GenericParameters); } [Fact] public void TwoLevelsDeep() { var parsedTypeName = TypeNameParser.Parse("a<b|c<d|e>>"); Assert.Equal("a", parsedTypeName.TypeName); Assert.Null(parsedTypeName.Assembly); var parameters = parsedTypeName.GenericParameters; Assert.NotNull(parameters); Assert.NotEmpty(parameters); Assert.Equal(1, parameters.Count); Assert.Equal("b", parameters[0].Assembly); Assert.Equal("c", parameters[0].TypeName); Assert.NotNull(parameters[0].GenericParameters); Assert.NotEmpty(parameters[0].GenericParameters); Assert.Equal(1, parameters[0].GenericParameters.Count); Assert.Equal("d", parameters[0].GenericParameters[0].Assembly); Assert.Equal("e", parameters[0].GenericParameters[0].TypeName); Assert.Null(parameters[0].GenericParameters[0].GenericParameters); } [Fact] public void DoubleGeneric() { var parsedTypeName = TypeNameParser.Parse("a<b|c<d|e>,f|g>"); Assert.Equal("a", parsedTypeName.TypeName); Assert.Null(parsedTypeName.Assembly); var parameters = parsedTypeName.GenericParameters; Assert.NotNull(parameters); Assert.NotEmpty(parameters); Assert.Equal(2, parameters.Count); Assert.Equal("b", parameters[0].Assembly); Assert.Equal("c", parameters[0].TypeName); Assert.NotNull(parameters[0].GenericParameters); Assert.NotEmpty(parameters[0].GenericParameters); Assert.Equal(1, parameters[0].GenericParameters.Count); Assert.Equal("d", parameters[0].GenericParameters[0].Assembly); Assert.Equal("e", parameters[0].GenericParameters[0].TypeName); Assert.Null(parameters[0].GenericParameters[0].GenericParameters); Assert.Equal("f", parameters[1].Assembly); Assert.Equal("g", parameters[1].TypeName); Assert.Null(parameters[1].GenericParameters); } [Theory] [InlineData("<")] [InlineData("a<<")] [InlineData("a<b|<")] [InlineData("a<b|c,<")] public void GenericStartWithoutTypeName(string typeName) { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse(typeName)); Assert.Equal("Expected a name, got <", exception.Message); } [Theory] [InlineData(">")] [InlineData("a<>")] [InlineData("a<b|>")] [InlineData("a<b|c,>")] public void GenericEndWithoutTypeName(string typeName) { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse(typeName)); Assert.Equal("Expected a name, got >", exception.Message); } [Theory] [InlineData("|")] [InlineData("a<|")] [InlineData("a<b||")] [InlineData("a<b|c,|")] public void AssemblySeparatorWithoutTypeName(string typeName) { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse(typeName)); Assert.Equal("Expected a name, got |", exception.Message); } [Theory] [InlineData(",")] [InlineData("a<,")] [InlineData("a<b|,")] [InlineData("a<b|c,,")] public void GenericParamSeparatorWithoutTypeName(string typeName) { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse(typeName)); Assert.Equal("Expected a name, got ,", exception.Message); } [Fact] public void UnrecognizedEscapeSequence() { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse("\\a")); Assert.Equal("Unrecognized escape sequence '\\a'", exception.Message); } [Theory] [InlineData("")] [InlineData("a<")] [InlineData("a<b|")] public void EmptyTypeName(string typeName) { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse(typeName)); Assert.Equal("Expected a name, got <end of type>", exception.Message); } [Fact] public void UnbalancedTypeSpec_AssemblyName() { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse("a<b")); Assert.Equal("Expected assembly name separator, got <end of type>", exception.Message); } [Fact] public void UnbalancedTypeSpec_TypeName() { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse("a<b|c")); Assert.Equal("Unbalanced type specification, are you missing a >?", exception.Message); } [Theory] [InlineData("a|b")] [InlineData("a<b|c>|")] [InlineData("a<b|c<d|e>|")] public void UnexpectedAssemblyNameSeparator(string typeName) { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse(typeName)); Assert.Equal("Unexpected assembly name separator", exception.Message); } [Fact] public void GenericTypeMissingAssemblyNameSeparator_UnexpectedGenericTypeStart() { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse("a<b<")); Assert.Equal("Expected assembly name separator, got <", exception.Message); } [Fact] public void GenericTypeMissingAssemblyNameSeparator_UnexpectedGenericTypeEnd() { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse("a<b>")); Assert.Equal("Expected assembly name separator, got >", exception.Message); } [Fact] public void GenericTypeMissingAssemblyNameSeparator_UnexpectedGenericTypeSeparator() { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse("a<b,")); Assert.Equal("Expected assembly name separator, got ,", exception.Message); } [Theory] [InlineData("a<b|c>d")] [InlineData("a<b|c<d|e>f")] public void UnexpectedNameToken(string typeName) { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse(typeName)); Assert.Equal("Unexpected name token", exception.Message); } [Theory] [InlineData("a<b|c>,")] [InlineData("a<b|c<d|e>>,")] public void UnexpectedGenericTypeSeparator(string typeName) { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse(typeName)); Assert.Equal("Unexpected generic param separator", exception.Message); } [Theory] [InlineData("a<b|c>>")] [InlineData("a<b|c<d|e>>>")] public void UnexpectedGenericTypeEnd(string typeName) { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse(typeName)); Assert.Equal("Unexpected generic type end", exception.Message); } [Theory] [InlineData("a<b|c><")] [InlineData("a<b|c<d|e><")] public void UnexpectedGenericTypeStart(string typeName) { var exception = Assert.Throws<WeavingException>(() => TypeNameParser.Parse(typeName)); Assert.Equal("Unexpected generic type start", exception.Message); } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.NotificationHubs; using Microsoft.Azure.Management.NotificationHubs.Models; namespace Microsoft.Azure.Management.NotificationHubs { /// <summary> /// .Net client wrapper for the REST API for Azure NotificationHub Service /// </summary> public static partial class NotificationHubOperationsExtensions { /// <summary> /// Checks the availability of the given notificationHub in a /// namespace. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='parameters'> /// Required. The notificationHub name. /// </param> /// <returns> /// Response of the Check NameAvailability operation. /// </returns> public static CheckAvailabilityResponse CheckAvailability(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, CheckAvailabilityParameters parameters) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).CheckAvailabilityAsync(resourceGroupName, namespaceName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks the availability of the given notificationHub in a /// namespace. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='parameters'> /// Required. The notificationHub name. /// </param> /// <returns> /// Response of the Check NameAvailability operation. /// </returns> public static Task<CheckAvailabilityResponse> CheckAvailabilityAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, CheckAvailabilityParameters parameters) { return operations.CheckAvailabilityAsync(resourceGroupName, namespaceName, parameters, CancellationToken.None); } /// <summary> /// Creates a new NotificationHub in a namespace. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create a Namespace Resource. /// </param> /// <returns> /// Response of the CreateOrUpdate operation on the NotificationHub /// </returns> public static NotificationHubCreateOrUpdateResponse Create(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, NotificationHubCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).CreateAsync(resourceGroupName, namespaceName, notificationHubName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new NotificationHub in a namespace. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create a Namespace Resource. /// </param> /// <returns> /// Response of the CreateOrUpdate operation on the NotificationHub /// </returns> public static Task<NotificationHubCreateOrUpdateResponse> CreateAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, NotificationHubCreateOrUpdateParameters parameters) { return operations.CreateAsync(resourceGroupName, namespaceName, notificationHubName, parameters, CancellationToken.None); } /// <summary> /// The create NotificationHub authorization rule operation creates an /// authorization rule for a NotificationHub /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Required. The namespace authorizationRuleName name. /// </param> /// <param name='parameters'> /// Required. The shared access authorization rule. /// </param> /// <returns> /// Response of the CreateOrUpdate operation on the AuthorizationRules /// </returns> public static SharedAccessAuthorizationRuleCreateOrUpdateResponse CreateOrUpdateAuthorizationRule(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The create NotificationHub authorization rule operation creates an /// authorization rule for a NotificationHub /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Required. The namespace authorizationRuleName name. /// </param> /// <param name='parameters'> /// Required. The shared access authorization rule. /// </param> /// <returns> /// Response of the CreateOrUpdate operation on the AuthorizationRules /// </returns> public static Task<SharedAccessAuthorizationRuleCreateOrUpdateResponse> CreateOrUpdateAuthorizationRuleAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, parameters, CancellationToken.None); } /// <summary> /// Deletes a notification hub associated with a namespace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).DeleteAsync(resourceGroupName, namespaceName, notificationHubName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a notification hub associated with a namespace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName) { return operations.DeleteAsync(resourceGroupName, namespaceName, notificationHubName, CancellationToken.None); } /// <summary> /// The delete a notificationHub authorization rule operation /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Required. The namespace authorizationRuleName name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse DeleteAuthorizationRule(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, notificationHubName, authorizationRuleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The delete a notificationHub authorization rule operation /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Required. The namespace authorizationRuleName name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAuthorizationRuleAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName) { return operations.DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, CancellationToken.None); } /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <returns> /// The response of the Get NotificationHub operation. /// </returns> public static NotificationHubGetResponse Get(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).GetAsync(resourceGroupName, namespaceName, notificationHubName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <returns> /// The response of the Get NotificationHub operation. /// </returns> public static Task<NotificationHubGetResponse> GetAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName) { return operations.GetAsync(resourceGroupName, namespaceName, notificationHubName, CancellationToken.None); } /// <summary> /// The get authorization rule operation gets an authorization rule for /// a NotificationHub by name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace to get the authorization rule for. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Required. The entity name to get the authorization rule for. /// </param> /// <returns> /// The response of the Get Namespace operation. /// </returns> public static SharedAccessAuthorizationRuleGetResponse GetAuthorizationRule(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).GetAuthorizationRuleAsync(resourceGroupName, namespaceName, notificationHubName, authorizationRuleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The get authorization rule operation gets an authorization rule for /// a NotificationHub by name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace to get the authorization rule for. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Required. The entity name to get the authorization rule for. /// </param> /// <returns> /// The response of the Get Namespace operation. /// </returns> public static Task<SharedAccessAuthorizationRuleGetResponse> GetAuthorizationRuleAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName) { return operations.GetAuthorizationRuleAsync(resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, CancellationToken.None); } /// <summary> /// Lists the PNS Credentials associated with a notification hub . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <returns> /// The response of the Get NotificationHub operation. /// </returns> public static NotificationHubGetResponse GetPnsCredentials(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).GetPnsCredentialsAsync(resourceGroupName, namespaceName, notificationHubName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the PNS Credentials associated with a notification hub . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <returns> /// The response of the Get NotificationHub operation. /// </returns> public static Task<NotificationHubGetResponse> GetPnsCredentialsAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName) { return operations.GetPnsCredentialsAsync(resourceGroupName, namespaceName, notificationHubName, CancellationToken.None); } /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <returns> /// The response of the List NotificationHub operation. /// </returns> public static NotificationHubListResponse List(this INotificationHubOperations operations, string resourceGroupName, string namespaceName) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).ListAsync(resourceGroupName, namespaceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <returns> /// The response of the List NotificationHub operation. /// </returns> public static Task<NotificationHubListResponse> ListAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName) { return operations.ListAsync(resourceGroupName, namespaceName, CancellationToken.None); } /// <summary> /// The get authorization rules operation gets the authorization rules /// for a NotificationHub. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The NotificationHub to get the authorization rule for. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <returns> /// The response of the List Namespace operation. /// </returns> public static SharedAccessAuthorizationRuleListResponse ListAuthorizationRules(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).ListAuthorizationRulesAsync(resourceGroupName, namespaceName, notificationHubName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The get authorization rules operation gets the authorization rules /// for a NotificationHub. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The NotificationHub to get the authorization rule for. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <returns> /// The response of the List Namespace operation. /// </returns> public static Task<SharedAccessAuthorizationRuleListResponse> ListAuthorizationRulesAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName) { return operations.ListAuthorizationRulesAsync(resourceGroupName, namespaceName, notificationHubName, CancellationToken.None); } /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the /// NotificationHub (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Required. The connection string of the NotificationHub for the /// specified authorizationRule. /// </param> /// <returns> /// Namespace/NotificationHub Connection String /// </returns> public static ResourceListKeys ListKeys(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).ListKeysAsync(resourceGroupName, namespaceName, notificationHubName, authorizationRuleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the /// NotificationHub (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Required. The connection string of the NotificationHub for the /// specified authorizationRule. /// </param> /// <returns> /// Namespace/NotificationHub Connection String /// </returns> public static Task<ResourceListKeys> ListKeysAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName) { return operations.ListKeysAsync(resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, CancellationToken.None); } /// <summary> /// Creates a new NotificationHub in a namespace. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create a Namespace Resource. /// </param> /// <returns> /// Response of the CreateOrUpdate operation on the NotificationHub /// </returns> public static NotificationHubCreateOrUpdateResponse Update(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, NotificationHubCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((INotificationHubOperations)s).UpdateAsync(resourceGroupName, namespaceName, notificationHubName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new NotificationHub in a namespace. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INotificationHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='notificationHubName'> /// Required. The notification hub name. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create a Namespace Resource. /// </param> /// <returns> /// Response of the CreateOrUpdate operation on the NotificationHub /// </returns> public static Task<NotificationHubCreateOrUpdateResponse> UpdateAsync(this INotificationHubOperations operations, string resourceGroupName, string namespaceName, string notificationHubName, NotificationHubCreateOrUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, namespaceName, notificationHubName, parameters, CancellationToken.None); } } }
using Revolver.Core.Commands.Parameters; using Sitecore.Collections; using Sitecore.Data; using Sitecore.Data.Fields; using Sitecore.Data.Items; using Sitecore.StringExtensions; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Text.RegularExpressions; namespace Revolver.Core.Commands { [Command("find")] public class FindItems : BaseCommand { protected const string WILDCARD_FIELDNAME = "*"; protected Regex _fieldRegex = null; protected Regex _attributeRegex = null; [FlagParameter("r")] [Description("Recursive. Search all descendants as well.")] [Optional] public bool Recursive { get; set; } [FlagParameter("ns")] [Description("No statistics. Don't show how many items were found.")] [Optional] public bool NoStatistics { get; set; } [FlagParameter("so")] [Description("Statistics only. Only show the count of items that were found. No need to supply a command when using this flag.")] [Optional] public bool StatisticsOnly { get; set; } [FlagParameter("nsv")] [Description("Retrieve the field value directly from the item, ignoring standard values.")] [Optional] public bool NoStandardValues { get; set; } [NamedParameter("i", "idlist")] [Description("Pipe seperated list of item IDs to find.")] [Optional] public string Ids { get; set; } [NamedParameter("t", "template")] [Description("The template to match items on. Can either be an ID or a path.")] [Optional] public string Template { get; set; } [NamedParameter("b", "branch")] [Description("The branch to match items on. Can either be an ID or a name.")] [Optional] public string Branch { get; set; } [NamedParameter("f", "field value", 2)] [Description("The field to match items on. Use " + WILDCARD_FIELDNAME + " to search in all fields")] [Optional] [TypeConverter(typeof(KeyValueConverter))] public KeyValuePair<string, string> FindByField { get; set; } [FlagParameter("fc")] [Description("Perform case sensitive field regular expression match.")] [Optional] public bool FindByFieldCaseSensitive { get; set; } [NamedParameter("e", "expression")] [Description("A comparative expression to evaluate.")] [Optional] public string Expression { get; set; } [NamedParameter("a", "attribute value", 2)] [Description("The attribute to match items on.")] [Optional] [TypeConverter(typeof(KeyValueConverter))] public KeyValuePair<string, string> FindByAttribute { get; set; } [FlagParameter("ac")] [Description("Perform case sensitive attribute regular expression match.")] [Optional] public bool FindByAttributeCaseSensitive { get; set; } [NumberedParameter(0, "command")] [Description("Required when -so flag is not used. The command to execute against each matching item.")] [Optional] [NoSubstitutionAttribute] public string Command { get; set; } [NumberedParameter(1, "path")] [Description("The path of the item to execute this command from. If not specified the current item is used.")] [Optional] public string Path { get; set; } public FindItems() { Recursive = false; NoStatistics = false; StatisticsOnly = false; NoStandardValues = false; Ids = string.Empty; Template = string.Empty; Branch = string.Empty; FindByFieldCaseSensitive = false; Expression = string.Empty; FindByAttributeCaseSensitive = false; Command = string.Empty; Path = string.Empty; } public override CommandResult Run() { if (string.IsNullOrEmpty(Command) && !StatisticsOnly) return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("command") + " or -so flag."); if (!string.IsNullOrEmpty(Command) && StatisticsOnly) return new CommandResult(CommandStatus.Failure, "Cannot specify a command when returning statistics only."); // Make sure we have the right parameters filled in if (string.IsNullOrEmpty(FindByField.Key) ^ string.IsNullOrEmpty(FindByField.Value)) return new CommandResult(CommandStatus.Failure, "Field name or value is missing."); // Reset regexs so they get rebuilt if required, based on current parameters _fieldRegex = null; _attributeRegex = null; // Convert template and branch arguments to IDs var templateId = ID.Null; if(!string.IsNullOrEmpty(Template)) { var templateItem = Context.CurrentDatabase.Templates[Template]; if (templateItem == null) return new CommandResult(CommandStatus.Failure, "Faild to find template '{0}'".FormatWith(Template)); templateId = templateItem.ID; } var branchId = ID.Null; if (!string.IsNullOrEmpty(Branch)) { var branchItem = Context.CurrentDatabase.Branches[Branch]; if (branchItem == null) return new CommandResult(CommandStatus.Failure, "Faild to find branch '{0}'".FormatWith(Branch)); branchId = branchItem.ID; } var output = new StringBuilder(); using (var cs = new ContextSwitcher(Context, Path)) { if (cs.Result.Status != CommandStatus.Success) return cs.Result; var items = new ItemCollection(); if (!string.IsNullOrEmpty(Ids)) { foreach (var id in ID.ParseArray(Ids)) { var item = Context.CurrentDatabase.GetItem(id); if (item != null) { if (IncludeItem(item, templateId, branchId)) items.Add(item); } else return new CommandResult(CommandStatus.Failure, "Failed to find item with id '{0}'".FormatWith(id)); } } else ProcessItem(items, Context.CurrentItem, templateId, branchId, true); // Return number of matched items if only returning stats if (StatisticsOnly) output.Append(items.Count); else { // Execute command against each found item var limit = items.Count; for (var i = 0; i < limit; i++) { var item = items[i]; using (new ContextSwitcher(Context, item.ID.ToString())) { var result = Context.ExecuteCommand(Command, Formatter); // Should we check the status? Maybe abort if stoponerror is set? output.Append(result); } if(i < limit - 1) Formatter.PrintLine(string.Empty, output); } if (!NoStatistics) { Formatter.PrintLine(string.Empty, output); Formatter.PrintLine(string.Empty, output); output.Append(string.Format("Found {0} {1}", items.Count, (items.Count == 1 ? "item" : "items"))); } } } return new CommandResult(CommandStatus.Success, output.ToString()); } /// <summary> /// Adds items to the collection based on the search criteria /// </summary> /// <param name="items">The collection to add items to</param> /// <param name="current">The current item</param> /// <param name="templateId">Template filter</param> /// <param name="branchId">Branch filter</param> /// <param name="start">Indicates if the item is the start item</param> protected virtual void ProcessItem(ItemCollection items, Item current, ID templateId, ID branchId, bool start) { if (!start) { var include = IncludeItem(current, templateId, branchId); if (include) items.Add(current); } if (Recursive || start) { // process each child ChildList children = current.GetChildren(); for (int i = 0; i < children.Count; i++) { ProcessItem(items, children[i], templateId, branchId, false); } } } /// <summary> /// Checks to see if an item passes the filters /// </summary> /// <param name="item">The item to check</param> /// <param name="templateId">Template filter</param> /// <param name="branchId">Branch filter</param> /// <returns></returns> protected virtual bool IncludeItem(Item item, ID templateId, ID branchId) { var include = FilterByTemplate(item, templateId); if (include) include = FilterByBranch(item, branchId); if (include) include = FilterByField(item); if (include) include = FilterByAttribute(item); if (include) include = FilterByExpression(item); return include; } protected virtual bool FilterByTemplate(Item item, ID templateId) { if (templateId == ID.Null) return true; return item.TemplateID == templateId; } protected virtual bool FilterByBranch(Item item, ID branchId) { if (branchId == ID.Null) return true; return item.BranchId == branchId; } protected virtual bool FilterByField(Item item) { if (string.IsNullOrEmpty(FindByField.Key) || string.IsNullOrEmpty(FindByField.Value)) return true; if (item.Fields[FindByField.Key] == null && FindByField.Key != WILDCARD_FIELDNAME) return false; if (_fieldRegex == null) { var options = RegexOptions.Compiled; if (!FindByFieldCaseSensitive) options |= RegexOptions.IgnoreCase; _fieldRegex = new Regex(FindByField.Value, options); } if (FindByField.Key == WILDCARD_FIELDNAME) { foreach (Field singleField in item.Fields) { if (_fieldRegex.IsMatch(singleField.GetValue(!NoStandardValues))) { return true; } } return false; } return _fieldRegex.IsMatch(item.Fields[FindByField.Key].GetValue(!NoStandardValues)); } protected virtual bool FilterByAttribute(Item item) { if (string.IsNullOrEmpty(FindByAttribute.Key) || string.IsNullOrEmpty(FindByAttribute.Value)) return true; if (_attributeRegex == null) { var options = RegexOptions.Compiled; if (!FindByAttributeCaseSensitive) options |= RegexOptions.IgnoreCase; _attributeRegex = new Regex(FindByAttribute.Value, options); } var attrcmd = new GetAttributes(); attrcmd.Initialise(Context, Formatter); attrcmd.Attribute = FindByAttribute.Key; attrcmd.Path = item.ID.ToString(); var result = attrcmd.Run(); if (result.Status == CommandStatus.Success) { var output = result.Message; return _attributeRegex.IsMatch(output); } return false; } protected virtual bool FilterByExpression(Item item) { if (string.IsNullOrEmpty(Expression)) return true; var context = Context.Clone(); context.CurrentItem = item; return ExpressionParser.EvaluateExpression(context, Expression); } public override string Description() { return "Locate a set of items through content tree traversal and execute the given command against each item."; } public override void Help(HelpDetails details) { details.AddExample("-i {493B3A83-0FA7-4484-8FC9-4680991CF743} pwd"); details.AddExample("-i {493B3A83-0FA7-4484-8FC9-4680991CF743}|{543B3A83-0FA7-4484-8FC9-4680991CF797} pwd"); details.AddExample("-t {493B3A83-0FA7-4484-8FC9-4680991CF743} (sf title hi)"); details.AddExample("-t Document (sf title hi)"); details.AddExample("-b MyBranch (sf title hi)"); details.AddExample("-f title (a page for .*) (sf title hi)"); details.AddExample("-f * sitecore pwd"); details.AddExample("-f title (a page for .*) -fc (sf title hi)"); details.AddExample("-r -f title (a page for .*) (sf title hi) /sitecore/content/home"); details.AddExample("-t {493B3A83-0FA7-4484-8FC9-4680991CF743} -f title hi (sf title welcome)"); details.AddExample("-ns -e (@__created > 3/1/2007 as date) pwd"); details.AddExample("-so -e (@__created > 3/1/2007 as date)"); } } }
//#define ASTAR_POOL_DEBUG //@SHOWINEDITOR Enables debugging of path pooling. Will log warnings and info messages about paths not beeing pooled correctly. using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Pathfinding { /** Base class for all path types */ public abstract class Path { /** Data for the thread calculating this path */ public PathHandler pathHandler { get; private set; } /** Callback to call when the path is complete. * This is usually sent to the Seeker component which post processes the path and then calls a callback to the script which requested the path */ public OnPathDelegate callback; /** Immediate callback to call when the path is complete. * \warning This may be called from a separate thread. Usually you do not want to use this one. * * \see callback */ public OnPathDelegate immediateCallback; PathState state; System.Object stateLock = new object(); /** Current state of the path. * \see #CompleteState */ PathCompleteState pathCompleteState; /** Current state of the path */ public PathCompleteState CompleteState { get { return pathCompleteState; } protected set { pathCompleteState = value; } } /** If the path failed, this is true. * \see #errorLog */ public bool error { get { return CompleteState == PathCompleteState.Error; } } /** Additional info on what went wrong. * \see #error */ private string _errorLog = ""; /** Log messages with info about eventual errors. */ public string errorLog { get { return _errorLog; } } /** Holds the path as a Node array. All nodes the path traverses. * This might not be the same as all nodes the smoothed path traverses. */ public List<GraphNode> path; /** Holds the (perhaps post processed) path as a Vector3 list */ public List<Vector3> vectorPath; /** The max number of milliseconds per iteration (frame, in case of non-multithreading) */ protected float maxFrameTime; /** The node currently being processed */ protected PathNode currentR; /** The duration of this path in ms. How long it took to calculate the path */ public float duration; /** The number of frames/iterations this path has executed. * This is the number of frames when not using multithreading. * When using multithreading, this value is quite irrelevant */ public int searchIterations; /** Number of nodes this path has searched */ public int searchedNodes; /** When the call was made to start the pathfinding for this path */ public System.DateTime callTime { get; private set; } /** True if the path is currently pooled. * Do not set this value. Only read. It is used internally. * * \see PathPool * \version Was named 'recycled' in 3.7.5 and earlier. */ internal bool pooled; /** True if the path is currently recycled (i.e in the path pool). * Do not set this value. Only read. It is used internally. * * \deprecated Has been renamed to 'pooled' to use more widely underestood terminology */ [System.Obsolete("Has been renamed to 'pooled' to use more widely underestood terminology")] internal bool recycled { get { return pooled; } set { pooled = value; } } /** True if the Reset function has been called. * Used to alert users when they are doing something wrong. */ protected bool hasBeenReset; /** Constraint for how to search for nodes */ public NNConstraint nnConstraint = PathNNConstraint.Default; /** Internal linked list implementation. * \warning This is used internally by the system. You should never change this. */ internal Path next; /** Determines which heuristic to use */ public Heuristic heuristic; /** Scale of the heuristic values */ public float heuristicScale = 1F; /** ID of this path. Used to distinguish between different paths */ public ushort pathID { get; private set; } /** Target to use for H score calculation. Used alongside #hTarget. */ protected GraphNode hTargetNode; /** Target to use for H score calculations. \see Pathfinding.Node.H */ protected Int3 hTarget; /** Which graph tags are traversable. * This is a bitmask so -1 = all bits set = all tags traversable. * For example, to set bit 5 to true, you would do * \code myPath.enabledTags |= 1 << 5; \endcode * To set it to false, you would do * \code myPath.enabledTags &= ~(1 << 5); \endcode * * The Seeker has a popup field where you can set which tags to use. * \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath. * So you need to change the Seeker value via script, not set this value if you want to change it via script. * * \see CanTraverse */ public int enabledTags = -1; /** List of zeroes to use as default tag penalties */ static readonly int[] ZeroTagPenalties = new int[32]; /** The tag penalties that are actually used. * If manualTagPenalties is null, this will be ZeroTagPenalties * \see tagPenalties */ protected int[] internalTagPenalties; /** Tag penalties set by other scripts * \see tagPenalties */ protected int[] manualTagPenalties; /** Penalties for each tag. * Tag 0 which is the default tag, will have added a penalty of tagPenalties[0]. * These should only be positive values since the A* algorithm cannot handle negative penalties. * \note This array will never be null. If you try to set it to null or with a lenght which is not 32. It will be set to "new int[0]". * * \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath. * So you need to change the Seeker value via script, not set this value if you want to change it via script. * * \see Seeker.tagPenalties */ public int[] tagPenalties { get { return manualTagPenalties; } set { if (value == null || value.Length != 32) { manualTagPenalties = null; internalTagPenalties = ZeroTagPenalties; } else { manualTagPenalties = value; internalTagPenalties = value; } } } /** True for paths that want to search all nodes and not jump over nodes as optimizations. * This disables Jump Point Search when that is enabled to prevent e.g ConstantPath and FloodPath * to become completely useless. */ public virtual bool FloodingPath { get { return false; } } /** Total Length of the path. * Calculates the total length of the #vectorPath. * Cache this rather than call this function every time since it will calculate the length every time, not just return a cached value. * \returns Total length of #vectorPath, if #vectorPath is null positive infinity is returned. */ public float GetTotalLength () { if (vectorPath == null) return float.PositiveInfinity; float tot = 0; for (int i = 0; i < vectorPath.Count-1; i++) tot += Vector3.Distance(vectorPath[i], vectorPath[i+1]); return tot; } /** Waits until this path has been calculated and returned. * Allows for very easy scripting. * \code * //In an IEnumerator function * * Path p = Seeker.StartPath (transform.position, transform.position + Vector3.forward * 10); * yield return StartCoroutine (p.WaitForPath ()); * * //The path is calculated at this stage * \endcode * \note Do not confuse this with AstarPath.WaitForPath. This one will wait using yield until it has been calculated * while AstarPath.WaitForPath will halt all operations until the path has been calculated. * * \throws System.InvalidOperationException if the path is not started. Send the path to Seeker.StartPath or AstarPath.StartPath before calling this function. * * \see AstarPath.WaitForPath */ public IEnumerator WaitForPath () { if (GetState() == PathState.Created) throw new System.InvalidOperationException("This path has not been started yet"); while (GetState() != PathState.Returned) yield return null; } /** Estimated cost from the specified node to the target. * \see https://en.wikipedia.org/wiki/A*_search_algorithm */ public uint CalculateHScore (GraphNode node) { uint h; switch (heuristic) { case Heuristic.Euclidean: h = (uint)(((GetHTarget() - node.position).costMagnitude)*heuristicScale); return h; case Heuristic.Manhattan: Int3 p2 = node.position; h = (uint)((System.Math.Abs(hTarget.x-p2.x) + System.Math.Abs(hTarget.y-p2.y) + System.Math.Abs(hTarget.z-p2.z))*heuristicScale); return h; case Heuristic.DiagonalManhattan: Int3 p = GetHTarget() - node.position; p.x = System.Math.Abs(p.x); p.y = System.Math.Abs(p.y); p.z = System.Math.Abs(p.z); int diag = System.Math.Min(p.x, p.z); int diag2 = System.Math.Max(p.x, p.z); h = (uint)((((14*diag)/10) + (diag2-diag) + p.y) * heuristicScale); return h; } return 0U; } /** Returns penalty for the given tag. * \param tag A value between 0 (inclusive) and 32 (exclusive). */ public uint GetTagPenalty (int tag) { return (uint)internalTagPenalties[tag]; } public Int3 GetHTarget () { return hTarget; } /** Returns if the node can be traversed. * This per default equals to if the node is walkable and if the node's tag is included in #enabledTags */ public bool CanTraverse (GraphNode node) { unchecked { return node.Walkable && (enabledTags >> (int)node.Tag & 0x1) != 0; } } public uint GetTraversalCost (GraphNode node) { #if ASTAR_NO_TRAVERSAL_COST return 0; #else unchecked { return GetTagPenalty((int)node.Tag) + node.Penalty; } #endif } /** May be called by graph nodes to get a special cost for some connections. * Nodes may call it when PathNode.flag2 is set to true, for example mesh nodes, which have * a very large area can be marked on the start and end nodes, this method will be called * to get the actual cost for moving from the start position to its neighbours instead * of as would otherwise be the case, from the start node's position to its neighbours. * The position of a node and the actual start point on the node can vary quite a lot. * * The default behaviour of this method is to return the previous cost of the connection, * essentiall making no change at all. * * This method should return the same regardless of the order of a and b. * That is f(a,b) == f(b,a) should hold. * * \param a Moving from this node * \param b Moving to this node * \param currentCost The cost of moving between the nodes. Return this value if there is no meaningful special cost to return. */ public virtual uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost) { return currentCost; } /** Returns if this path is done calculating. * \returns If CompleteState is not PathCompleteState.NotCalculated. * * \note The path might not have been returned yet. * * \since Added in 3.0.8 * * \see Seeker.IsDone */ public bool IsDone () { return CompleteState != PathCompleteState.NotCalculated; } /** Threadsafe increment of the state */ public void AdvanceState (PathState s) { lock (stateLock) { state = (PathState)System.Math.Max((int)state, (int)s); } } /** Returns the state of the path in the pathfinding pipeline */ public PathState GetState () { return (PathState)state; } /** Appends \a msg to #errorLog and logs \a msg to the console. * Debug.Log call is only made if AstarPath.logPathResults is not equal to None and not equal to InGame. * Consider calling Error() along with this call. */ // Ugly Code Inc. wrote the below code :D // What it does is that it disables the LogError function if ASTAR_NO_LOGGING is enabled // since the DISABLED define will never be enabled // Ugly way of writing Conditional("!ASTAR_NO_LOGGING") public void LogError (string msg) { // Optimize for release builds if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) { _errorLog += msg; } if (AstarPath.active.logPathResults != PathLog.None && AstarPath.active.logPathResults != PathLog.InGame) { Debug.LogWarning(msg); } } /** Logs an error and calls Error(). * This is called only if something is very wrong or the user is doing something he/she really should not be doing. */ public void ForceLogError (string msg) { Error(); _errorLog += msg; Debug.LogError(msg); } /** Appends a message to the #errorLog. * Nothing is logged to the console. * * \note If AstarPath.logPathResults is PathLog.None and this is a standalone player, nothing will be logged as an optimization. */ public void Log (string msg) { // Optimize for release builds if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) { _errorLog += msg; } } /** Aborts the path because of an error. * Sets #error to true. * This function is called when an error has ocurred (e.g a valid path could not be found). * \see LogError */ public void Error () { CompleteState = PathCompleteState.Error; } /** Does some error checking. * Makes sure the user isn't using old code paths and that no major errors have been done. * * \throws An exception if any errors are found */ private void ErrorCheck () { if (!hasBeenReset) throw new System.Exception("The path has never been reset. Use pooling API or call Reset() after creating the path with the default constructor."); if (pooled) throw new System.Exception("The path is currently in a path pool. Are you sending the path for calculation twice?"); if (pathHandler == null) throw new System.Exception("Field pathHandler is not set. Please report this bug."); if (GetState() > PathState.Processing) throw new System.Exception("This path has already been processed. Do not request a path with the same path object twice."); } /** Called when the path enters the pool. * This method should release e.g pooled lists and other pooled resources * The base version of this method releases vectorPath and path lists. * Reset() will be called after this function, not before. * \warning Do not call this function manually. */ public virtual void OnEnterPool () { if (vectorPath != null) Pathfinding.Util.ListPool<Vector3>.Release(vectorPath); if (path != null) Pathfinding.Util.ListPool<GraphNode>.Release(path); vectorPath = null; path = null; immediateCallback = null; // Clear the callback to remove a potential memory leak // while the path is in the pool (which it could be for a long time). callback = null; } /** Reset all values to their default values. * * \note All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to * override this function, resetting ALL their variables to enable recycling of paths. * If this is not done, trying to use that path type for pooling might result in weird behaviour. * The best way is to reset to default values the variables declared in the extended path type and then * call this base function in inheriting types with base.Reset (). * * \warning This function should not be called manually. */ public virtual void Reset () { if (System.Object.ReferenceEquals(AstarPath.active, null)) throw new System.NullReferenceException("No AstarPath object found in the scene. " + "Make sure there is one or do not create paths in Awake"); hasBeenReset = true; state = (int)PathState.Created; releasedNotSilent = false; pathHandler = null; callback = null; immediateCallback = null; _errorLog = ""; pathCompleteState = PathCompleteState.NotCalculated; path = Pathfinding.Util.ListPool<GraphNode>.Claim(); vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim(); currentR = null; duration = 0; searchIterations = 0; searchedNodes = 0; //calltime nnConstraint = PathNNConstraint.Default; next = null; heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; enabledTags = -1; tagPenalties = null; callTime = System.DateTime.UtcNow; pathID = AstarPath.active.GetNextPathID(); hTarget = Int3.zero; hTargetNode = null; } protected bool HasExceededTime (int searchedNodes, long targetTime) { return System.DateTime.UtcNow.Ticks >= targetTime; } /** List of claims on this path with reference objects */ private List<System.Object> claimed = new List<System.Object>(); /** True if the path has been released with a non-silent call yet. * * \see Release * \see Claim */ private bool releasedNotSilent; /** Claim this path (pooling). * A claim on a path will ensure that it is not pooled. * If you are using a path, you will want to claim it when you first get it and then release it when you will not * use it anymore. When there are no claims on the path, it will be reset and put in a pool. * * This is essentially just reference counting. * * The object passed to this method is merely used as a way to more easily detect when pooling is not done correctly. * It can be any object, when used from a movement script you can just pass "this". This class will throw an exception * if you try to call Claim on the same path twice with the same object (which is usually not what you want) or * if you try to call Release with an object that has not been used in a Claim call for that path. * The object passed to the Claim method needs to be the same as the one you pass to this method. * * \see Release * \see Pool * \see \ref pooling */ public void Claim (System.Object o) { if (System.Object.ReferenceEquals(o, null)) throw new System.ArgumentNullException("o"); for (int i = 0; i < claimed.Count; i++) { // Need to use ReferenceEquals because it might be called from another thread if (System.Object.ReferenceEquals(claimed[i], o)) throw new System.ArgumentException("You have already claimed the path with that object ("+o+"). Are you claiming the path with the same object twice?"); } claimed.Add(o); } /** Releases the path silently (pooling). * \deprecated Use Release(o, true) instead */ [System.Obsolete("Use Release(o, true) instead")] public void ReleaseSilent (System.Object o) { Release(o, true); } /** Releases a path claim (pooling). * Removes the claim of the path by the specified object. * When the claim count reaches zero, the path will be pooled, all variables will be cleared and the path will be put in a pool to be used again. * This is great for memory since less allocations are made. * * If the silent parameter is true, this method will remove the claim by the specified object * but the path will not be pooled if the claim count reches zero unless a Release call (not silent) has been made earlier. * This is used by the internal pathfinding components such as Seeker and AstarPath so that they will not cause paths to be pooled. * This enables users to skip the claim/release calls if they want without the path being pooled by the Seeker or AstarPath and * thus causing strange bugs. * * \see Claim * \see PathPool */ public void Release (System.Object o, bool silent = false) { if (o == null) throw new System.ArgumentNullException("o"); for (int i = 0; i < claimed.Count; i++) { // Need to use ReferenceEquals because it might be called from another thread if (System.Object.ReferenceEquals(claimed[i], o)) { claimed.RemoveAt(i); if (!silent) { releasedNotSilent = true; } if (claimed.Count == 0 && releasedNotSilent) { PathPool.Pool(this); } return; } } if (claimed.Count == 0) { throw new System.ArgumentException("You are releasing a path which is not claimed at all (most likely it has been pooled already). " + "Are you releasing the path with the same object ("+o+") twice?" + "\nCheck out the documentation on path pooling for help."); } throw new System.ArgumentException("You are releasing a path which has not been claimed with this object ("+o+"). " + "Are you releasing the path with the same object twice?\n" + "Check out the documentation on path pooling for help."); } /** Traces the calculated path from the end node to the start. * This will build an array (#path) of the nodes this path will pass through and also set the #vectorPath array to the #path arrays positions. * Assumes the #vectorPath and #path are empty and not null (which will be the case for a correctly initialized path). */ protected virtual void Trace (PathNode from) { // Current node we are processing PathNode c = from; int count = 0; while (c != null) { c = c.parent; count++; if (count > 2048) { Debug.LogWarning("Infinite loop? >2048 node path. Remove this message if you really have that long paths (Path.cs, Trace method)"); break; } } // Ensure capacities for lists AstarProfiler.StartProfile("Check List Capacities"); if (path.Capacity < count) path.Capacity = count; if (vectorPath.Capacity < count) vectorPath.Capacity = count; AstarProfiler.EndProfile(); c = from; for (int i = 0; i < count; i++) { path.Add(c.node); c = c.parent; } // Reverse int half = count/2; for (int i = 0; i < half; i++) { var tmp = path[i]; path[i] = path[count-i-1]; path[count - i - 1] = tmp; } for (int i = 0; i < count; i++) { vectorPath.Add((Vector3)path[i].position); } } /** Writes text shared for all overrides of DebugString to the string builder. * \see DebugString */ protected void DebugStringPrefix (PathLog logMode, System.Text.StringBuilder text) { text.Append(error ? "Path Failed : " : "Path Completed : "); text.Append("Computation Time "); text.Append(duration.ToString(logMode == PathLog.Heavy ? "0.000 ms " : "0.00 ms ")); text.Append("Searched Nodes ").Append(searchedNodes); if (!error) { text.Append(" Path Length "); text.Append(path == null ? "Null" : path.Count.ToString()); if (logMode == PathLog.Heavy) { text.Append("\nSearch Iterations ").Append(searchIterations); } } } /** Writes text shared for all overrides of DebugString to the string builder. * \see DebugString */ protected void DebugStringSuffix (PathLog logMode, System.Text.StringBuilder text) { if (error) { text.Append("\nError: ").Append(errorLog); } if (logMode == PathLog.Heavy && !AstarPath.IsUsingMultithreading) { text.Append("\nCallback references "); if (callback != null) text.Append(callback.Target.GetType().FullName).AppendLine(); else text.AppendLine("NULL"); } text.Append("\nPath Number ").Append(pathID).Append(" (unique id)"); } /** Returns a string with information about it. * More information is emitted when logMode == Heavy. * An empty string is returned if logMode == None * or logMode == OnlyErrors and this path did not fail. */ public virtual string DebugString (PathLog logMode) { if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) { return ""; } // Get a cached string builder for this thread System.Text.StringBuilder text = pathHandler.DebugStringBuilder; text.Length = 0; DebugStringPrefix(logMode, text); DebugStringSuffix(logMode, text); return text.ToString(); } /** Calls callback to return the calculated path. \see #callback */ public virtual void ReturnPath () { if (callback != null) { callback(this); } } /** Prepares low level path variables for calculation. * Called before a path search will take place. * Always called before the Prepare, Initialize and CalculateStep functions */ internal void PrepareBase (PathHandler pathHandler) { //Path IDs have overflowed 65K, cleanup is needed //Since pathIDs are handed out sequentially, we can do this if (pathHandler.PathID > pathID) { pathHandler.ClearPathIDs(); } //Make sure the path has a reference to the pathHandler this.pathHandler = pathHandler; //Assign relevant path data to the pathHandler pathHandler.InitializeForPath(this); // Make sure that internalTagPenalties is an array which has the length 32 if (internalTagPenalties == null || internalTagPenalties.Length != 32) internalTagPenalties = ZeroTagPenalties; try { ErrorCheck(); } catch (System.Exception e) { ForceLogError("Exception in path "+pathID+"\n"+e); } } /** Called before the path is started. * Called right before Initialize */ public abstract void Prepare (); /** Always called after the path has been calculated. * Guaranteed to be called before other paths have been calculated on * the same thread. * Use for cleaning up things like node tagging and similar. */ public virtual void Cleanup () {} /** Initializes the path. * Sets up the open list and adds the first node to it */ public abstract void Initialize (); /** Calculates the until it is complete or the time has progressed past \a targetTick */ public abstract void CalculateStep (long targetTick); } }
// // SourceManager.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2005-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Addins; using Banshee.ServiceStack; using Banshee.Library; namespace Banshee.Sources { public delegate void SourceEventHandler(SourceEventArgs args); public delegate void SourceAddedHandler(SourceAddedArgs args); public class SourceEventArgs : EventArgs { public Source Source; } public class SourceAddedArgs : SourceEventArgs { public int Position; } public class SourceManager : /*ISourceManager,*/ IInitializeService, IRequiredService, IDBusExportable, IDisposable { private List<Source> sources = new List<Source>(); private Dictionary<string, Source> extension_sources = new Dictionary<string, Source> (); private Source active_source; private Source default_source; private MusicLibrarySource music_library; private VideoLibrarySource video_library; public event SourceEventHandler SourceUpdated; public event SourceAddedHandler SourceAdded; public event SourceEventHandler SourceRemoved; public event SourceEventHandler ActiveSourceChanged; public void Initialize () { // TODO should add library sources here, but requires changing quite a few // things that depend on being loaded before the music library is added. //AddSource (music_library = new MusicLibrarySource (), true); //AddSource (video_library = new VideoLibrarySource (), false); } internal void LoadExtensionSources () { lock (this) { AddinManager.AddExtensionNodeHandler ("/Banshee/SourceManager/Source", OnExtensionChanged); } } public void Dispose () { lock (this) { try { AddinManager.RemoveExtensionNodeHandler ("/Banshee/SourceManager/Source", OnExtensionChanged); } catch {} active_source = null; default_source = null; music_library = null; video_library = null; // Do dispose extension sources foreach (Source source in extension_sources.Values) { RemoveSource (source, true); } // But do not dispose non-extension sources while (sources.Count > 0) { RemoveSource (sources[0], false); } sources.Clear (); extension_sources.Clear (); } } private void OnExtensionChanged (object o, ExtensionNodeEventArgs args) { lock (this) { TypeExtensionNode node = (TypeExtensionNode)args.ExtensionNode; if (args.Change == ExtensionChange.Add && !extension_sources.ContainsKey (node.Id)) { Source source = (Source)node.CreateInstance (); extension_sources.Add (node.Id, source); bool add_source = true; if (source.Properties.Contains ("AutoAddSource")) { add_source = source.Properties.GetBoolean ("AutoAddSource"); } if (add_source) { AddSource (source); } } else if (args.Change == ExtensionChange.Remove && extension_sources.ContainsKey (node.Id)) { Source source = extension_sources[node.Id]; extension_sources.Remove (node.Id); RemoveSource (source, true); } } } public void AddSource(Source source) { AddSource(source, false); } public void AddSource(Source source, bool isDefault) { Banshee.Base.ThreadAssist.AssertInMainThread (); if(source == null || ContainsSource (source)) { return; } int position = FindSourceInsertPosition(source); sources.Insert(position, source); if(isDefault) { default_source = source; } source.Updated += OnSourceUpdated; source.ChildSourceAdded += OnChildSourceAdded; source.ChildSourceRemoved += OnChildSourceRemoved; SourceAddedHandler handler = SourceAdded; if(handler != null) { SourceAddedArgs args = new SourceAddedArgs(); args.Position = position; args.Source = source; handler(args); } if (source is MusicLibrarySource) { music_library = source as MusicLibrarySource; } else if (source is VideoLibrarySource) { video_library = source as VideoLibrarySource; } IDBusExportable exportable = source as IDBusExportable; if (exportable != null) { ServiceManager.DBusServiceManager.RegisterObject (exportable); } List<Source> children = new List<Source> (source.Children); foreach(Source child_source in children) { AddSource (child_source, false); } if(isDefault && ActiveSource == null) { SetActiveSource(source); } } public void RemoveSource (Source source) { RemoveSource (source, false); } public void RemoveSource (Source source, bool recursivelyDispose) { if(source == null || !ContainsSource (source)) { return; } if(source == default_source) { default_source = null; } source.Updated -= OnSourceUpdated; source.ChildSourceAdded -= OnChildSourceAdded; source.ChildSourceRemoved -= OnChildSourceRemoved; sources.Remove(source); foreach(Source child_source in source.Children) { RemoveSource (child_source, recursivelyDispose); } IDBusExportable exportable = source as IDBusExportable; if (exportable != null) { ServiceManager.DBusServiceManager.UnregisterObject (exportable); } if (recursivelyDispose) { IDisposable disposable = source as IDisposable; if (disposable != null) { disposable.Dispose (); } } Banshee.Base.ThreadAssist.ProxyToMain (delegate { if(source == active_source) { SetActiveSource(default_source); } SourceEventHandler handler = SourceRemoved; if(handler != null) { SourceEventArgs args = new SourceEventArgs(); args.Source = source; handler(args); } }); } public void RemoveSource(Type type) { Queue<Source> remove_queue = new Queue<Source>(); foreach(Source source in Sources) { if(source.GetType() == type) { remove_queue.Enqueue(source); } } while(remove_queue.Count > 0) { RemoveSource(remove_queue.Dequeue()); } } public bool ContainsSource(Source source) { return sources.Contains(source); } private void OnSourceUpdated(object o, EventArgs args) { Banshee.Base.ThreadAssist.ProxyToMain (delegate { SourceEventHandler handler = SourceUpdated; if(handler != null) { SourceEventArgs evargs = new SourceEventArgs(); evargs.Source = o as Source; handler(evargs); } }); } private void OnChildSourceAdded(SourceEventArgs args) { AddSource (args.Source); } private void OnChildSourceRemoved(SourceEventArgs args) { RemoveSource (args.Source); } private int FindSourceInsertPosition(Source source) { for(int i = sources.Count - 1; i >= 0; i--) { if((sources[i] as Source).Order == source.Order) { return i; } } for(int i = 0; i < sources.Count; i++) { if((sources[i] as Source).Order >= source.Order) { return i; } } return sources.Count; } public Source DefaultSource { get { return default_source; } set { default_source = value; } } public MusicLibrarySource MusicLibrary { get { return music_library; } } public VideoLibrarySource VideoLibrary { get { return video_library; } } public Source ActiveSource { get { return active_source; } } /*ISource ISourceManager.DefaultSource { get { return DefaultSource; } } ISource ISourceManager.ActiveSource { get { return ActiveSource; } set { value.Activate (); } }*/ public void SetActiveSource(Source source) { SetActiveSource(source, true); } public void SetActiveSource(Source source, bool notify) { Banshee.Base.ThreadAssist.AssertInMainThread (); if(source == null || !source.CanActivate || active_source == source) { return; } if(active_source != null) { active_source.Deactivate(); } active_source = source; if(!notify) { source.Activate(); return; } SourceEventHandler handler = ActiveSourceChanged; if(handler != null) { SourceEventArgs args = new SourceEventArgs(); args.Source = active_source; handler(args); } source.Activate(); } public IEnumerable<T> FindSources<T> () where T : Source { foreach (Source source in Sources) { T t_source = source as T; if (t_source != null) { yield return t_source; } } } public ICollection<Source> Sources { get { return sources; } } /*string [] ISourceManager.Sources { get { return DBusServiceManager.MakeObjectPathArray<Source>(sources); } }*/ IDBusExportable IDBusExportable.Parent { get { return null; } } string Banshee.ServiceStack.IService.ServiceName { get { return "SourceManager"; } } } }
//************************************************************************** // // // National Institute Of Standards and Technology // DTS Version 1.0 // // Text Interface // // Written by: Carmelo Montanez // Modified by: Mary Brady // // Ported to System.Xml by: Mizrahi Rafael [email protected] // Mainsoft Corporation (c) 2003-2004 //************************************************************************** using System; using System.Xml; using nist_dom; using NUnit.Framework; namespace nist_dom.fundamental { [TestFixture] public class TextTest : Assertion { public static int i = 2; /* public testResults[] RunTests() { testResults[] tests = new testResults[] {core0001T(), core0002T(), core0003T(),core0004T(), core0005T(), core0006T(), core0007T(), core0008T(), core0009T()}; return tests; } */ //------------------------ test case core-0001T ------------------------ // // Testing feature - If there is no markup inside an Element or Attr node // content, then the text is contained in a single object // implementing the Text interface that is the only child // of the element. // // Testing approach - Retrieve the textual data from the second child of the // third employee. That Text node contains a block of // multiple text lines without markup, so they should be // treated as a single Text node. The "nodeValue" attribute // should contain the combination of the two lines. // // Semantic Requirements: 1 // //---------------------------------------------------------------------------- [Test] public void core0001T() { string computedValue = ""; string expectedValue = "Roger\n Jones"; System.Xml.XmlNode testNode = null; System.Xml.XmlCharacterData testNodeData = null; testResults results = new testResults("Core0001T"); try { results.description = "If there is no markup language in a block of text, " + "then the content of the text is contained into " + "an object implementing the Text interface that is " + "the only child of the element."; // // Retrieve the second child of the second employee and access its // textual data. // testNode = util.nodeObject(util.THIRD,util.SECOND); testNode.Normalize(); testNodeData = (System.Xml.XmlCharacterData)testNode.FirstChild; computedValue = testNodeData.Value; } catch(System.Exception ex) { computedValue = "Exception " + ex.Message; } // // Write out results // results.expected = expectedValue; results.actual = computedValue; AssertEquals (results.expected, results.actual); } //------------------------ End test case core-0001T -------------------------- // //-------------------------- test case core-0002T ---------------------------- // // Testing feature - If there is markup inside the Text element content, // then the text is parsed into a list of elements and text // that forms the list of children of the element. // // Testing approach - Retrieve the textual data from the last child of the // third employee. That node is composed of two // EntityReferences nodes and two Text nodes. After the // content of the node is parsed, the "address" Element // should contain four children with each one of the // EntityReferences containing one child in turn. // // Semantic Requirements: 2 // //---------------------------------------------------------------------------- [Test] public void core0002T() { string computedValue = ""; string expectedValue = "1900 Dallas Road Dallas, Texas\n 98554"; System.Xml.XmlNode testNode = null; System.Xml.XmlNode textBlock1 = null; System.Xml.XmlNode textBlock2 = null; System.Xml.XmlNode textBlock3 = null; System.Xml.XmlNode textBlock4 = null; testResults results = new testResults("Core0002T"); try { results.description = "If there is markup language in the content of the " + "element then the content is parsed into a " + "list of elements and Text that are the children of " + "the element"; // // This last child of the second employee should now have four children, // two Text nodes and two EntityReference nodes. Retrieve each one of them // and in the case of EntityReferences retrieve their respective children. // testNode = util.nodeObject(util.SECOND,util.SIXTH); textBlock1 = testNode.ChildNodes.Item(util.FIRST).FirstChild; textBlock2 = testNode.ChildNodes.Item(util.SECOND); textBlock3 = testNode.ChildNodes.Item(util.THIRD).FirstChild; textBlock4 = testNode.ChildNodes.Item(util.FOURTH); computedValue += textBlock1.Value; computedValue += textBlock2.Value; computedValue += textBlock3.Value; computedValue += textBlock4.Value; } catch(System.Exception ex) { computedValue = "Exception " + ex.Message; } // // Write out results // results.expected = expectedValue; results.actual = computedValue; AssertEquals (results.expected, results.actual); } //------------------------ End test case core-0002 -------------------------- // //-------------------------- test case core-0003T --------------------------- // // Testing feature - The "splitText(offset)" method breaks the Text node // into two Text nodes at the specified offset keeping // each node as siblings in the tree. // // Testing approach - Retrieve the textual data from the second child of the // third employee and invoke its "splitText(offset)" method. // The method splits the Text node into two new sibling // Text Nodes keeping both of them in the tree. This test // checks the "nextSibling" attribute of the original node // to ensure that the two nodes are indeed siblings. // // Semantic Requirements: 3 // //---------------------------------------------------------------------------- [Test] public void core0003T() { string computedValue = ""; string expectedValue = "Jones"; System.Xml.XmlText oldTextNode = null; System.Xml.XmlNode testNode = null; testResults results = new testResults("Core0003T"); try { results.description = "The \"splitText(offset)\" method breaks the Text node " + "into two Text nodes at the specified offset, keeping each " + "node in the tree as siblings."; // // Retrieve the targeted data. // testNode = util.nodeObject(util.THIRD,util.SECOND); oldTextNode = (System.Xml.XmlText)testNode.FirstChild; // // Split the two lines of text into two different Text nodes. // oldTextNode.SplitText(util.EIGHT); computedValue = oldTextNode.NextSibling.Value; } catch(System.Exception ex) { computedValue = "Exception " + ex.Message; } // // Write out results // results.expected = expectedValue; results.actual = computedValue; util.resetData(); AssertEquals (results.expected, results.actual); } //------------------------ End test case core-0003T -------------------------- // //-------------------------- test case core-0004T --------------------------- // // Testing feature - After The "splitText(offset)" method breaks the Text node // into two Text nodes, the original node contains all the // content up to the offset point. // // Testing approach - Retrieve the textual data from the second child // of the third employee and invoke the "splitText(offset)" // method. The original Text node should contain all the // content up to the offset point. The "nodeValue" // attribute is invoke to check that indeed the original // node now contains the first five characters // // Semantic Requirements: 4 // //---------------------------------------------------------------------------- [Test] public void core0004T() { string computedValue = ""; string expectedValue = "Roger"; System.Xml.XmlText oldTextNode = null; System.Xml.XmlNode testNode = null; testResults results = new testResults("Core0004T"); try { results.description = "After the \"splitText(offset)\" method is invoked, the " + "original Text node contains all of the content up to the " + "offset point."; // // Retrieve targeted data. // testNode = util.nodeObject(util.THIRD,util.SECOND); oldTextNode = (System.Xml.XmlText)testNode.FirstChild; // // Split the two lines of text into two different Text nodes. // oldTextNode.SplitText(util.SIXTH); computedValue = oldTextNode.Value; } catch(System.Exception ex) { computedValue = "Exception " + ex.Message; } // // Write out results // results.expected = expectedValue; results.actual = computedValue; util.resetData(); AssertEquals (results.expected, results.actual); } //------------------------ End test case core-0004T -------------------------- // //-------------------------- test case core-0005T --------------------------- // // Testing feature - After The "splitText(offset)" method breaks the Text node // into two Text nodes, the new Text node contains all the // content at and after the offset point. // // Testing approach - Retrieve the textual data from the second child of the // third employee and invoke the "splitText(offset)" method. // The new Text node should contain all the content at // and after the offset point. The "nodeValue" attribute // is invoked to check that indeed the new node now // contains the first characters at and after position // seven (starting from 0). // // Semantic Requirements: 5 // //---------------------------------------------------------------------------- [Test] public void core0005T() { string computedValue = ""; string expectedValue = " Jones"; System.Xml.XmlText oldTextNode = null; System.Xml.XmlText newTextNode = null; System.Xml.XmlNode testNode = null; testResults results = new testResults("Core0005T"); try { results.description = "After the \"splitText(offset)\" method is invoked, the " + "new Text node contains all of the content from the offset " + "point to the end of the text."; // // Retrieve the targeted data. // testNode = util.nodeObject(util.THIRD,util.SECOND); oldTextNode = (System.Xml.XmlText)testNode.FirstChild; // // Split the two lines of text into two different Text nodes. // newTextNode = oldTextNode.SplitText(util.SEVENTH); computedValue = newTextNode.Value; } catch(System.Exception ex) { computedValue = "Exception " + ex.Message; } // // Write out results // results.expected = expectedValue; results.actual = computedValue; util.resetData(); AssertEquals (results.expected, results.actual); } //------------------------ End test case core-0005T -------------------------- // //-------------------------- test case core-0006T --------------------------- // // Testing feature - The "splitText(offset)" method returns the new Text // node. // // Testing approach - Retrieve the textual data from the last child of the // first employee and invoke its "splitText(offset)" method. // The method should return the new Text node. The offset // value used for this test is 30. The "nodeValue" // attribute is invoked to check that indeed the new node // now contains the characters at and after postion 30 // (counting from 0). // // Semantic Requirements: 6 // //---------------------------------------------------------------------------- [Test] public void core0006T() { string computedValue = ""; string expectedValue = "98551"; System.Xml.XmlText oldTextNode = null; System.Xml.XmlText newTextNode = null; System.Xml.XmlNode testNode = null; testResults results = new testResults("Core0006T"); try { results.description = "The \"splitText(offset)\" method returns the " + "new Text node."; // // Retrieve the targeted data. // testNode = util.nodeObject(util.FIRST,util.SIXTH); oldTextNode = (System.Xml.XmlText)testNode.FirstChild; // // Split the two lines of text into two different Text nodes. // newTextNode = oldTextNode.SplitText(30); computedValue = newTextNode.Value; } catch(System.Exception ex) { computedValue = "Exception " + ex.Message; } // // Write out results // results.expected = expectedValue; results.actual = computedValue; util.resetData(); AssertEquals (results.expected, results.actual); } //------------------------ End test case core-0006T -------------------------- // //-------------------------- test case core-0007T --------------------------- // // Testing feature - The "splitText(offset)" method raises an INDEX_SIZE_ERR // Exception if the specified offset is negative. // // Testing approach - Retrieve the textual data from the second child of // the third employee and invoke its "splitText(offset)" // method with "offset" equals to a negative number. It // should raise the desired exception. // // Semantic Requirements: 7 // //---------------------------------------------------------------------------- [Test] public void core0007T() { string computedValue = ""; System.Xml.XmlText oldTextNode = null; System.Xml.XmlText newTextNode = null; System.Xml.XmlNode testNode = null; string expectedValue = "System.ArgumentOutOfRangeException";//util.INDEX_SIZE_ERR; testResults results = new testResults("Core0007T"); try { results.description = "The \"splitText(offset)\" method raises an " + "INDEX_SIZE_ERR Exception if the specified " + "offset is negative."; // // Retrieve the targeted data // testNode = util.nodeObject(util.THIRD,util.SECOND); oldTextNode = (System.Xml.XmlText)testNode.FirstChild; // // Call the "spitText(offset)" method with "offset" equal to a negative // number should raise an exception. // try { oldTextNode.SplitText(-69); } catch(System.Exception ex) { computedValue = ex.GetType ().FullName; } } catch(System.Exception ex) { computedValue = "Exception " + ex.Message; } results.expected = expectedValue; results.actual = computedValue; util.resetData(); AssertEquals (results.expected, results.actual); } //------------------------ End test case core-0007T -------------------------- // //-------------------------- test case core-0008T ---------------------------- // // Testing feature - The "splitText(offset)" method raises an // ArgumentOutOfRangeException if the specified offset is greater than the // number of 16-bit units in the Text node. // // Testing approach - Retrieve the textual data from the second child of // third employee and invoke its "splitText(offset)" // method with "offset" greater than the number of // characters in the Text node. It should raise the // desired exception. // // Semantic Requirements: 7 // //---------------------------------------------------------------------------- [Test] public void core0008T() { string computedValue = ""; System.Xml.XmlText oldTextNode = null; System.Xml.XmlNode testNode = null; string expectedValue = "System.ArgumentOutOfRangeException"; testResults results = new testResults("Core0008T"); try { results.description = "The \"splitText(offset)\" method raises an " + "ArgumentOutOfRangeException if the specified " + "offset is greater than the number of 16-bit units " + "in the Text node."; // // Retrieve the targeted data. // testNode = util.nodeObject(util.THIRD,util.SECOND); oldTextNode = (System.Xml.XmlText)testNode.FirstChild; // // Call the "spitText(offset)" method with "offset" greater than the numbers // of characters in the Text node, it should raise an exception. try { oldTextNode.SplitText(300); } catch(System.Exception ex) { computedValue = ex.GetType().ToString(); } } catch(System.Exception ex) { computedValue = "Exception " + ex.Message; } results.expected = expectedValue; results.actual = computedValue; util.resetData(); AssertEquals (results.expected, results.actual); } //------------------------ End test case core-0008T -------------------------- // //-------------------------- test case core-0009T ---------------------------- // // Testing feature - The "splitText(offset)" method raises a // NO_MODIFICATION_ALLOWED_ERR Exception if // the node is readonly. // // Testing approach - Retrieve the textual data from the first EntityReference // inside the last child of the second employee and invoke // its splitText(offset) method. Descendants of // EntityReference nodes are readonly and therefore the // desired exception should be raised. // // Semantic Requirements: 8 // //---------------------------------------------------------------------------- [Test] [Category ("NotDotNet")] // MS DOM is buggy public void core0009T() { string computedValue = ""; System.Xml.XmlNode testNode = null; System.Xml.XmlText readOnlyText = null; string expectedValue = "System.ArgumentException";//util.NO_MODIFICATION_ALLOWED_ERR; testResults results = new testResults("Core0009T"); try { results.description = "The \"splitText(offset)\" method raises a " + "NO_MODIFICATION_ALLOWED_ERR Exception if the " + "node is readonly."; // // Attempt to modify descendants of an EntityReference node should raise // an exception. // testNode = util.nodeObject(util.SECOND,util.SIXTH); readOnlyText = (System.Xml.XmlText)testNode.ChildNodes.Item(util.FIRST).FirstChild; try { readOnlyText.SplitText(5); } catch(ArgumentException ex) { computedValue = ex.GetType ().FullName; } } catch(System.Exception ex) { computedValue = "Exception " + ex.Message; } results.expected = expectedValue; results.actual = computedValue; util.resetData(); AssertEquals (results.expected, results.actual); } //------------------------ End test case core-0009T -------------------------- } }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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. *****************************************************************************/ // Contributed by: Mitch Thompson using UnityEngine; using UnityEditor; using System.Collections.Generic; using Spine; namespace Spine.Unity.Editor { using Icons = SpineEditorUtilities.Icons; [CustomEditor(typeof(SkeletonUtilityBone)), CanEditMultipleObjects] public class SkeletonUtilityBoneInspector : UnityEditor.Editor { SerializedProperty mode, boneName, zPosition, position, rotation, scale, overrideAlpha, parentReference; //multi selected flags bool containsFollows, containsOverrides, multiObject; //single selected helpers SkeletonUtilityBone utilityBone; SkeletonUtility skeletonUtility; bool canCreateHingeChain = false; Dictionary<Slot, List<BoundingBoxAttachment>> boundingBoxTable = new Dictionary<Slot, List<BoundingBoxAttachment>>(); //string currentSkinName = ""; void OnEnable () { mode = this.serializedObject.FindProperty("mode"); boneName = this.serializedObject.FindProperty("boneName"); zPosition = this.serializedObject.FindProperty("zPosition"); position = this.serializedObject.FindProperty("position"); rotation = this.serializedObject.FindProperty("rotation"); scale = this.serializedObject.FindProperty("scale"); overrideAlpha = this.serializedObject.FindProperty("overrideAlpha"); parentReference = this.serializedObject.FindProperty("parentReference"); EvaluateFlags(); if (!utilityBone.valid && skeletonUtility != null && skeletonUtility.skeletonRenderer != null) skeletonUtility.skeletonRenderer.Initialize(false); canCreateHingeChain = CanCreateHingeChain(); boundingBoxTable.Clear(); if (multiObject) return; if (utilityBone.bone == null) return; var skeleton = utilityBone.bone.Skeleton; int slotCount = skeleton.Slots.Count; Skin skin = skeleton.Skin; if (skeleton.Skin == null) skin = skeleton.Data.DefaultSkin; //currentSkinName = skin.Name; for(int i = 0; i < slotCount; i++){ Slot slot = skeletonUtility.skeletonRenderer.skeleton.Slots.Items[i]; if (slot.Bone == utilityBone.bone) { var slotAttachments = new List<Attachment>(); skin.FindAttachmentsForSlot(skeleton.FindSlotIndex(slot.Data.Name), slotAttachments); var boundingBoxes = new List<BoundingBoxAttachment>(); foreach (var att in slotAttachments) { var boundingBoxAttachment = att as BoundingBoxAttachment; if (boundingBoxAttachment != null) boundingBoxes.Add(boundingBoxAttachment); } if (boundingBoxes.Count > 0) boundingBoxTable.Add(slot, boundingBoxes); } } } void EvaluateFlags () { utilityBone = (SkeletonUtilityBone)target; skeletonUtility = utilityBone.skeletonUtility; if (Selection.objects.Length == 1) { containsFollows = utilityBone.mode == SkeletonUtilityBone.Mode.Follow; containsOverrides = utilityBone.mode == SkeletonUtilityBone.Mode.Override; } else { int boneCount = 0; foreach (Object o in Selection.objects) { var go = o as GameObject; if (go != null) { SkeletonUtilityBone sub = go.GetComponent<SkeletonUtilityBone>(); if (sub != null) { boneCount++; containsFollows |= (sub.mode == SkeletonUtilityBone.Mode.Follow); containsOverrides |= (sub.mode == SkeletonUtilityBone.Mode.Override); } } } multiObject |= (boneCount > 1); } } public override void OnInspectorGUI () { serializedObject.Update(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(mode); if (EditorGUI.EndChangeCheck()) { containsOverrides = mode.enumValueIndex == 1; containsFollows = mode.enumValueIndex == 0; } using (new EditorGUI.DisabledGroupScope(multiObject)) { string str = boneName.stringValue; if (str == "") str = "<None>"; if (multiObject) str = "<Multiple>"; using (new GUILayout.HorizontalScope()) { EditorGUILayout.PrefixLabel("Bone"); if (GUILayout.Button(str, EditorStyles.popup)) { BoneSelectorContextMenu(str, ((SkeletonUtilityBone)target).skeletonUtility.skeletonRenderer.skeleton.Bones, "<None>", TargetBoneSelected); } } } EditorGUILayout.PropertyField(zPosition); EditorGUILayout.PropertyField(position); EditorGUILayout.PropertyField(rotation); EditorGUILayout.PropertyField(scale); using (new EditorGUI.DisabledGroupScope(containsFollows)) { EditorGUILayout.PropertyField(overrideAlpha); EditorGUILayout.PropertyField(parentReference); } EditorGUILayout.Space(); using (new GUILayout.HorizontalScope()) { EditorGUILayout.Space(); using (new EditorGUI.DisabledGroupScope(multiObject || !utilityBone.valid || utilityBone.bone == null || utilityBone.bone.Children.Count == 0)) { if (GUILayout.Button(SpineInspectorUtility.TempContent("Add Child", Icons.bone), GUILayout.MinWidth(120), GUILayout.Height(24))) BoneSelectorContextMenu("", utilityBone.bone.Children, "<Recursively>", SpawnChildBoneSelected); } using (new EditorGUI.DisabledGroupScope(multiObject || !utilityBone.valid || utilityBone.bone == null || containsOverrides)) { if (GUILayout.Button(SpineInspectorUtility.TempContent("Add Override", Icons.poseBones), GUILayout.MinWidth(120), GUILayout.Height(24))) SpawnOverride(); } EditorGUILayout.Space(); } EditorGUILayout.Space(); using (new GUILayout.HorizontalScope()) { EditorGUILayout.Space(); using (new EditorGUI.DisabledGroupScope(multiObject || !utilityBone.valid || !canCreateHingeChain)) { if (GUILayout.Button(SpineInspectorUtility.TempContent("Create Hinge Chain", Icons.hingeChain), GUILayout.Width(150), GUILayout.Height(24))) CreateHingeChain(); } EditorGUILayout.Space(); } using (new EditorGUI.DisabledGroupScope(multiObject || boundingBoxTable.Count == 0)) { EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Bounding Boxes", Icons.boundingBox), EditorStyles.boldLabel); foreach (var entry in boundingBoxTable){ Slot slot = entry.Key; var boundingBoxes = entry.Value; EditorGUI.indentLevel++; EditorGUILayout.LabelField(slot.Data.Name); EditorGUI.indentLevel++; { foreach (var box in boundingBoxes) { using (new GUILayout.HorizontalScope()) { GUILayout.Space(30); string buttonLabel = box.IsWeighted() ? box.Name + " (!)" : box.Name; if (GUILayout.Button(buttonLabel, GUILayout.Width(200))) { utilityBone.bone.Skeleton.UpdateWorldTransform(); var bbTransform = utilityBone.transform.Find("[BoundingBox]" + box.Name); // Use FindChild in older versions of Unity. if (bbTransform != null) { var originalCollider = bbTransform.GetComponent<PolygonCollider2D>(); if (originalCollider != null) SkeletonUtility.SetColliderPointsLocal(originalCollider, slot, box); else SkeletonUtility.AddBoundingBoxAsComponent(box, slot, bbTransform.gameObject); } else { var newPolygonCollider = SkeletonUtility.AddBoundingBoxGameObject(null, box, slot, utilityBone.transform); bbTransform = newPolygonCollider.transform; } EditorGUIUtility.PingObject(bbTransform); } } } } EditorGUI.indentLevel--; EditorGUI.indentLevel--; } } BoneFollowerInspector.RecommendRigidbodyButton(utilityBone); serializedObject.ApplyModifiedProperties(); } static void BoneSelectorContextMenu (string current, ExposedList<Bone> bones, string topValue, GenericMenu.MenuFunction2 callback) { var menu = new GenericMenu(); if (topValue != "") menu.AddItem(new GUIContent(topValue), current == topValue, callback, null); for (int i = 0; i < bones.Count; i++) menu.AddItem(new GUIContent(bones.Items[i].Data.Name), bones.Items[i].Data.Name == current, callback, bones.Items[i]); menu.ShowAsContext(); } void TargetBoneSelected (object obj) { if (obj == null) { boneName.stringValue = ""; serializedObject.ApplyModifiedProperties(); } else { var bone = (Bone)obj; boneName.stringValue = bone.Data.Name; serializedObject.ApplyModifiedProperties(); utilityBone.Reset(); } } void SpawnChildBoneSelected (object obj) { if (obj == null) { // Add recursively foreach (var bone in utilityBone.bone.Children) { GameObject go = skeletonUtility.SpawnBoneRecursively(bone, utilityBone.transform, utilityBone.mode, utilityBone.position, utilityBone.rotation, utilityBone.scale); SkeletonUtilityBone[] newUtilityBones = go.GetComponentsInChildren<SkeletonUtilityBone>(); foreach (SkeletonUtilityBone utilBone in newUtilityBones) SkeletonUtilityInspector.AttachIcon(utilBone); } } else { var bone = (Bone)obj; GameObject go = skeletonUtility.SpawnBone(bone, utilityBone.transform, utilityBone.mode, utilityBone.position, utilityBone.rotation, utilityBone.scale); SkeletonUtilityInspector.AttachIcon(go.GetComponent<SkeletonUtilityBone>()); Selection.activeGameObject = go; EditorGUIUtility.PingObject(go); } } void SpawnOverride () { GameObject go = skeletonUtility.SpawnBone(utilityBone.bone, utilityBone.transform.parent, SkeletonUtilityBone.Mode.Override, utilityBone.position, utilityBone.rotation, utilityBone.scale); go.name = go.name + " [Override]"; SkeletonUtilityInspector.AttachIcon(go.GetComponent<SkeletonUtilityBone>()); Selection.activeGameObject = go; EditorGUIUtility.PingObject(go); } bool CanCreateHingeChain () { if (utilityBone == null) return false; if (utilityBone.GetComponent<Rigidbody>() != null) return false; if (utilityBone.bone != null && utilityBone.bone.Children.Count == 0) return false; Rigidbody[] rigidbodies = utilityBone.GetComponentsInChildren<Rigidbody>(); return rigidbodies.Length <= 0; } void CreateHingeChain () { var utilBoneArr = utilityBone.GetComponentsInChildren<SkeletonUtilityBone>(); foreach (var utilBone in utilBoneArr) { AttachRigidbody(utilBone); } utilityBone.GetComponent<Rigidbody>().isKinematic = true; foreach (var utilBone in utilBoneArr) { if (utilBone == utilityBone) continue; utilBone.mode = SkeletonUtilityBone.Mode.Override; HingeJoint joint = utilBone.gameObject.AddComponent<HingeJoint>(); joint.axis = Vector3.forward; joint.connectedBody = utilBone.transform.parent.GetComponent<Rigidbody>(); joint.useLimits = true; joint.limits = new JointLimits { min = -20, max = 20 }; utilBone.GetComponent<Rigidbody>().mass = utilBone.transform.parent.GetComponent<Rigidbody>().mass * 0.75f; } } static void AttachRigidbody (SkeletonUtilityBone utilBone) { if (utilBone.GetComponent<Collider>() == null) { if (utilBone.bone.Data.Length == 0) { SphereCollider sphere = utilBone.gameObject.AddComponent<SphereCollider>(); sphere.radius = 0.1f; } else { float length = utilBone.bone.Data.Length; BoxCollider box = utilBone.gameObject.AddComponent<BoxCollider>(); box.size = new Vector3(length, length / 3f, 0.2f); box.center = new Vector3(length / 2f, 0, 0); } } utilBone.gameObject.AddComponent<Rigidbody>(); } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.TypeInferrer; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TypeInferrer { public partial class TypeInferrerTests : TypeInferrerTestBase<CSharpTestWorkspaceFixture> { public TypeInferrerTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } protected override async Task TestWorkerAsync(Document document, TextSpan textSpan, string expectedType, bool useNodeStartPosition) { var root = (await document.GetSyntaxTreeAsync()).GetRoot(); var node = FindExpressionSyntaxFromSpan(root, textSpan); var typeInference = document.GetLanguageService<ITypeInferenceService>(); var inferredType = useNodeStartPosition ? typeInference.InferType(await document.GetSemanticModelForSpanAsync(new TextSpan(node?.SpanStart ?? textSpan.Start, 0), CancellationToken.None), node?.SpanStart ?? textSpan.Start, objectAsDefault: true, cancellationToken: CancellationToken.None) : typeInference.InferType(await document.GetSemanticModelForSpanAsync(node?.Span ?? textSpan, CancellationToken.None), node, objectAsDefault: true, cancellationToken: CancellationToken.None); var typeSyntax = inferredType.GenerateTypeSyntax(); Assert.Equal(expectedType, typeSyntax.ToString()); } private async Task TestInClassAsync(string text, string expectedType) { text = @"class C { $ }".Replace("$", text); await TestAsync(text, expectedType); } private async Task TestInMethodAsync(string text, string expectedType, bool testNode = true, bool testPosition = true) { text = @"class C { void M() { $ } }".Replace("$", text); await TestAsync(text, expectedType, testNode: testNode, testPosition: testPosition); } private ExpressionSyntax FindExpressionSyntaxFromSpan(SyntaxNode root, TextSpan textSpan) { var token = root.FindToken(textSpan.Start); var currentNode = token.Parent; while (currentNode != null) { ExpressionSyntax result = currentNode as ExpressionSyntax; if (result != null && result.Span == textSpan) { return result; } currentNode = currentNode.Parent; } return null; } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional1() { // We do not support position inference here as we're before the ? and we only look // backwards to infer a type here. await TestInMethodAsync("var q = [|Foo()|] ? 1 : 2;", "System.Boolean", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional2() { await TestInMethodAsync("var q = a ? [|Foo()|] : 2;", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional3() { await TestInMethodAsync(@"var q = a ? """" : [|Foo()|];", "System.String"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclarator1() { await TestInMethodAsync("int q = [|Foo()|];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclarator2() { await TestInMethodAsync("var q = [|Foo()|];", "System.Object"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce1() { await TestInMethodAsync("var q = [|Foo()|] ?? 1;", "System.Int32?", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce2() { await TestInMethodAsync(@"bool? b; var q = b ?? [|Foo()|];", "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce3() { await TestInMethodAsync(@"string s; var q = s ?? [|Foo()|];", "System.String"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce4() { await TestInMethodAsync("var q = [|Foo()|] ?? string.Empty;", "System.String", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryExpression1() { await TestInMethodAsync(@"string s; var q = s + [|Foo()|];", "System.String"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryExpression2() { await TestInMethodAsync(@"var s; var q = s || [|Foo()|];", "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryOperator1() { await TestInMethodAsync(@"var q = x << [|Foo()|];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryOperator2() { await TestInMethodAsync(@"var q = x >> [|Foo()|];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAssignmentOperator3() { await TestInMethodAsync(@"var q <<= [|Foo()|];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAssignmentOperator4() { await TestInMethodAsync(@"var q >>= [|Foo()|];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestOverloadedConditionalLogicalOperatorsInferBool() { await TestAsync(@"using System; class C { public static C operator &(C c, C d) { return null; } public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main(string[] args) { var c = new C() && [|Foo()|]; } }", "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestConditionalLogicalOrOperatorAlwaysInfersBool() { var text = @"using System; class C { static void Main(string[] args) { var x = a || [|7|]; } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestConditionalLogicalAndOperatorAlwaysInfersBool() { var text = @"using System; class C { static void Main(string[] args) { var x = a && [|7|]; } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalOrOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | true; } }"; await TestAsync(text, "System.Boolean", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalOrOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | b | c || d; } }"; await TestAsync(text, "System.Boolean", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalOrOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a | b | [|c|] || d; } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalOrOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] | b); } static object Foo(Program p) { return p; } }"; await TestAsync(text, "Program", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalOrOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] | b); } static object Foo(bool p) { return p; } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalOrOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] | y) != 0) {} } }"; await TestAsync(text, "System.Int32", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalOrOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] | y) {} } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalAndOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & true; } }"; await TestAsync(text, "System.Boolean", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalAndOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & b & c && d; } }"; await TestAsync(text, "System.Boolean", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalAndOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a & b & [|c|] && d; } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalAndOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] & b); } static object Foo(Program p) { return p; } }"; await TestAsync(text, "Program", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalAndOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] & b); } static object Foo(bool p) { return p; } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalAndOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] & y) != 0) {} } }"; await TestAsync(text, "System.Int32", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalAndOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] & y) {} } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalXorOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ true; } }"; await TestAsync(text, "System.Boolean", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalXorOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ b ^ c && d; } }"; await TestAsync(text, "System.Boolean", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalXorOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a ^ b ^ [|c|] && d; } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalXorOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] ^ b); } static object Foo(Program p) { return p; } }"; await TestAsync(text, "Program", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalXorOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] ^ b); } static object Foo(bool p) { return p; } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalXorOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] ^ y) != 0) {} } }"; await TestAsync(text, "System.Int32", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalXorOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^ y) {} } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalOrEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] |= y) {} } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalOrEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] |= y; } }"; await TestAsync(text, "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalAndEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] &= y) {} } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalAndEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] &= y; } }"; await TestAsync(text, "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalXorEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^= y) {} } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public async Task TestLogicalXorEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] ^= y; } }"; await TestAsync(text, "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturn1() { await TestInClassAsync(@"int M() { return [|Foo()|]; }", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturn2() { await TestInMethodAsync("return [|Foo()|];", "void"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturn3() { await TestInClassAsync(@"int Property { get { return [|Foo()|]; } }", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897)] public async Task TestYieldReturn() { var markup = @"using System.Collections.Generic; class Program { IEnumerable<int> M() { yield return [|abc|] } }"; await TestAsync(markup, "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInLambda() { await TestInMethodAsync("System.Func<string,int> f = s => { return [|Foo()|]; };", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestLambda() { await TestInMethodAsync("System.Func<string, int> f = s => [|Foo()|];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThrow() { await TestInMethodAsync("throw [|Foo()|];", "global::System.Exception"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCatch() { await TestInMethodAsync("try { } catch ([|Foo|] ex) { }", "global::System.Exception"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIf() { await TestInMethodAsync(@"if ([|Foo()|]) { }", "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhile() { await TestInMethodAsync(@"while ([|Foo()|]) { }", "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDo() { await TestInMethodAsync(@"do { } while ([|Foo()|])", "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor1() { await TestInMethodAsync(@"for (int i = 0; [|Foo()|]; i++) { }", "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor2() { await TestInMethodAsync(@"for (string i = [|Foo()|]; ; ) { }", "System.String"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor3() { await TestInMethodAsync(@"for (var i = [|Foo()|]; ; ) { }", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing1() { await TestInMethodAsync(@"using ([|Foo()|]) { }", "global::System.IDisposable"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing2() { await TestInMethodAsync(@"using (int i = [|Foo()|]) { }", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing3() { await TestInMethodAsync(@"using (var v = [|Foo()|]) { }", "global::System.IDisposable"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestForEach() { await TestInMethodAsync(@"foreach (int v in [|Foo()|]) { }", "global::System.Collections.Generic.IEnumerable<System.Int32>"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression1() { await TestInMethodAsync(@"var q = +[|Foo()|];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression2() { await TestInMethodAsync(@"var q = -[|Foo()|];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression3() { await TestInMethodAsync(@"var q = ~[|Foo()|];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression4() { await TestInMethodAsync(@"var q = ![|Foo()|];", "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayRankSpecifier() { await TestInMethodAsync(@"var q = new string[[|Foo()|]];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch1() { await TestInMethodAsync(@"switch ([|Foo()|]) { }", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch2() { await TestInMethodAsync(@"switch ([|Foo()|]) { default: }", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch3() { await TestInMethodAsync(@"switch ([|Foo()|]) { case ""a"": }", "System.String"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall1() { await TestInMethodAsync(@"Bar([|Foo()|]);", "System.Object"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall2() { await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar(int i);", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall3() { await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar();", "System.Object"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall4() { await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar(int i, string s);", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall5() { await TestInClassAsync(@"void M() { Bar(s: [|Foo()|]); } void Bar(int i, string s);", "System.String"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall1() { await TestInMethodAsync(@"new C([|Foo()|]);", "System.Object"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall2() { await TestInClassAsync(@"void M() { new C([|Foo()|]); } C(int i) { }", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall3() { await TestInClassAsync(@"void M() { new C([|Foo()|]); } C() { }", "System.Object"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall4() { await TestInClassAsync(@"void M() { new C([|Foo()|]); } C(int i, string s) { }", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall5() { await TestInClassAsync(@"void M() { new C(s: [|Foo()|]); } C(int i, string s) { }", "System.String"); } [WorkItem(858112)] [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializer1() { await TestAsync(@"class MyClass { public MyClass(int x) : this([|test|]) { } }", "System.Int32"); } [WorkItem(858112)] [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializer2() { await TestAsync(@"class MyClass { public MyClass(int x, string y) : this(5, [|test|]) { } }", "System.String"); } [WorkItem(858112)] [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBaseConstructorInitializer() { await TestAsync(@"class B { public B(int x) { } } class D : B { public D() : base([|test|]) { } }", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexAccess1() { await TestInMethodAsync(@"string[] i; i[[|Foo()|]];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall1() { await TestInMethodAsync(@"this[[|Foo()|]];", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall2() { // Update this when binding of indexers is working. await TestInClassAsync(@"void M() { this[[|Foo()|]]; } int this [int i] { get; }", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall3() { // Update this when binding of indexers is working. await TestInClassAsync(@"void M() { this[[|Foo()|]]; } int this [int i, string s] { get; }", "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall5() { await TestInClassAsync(@"void M() { this[s: [|Foo()|]]; } int this [int i, string s] { get; }", "System.String"); } [WpfFact] public async Task TestArrayInitializerInImplicitArrayCreationSimple() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { 1, [|2|] }; } }"; await TestAsync(text, "System.Int32"); } [WpfFact] public async Task TestArrayInitializerInImplicitArrayCreation1() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } int Bar() { return 1; } int Foo() { return 2; } }"; await TestAsync(text, "System.Int32"); } [WpfFact] public async Task TestArrayInitializerInImplicitArrayCreation2() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } int Bar() { return 1; } }"; await TestAsync(text, "System.Int32"); } [WpfFact] public async Task TestArrayInitializerInImplicitArrayCreation3() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } }"; await TestAsync(text, "System.Object"); } [WpfFact] public async Task TestArrayInitializerInEqualsValueClauseSimple() { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { 1, [|2|] }; } }"; await TestAsync(text, "System.Int32"); } [WpfFact] public async Task TestArrayInitializerInEqualsValueClause() { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { Bar(), [|Foo()|] }; } int Bar() { return 1; } }"; await TestAsync(text, "System.Int32"); } [WpfFact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCollectionInitializer1() { var text = @"using System.Collections.Generic; class C { void M() { new List<int>() { [|Foo()|] }; } }"; await TestAsync(text, "System.Int32"); } [WpfFact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCollectionInitializer2() { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { [|Foo()|], """" } }; } }"; await TestAsync(text, "System.Int32"); } [WpfFact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCollectionInitializer3() { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { 0, [|Foo()|] } }; } }"; await TestAsync(text, "System.String"); } [WpfFact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCustomCollectionInitializerAddMethod1() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { [|a|] }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "System.Int32", testPosition: false); } [WpfFact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCustomCollectionInitializerAddMethod2() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { ""test"", [|b|] } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "System.Boolean"); } [WpfFact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCustomCollectionInitializerAddMethod3() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { [|s|], true } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "System.String"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference1() { var text = @" class A { void Foo() { A[] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference1_Position() { var text = @" class A { void Foo() { A[] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[]", testNode: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference2() { var text = @" class A { void Foo() { A[][] x = new [|C|][][] { }; } }"; await TestAsync(text, "global::A", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference2_Position() { var text = @" class A { void Foo() { A[][] x = new [|C|][][] { }; } }"; await TestAsync(text, "global::A[][]", testNode: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference3() { var text = @" class A { void Foo() { A[][] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[]", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference3_Position() { var text = @" class A { void Foo() { A[][] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[][]", testNode: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference4() { var text = @" using System; class A { void Foo() { Func<int, int>[] x = new Func<int, int>[] { [|Bar()|] }; } }"; await TestAsync(text, "global::System.Func<System.Int32,System.Int32>"); } [WorkItem(538993)] [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInsideLambda2() { var text = @"using System; class C { void M() { Func<int,int> f = i => [|here|] } }"; await TestAsync(text, "System.Int32"); } [WorkItem(539813)] [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPointer1() { var text = @"class C { void M(int* i) { var q = i[[|Foo()|]]; } }"; await TestAsync(text, "System.Int32"); } [WorkItem(539813)] [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDynamic1() { var text = @"class C { void M(dynamic i) { var q = i[[|Foo()|]]; } }"; await TestAsync(text, "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestChecked1() { var text = @"class C { void M() { string q = checked([|Foo()|]); } }"; await TestAsync(text, "System.String"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584)] public async Task TestAwaitTaskOfT() { var text = @"using System.Threading.Tasks; class C { void M() { int x = await [|Foo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<System.Int32>"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584)] public async Task TestAwaitTaskOfTaskOfT() { var text = @"using System.Threading.Tasks; class C { void M() { Task<int> x = await [|Foo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Threading.Tasks.Task<System.Int32>>"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584)] public async Task TestAwaitTask() { var text = @"using System.Threading.Tasks; class C { void M() { await [|Foo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622)] public async Task TestLockStatement() { var text = @"class C { void M() { lock([|Foo()|]) { } } }"; await TestAsync(text, "System.Object"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622)] public async Task TestAwaitExpressionInLockStatement() { var text = @"class C { async void M() { lock(await [|Foo()|]) { } } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<System.Object>"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897)] public async Task TestReturnFromAsyncTaskOfT() { var markup = @"using System.Threading.Tasks; class Program { async Task<int> M() { await Task.Delay(1); return [|ab|] } }"; await TestAsync(markup, "System.Int32"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840)] public async Task TestAttributeArguments1() { var markup = @"[A([|dd|], ee, Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.DayOfWeek"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840)] public async Task TestAttributeArguments2() { var markup = @"[A(dd, [|ee|], Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "System.Double"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840)] public async Task TestAttributeArguments3() { var markup = @"[A(dd, ee, Y = [|ff|])] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "System.String"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(757111)] public async Task TestReturnStatementWithinDelegateWithinAMethodCall() { var text = @"using System; class Program { delegate string A(int i); static void Main(string[] args) { B(delegate(int i) { return [|M()|]; }); } private static void B(A a) { } }"; await TestAsync(text, "System.String"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388)] public async Task TestCatchFilterClause() { var text = @" try { } catch (Exception) if ([|M()|]) }"; await TestInMethodAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388)] public async Task TestCatchFilterClause1() { var text = @" try { } catch (Exception) if ([|M|]) }"; await TestInMethodAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388)] public async Task TestCatchFilterClause2() { var text = @" try { } catch (Exception) if ([|M|].N) }"; await TestInMethodAsync(text, "System.Object", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public async Task TestAwaitExpressionWithChainingMethod() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M()|].ConfigureAwait(false); } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<System.Boolean>"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public async Task TestAwaitExpressionWithChainingMethod2() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M|].ContinueWith(a => { return true; }).ContinueWith(a => { return false; }); } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<System.Boolean>"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public async Task TestAwaitExpressionWithGenericMethod1() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await X([|Test()|]); } private async Task<T> X<T>(T t) { return t; } }"; await TestAsync(text, "System.Boolean", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public async Task TestAwaitExpressionWithGenericMethod2() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await Task.Run(() => [|Test()|]);; } private async Task<T> X<T>(T t) { return t; } }"; await TestAsync(text, "System.Boolean"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator1() { var text = @"class C { void M() { object z = [|a|]?? null; } }"; await TestAsync(text, "System.Object"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator2() { var text = @"class C { void M() { object z = [|a|] ?? b ?? c; } }"; await TestAsync(text, "System.Object"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator3() { var text = @"class C { void M() { object z = a ?? [|b|] ?? c; } }"; await TestAsync(text, "System.Object"); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public async Task TestSelectLambda() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[||]) } }"; await TestAsync(text, "System.Object", testPosition: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public async Task TestSelectLambda2() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[|b|]) } }"; await TestAsync(text, "System.Object", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] public async Task TestReturnInAsyncLambda1() { var text = @"using System; using System.IO; using System.Threading.Tasks; public class C { public async void M() { Func<Task<int>> t2 = async () => { return [|a|]; }; } }"; await TestAsync(text, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] public async Task TestReturnInAsyncLambda2() { var text = @"using System; using System.IO; using System.Threading.Tasks; public class C { public async void M() { Func<Task<int>> t2 = async delegate () { return [|a|]; }; } }"; await TestAsync(text, "System.Int32"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; namespace System.Collections.Specialized.Tests { public class GetValuesTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { const int BIG_LENGTH = 100; HybridDictionary hd; // simple string values string[] valuesShort = { "", " ", "$%^#", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keysShort = { Int32.MaxValue.ToString(), " ", System.DateTime.Today.ToString(), "", "$%^#" }; string[] valuesLong = new string[BIG_LENGTH]; string[] keysLong = new string[BIG_LENGTH]; Array arr; ICollection vs; // Values collection int ind; for (int i = 0; i < BIG_LENGTH; i++) { valuesLong[i] = "Item" + i; keysLong[i] = "keY" + i; } // [] HybridDictionary is constructed as expected //----------------------------------------------------------------- hd = new HybridDictionary(); // [] for empty dictionary // if (hd.Count > 0) hd.Clear(); if (hd.Values.Count != 0) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", hd.Values.Count)); } // [] for short filled dictionary // int len = valuesShort.Length; hd.Clear(); for (int i = 0; i < len; i++) { hd.Add(keysShort[i], valuesShort[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } vs = hd.Values; if (vs.Count != len) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } arr = Array.CreateInstance(typeof(Object), len); vs.CopyTo(arr, 0); for (int i = 0; i < len; i++) { ind = Array.IndexOf(arr, valuesShort[i]); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain \"{1}\" value. Search result: {2}", i, valuesShort[i], ind)); } } // [] for long filled dictionary // len = valuesLong.Length; hd.Clear(); for (int i = 0; i < len; i++) { hd.Add(keysLong[i], valuesLong[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } vs = hd.Values; if (vs.Count != len) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } arr = Array.CreateInstance(typeof(Object), len); vs.CopyTo(arr, 0); for (int i = 0; i < len; i++) { ind = Array.IndexOf(arr, valuesLong[i]); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain \"{1}\" value. Search result: {2}", i, valuesLong[i], ind)); } } // // [] get Values on dictionary with different_in_casing_only keys - list // hd.Clear(); string intlStr = "intlStr"; hd.Add("keykey", intlStr); // 1st key hd.Add("keyKey", intlStr); // 2nd key if (hd.Count != 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, 2)); } // get Values // vs = hd.Values; if (vs.Count != hd.Count) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } arr = Array.CreateInstance(typeof(Object), 2); vs.CopyTo(arr, 0); ind = Array.IndexOf(arr, intlStr); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain {0} value", intlStr)); } // // [] get Values on dictionary with different_in_casing_only keys - hashtable // hd.Clear(); hd.Add("keykey", intlStr); // 1st key for (int i = 0; i < BIG_LENGTH; i++) { hd.Add(keysLong[i], valuesLong[i]); } hd.Add("keyKey", intlStr); // 2nd key if (hd.Count != BIG_LENGTH + 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, BIG_LENGTH + 2)); } // get Values // vs = hd.Values; if (vs.Count != hd.Count) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } arr = Array.CreateInstance(typeof(Object), BIG_LENGTH + 2); vs.CopyTo(arr, 0); for (int i = 0; i < BIG_LENGTH; i++) { if (Array.IndexOf(arr, valuesLong[i]) < 0) { Assert.False(true, string.Format("Error, Values doesn't contain {0} value", valuesLong[i], i)); } } ind = Array.IndexOf(arr, intlStr); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain {0} value", intlStr)); } // // [] Change long dictionary and check Values // hd.Clear(); len = valuesLong.Length; for (int i = 0; i < len; i++) { hd.Add(keysLong[i], valuesLong[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } vs = hd.Values; if (vs.Count != len) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } hd.Remove(keysLong[0]); if (hd.Count != len - 1) { Assert.False(true, string.Format("Error, didn't remove element")); } if (vs.Count != len - 1) { Assert.False(true, string.Format("Error, Values were not updated after removal")); } arr = Array.CreateInstance(typeof(Object), hd.Count); vs.CopyTo(arr, 0); ind = Array.IndexOf(arr, valuesLong[0]); if (ind >= 0) { Assert.False(true, string.Format("Error, Values still contains removed value " + ind)); } hd.Add(keysLong[0], "new item"); if (hd.Count != len) { Assert.False(true, string.Format("Error, didn't add element")); } if (vs.Count != len) { Assert.False(true, string.Format("Error, Values were not updated after addition")); } arr = Array.CreateInstance(typeof(Object), hd.Count); vs.CopyTo(arr, 0); ind = Array.IndexOf(arr, "new item"); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain added value ")); } // // [] Change short dictionary and check Values // hd.Clear(); len = valuesShort.Length; for (int i = 0; i < len; i++) { hd.Add(keysShort[i], valuesShort[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } vs = hd.Values; if (vs.Count != len) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } hd.Remove(keysShort[0]); if (hd.Count != len - 1) { Assert.False(true, string.Format("Error, didn't remove element")); } if (vs.Count != len - 1) { Assert.False(true, string.Format("Error, Values were not updated after removal")); } arr = Array.CreateInstance(typeof(Object), hd.Count); vs.CopyTo(arr, 0); ind = Array.IndexOf(arr, valuesShort[0]); if (ind >= 0) { Assert.False(true, string.Format("Error, Values still contains removed value " + ind)); } hd.Add(keysShort[0], "new item"); if (hd.Count != len) { Assert.False(true, string.Format("Error, didn't add element")); } if (vs.Count != len) { Assert.False(true, string.Format("Error, Values were not updated after addition")); } arr = Array.CreateInstance(typeof(Object), hd.Count); vs.CopyTo(arr, 0); ind = Array.IndexOf(arr, "new item"); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain added value ")); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for Additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace TestCases.HSSF.UserModel { using System; using System.Collections; using System.Collections.Generic; using NPOI.DDF; using NPOI.HSSF.Model; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.Util; using NUnit.Framework; using TestCases.SS.UserModel; /** * Test <c>HSSFPicture</c>. * * @author Yegor Kozlov (yegor at apache.org) */ [TestFixture] public class TestHSSFPicture : BaseTestPicture { public TestHSSFPicture() : base(HSSFITestDataProvider.Instance) { } [Test] public void Resize() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("resize_Compare.xls"); HSSFPatriarch dp = wb.GetSheetAt(0).CreateDrawingPatriarch() as HSSFPatriarch; IList<HSSFShape> pics = dp.Children; HSSFPicture inpPic = (HSSFPicture)pics[(0)]; HSSFPicture cmpPic = (HSSFPicture)pics[(1)]; BaseTestResize(inpPic, cmpPic, 2.0, 2.0); //wb.Close(); } /** * Bug # 45829 reported ArithmeticException (/ by zero) when resizing png with zero DPI. */ [Test] public void Bug45829() { HSSFWorkbook wb = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet sh1 = wb.CreateSheet(); IDrawing p1 = sh1.CreateDrawingPatriarch(); byte[] pictureData = HSSFTestDataSamples.GetTestDataFileContent("45829.png"); int idx1 = wb.AddPicture(pictureData, PictureType.PNG); IPicture pic = p1.CreatePicture(new HSSFClientAnchor(), idx1); pic.Resize(); } [Test] public void AddPictures() { IWorkbook wb = new HSSFWorkbook(); ISheet sh = wb.CreateSheet("Pictures"); IDrawing dr = sh.CreateDrawingPatriarch(); Assert.AreEqual(0, ((HSSFPatriarch)dr).Children.Count); IClientAnchor anchor = wb.GetCreationHelper().CreateClientAnchor(); //register a picture byte[] data1 = new byte[] { 1, 2, 3 }; int idx1 = wb.AddPicture(data1, PictureType.JPEG); Assert.AreEqual(1, idx1); IPicture p1 = dr.CreatePicture(anchor, idx1); Assert.IsTrue(Arrays.Equals(data1, ((HSSFPicture)p1).PictureData.Data)); // register another one byte[] data2 = new byte[] { 4, 5, 6 }; int idx2 = wb.AddPicture(data2, PictureType.JPEG); Assert.AreEqual(2, idx2); IPicture p2 = dr.CreatePicture(anchor, idx2); Assert.AreEqual(2, ((HSSFPatriarch)dr).Children.Count); Assert.IsTrue(Arrays.Equals(data2, ((HSSFPicture)p2).PictureData.Data)); // confirm that HSSFPatriarch.Children returns two picture shapes Assert.IsTrue(Arrays.Equals(data1, ((HSSFPicture)((HSSFPatriarch)dr).Children[(0)]).PictureData.Data)); Assert.IsTrue(Arrays.Equals(data2, ((HSSFPicture)((HSSFPatriarch)dr).Children[(1)]).PictureData.Data)); // Write, read back and verify that our pictures are there wb = HSSFTestDataSamples.WriteOutAndReadBack((HSSFWorkbook)wb); IList lst2 = wb.GetAllPictures(); Assert.AreEqual(2, lst2.Count); Assert.IsTrue(Arrays.Equals(data1, (lst2[(0)] as HSSFPictureData).Data)); Assert.IsTrue(Arrays.Equals(data2, (lst2[(1)] as HSSFPictureData).Data)); // confirm that the pictures are in the Sheet's Drawing sh = wb.GetSheet("Pictures"); dr = sh.CreateDrawingPatriarch(); Assert.AreEqual(2, ((HSSFPatriarch)dr).Children.Count); Assert.IsTrue(Arrays.Equals(data1, ((HSSFPicture)((HSSFPatriarch)dr).Children[(0)]).PictureData.Data)); Assert.IsTrue(Arrays.Equals(data2, ((HSSFPicture)((HSSFPatriarch)dr).Children[(1)]).PictureData.Data)); // add a third picture byte[] data3 = new byte[] { 7, 8, 9 }; // picture index must increment across Write-read int idx3 = wb.AddPicture(data3, PictureType.JPEG); Assert.AreEqual(3, idx3); IPicture p3 = dr.CreatePicture(anchor, idx3); Assert.IsTrue(Arrays.Equals(data3, ((HSSFPicture)p3).PictureData.Data)); Assert.AreEqual(3, ((HSSFPatriarch)dr).Children.Count); Assert.IsTrue(Arrays.Equals(data1, ((HSSFPicture)((HSSFPatriarch)dr).Children[(0)]).PictureData.Data)); Assert.IsTrue(Arrays.Equals(data2, ((HSSFPicture)((HSSFPatriarch)dr).Children[(1)]).PictureData.Data)); Assert.IsTrue(Arrays.Equals(data3, ((HSSFPicture)((HSSFPatriarch)dr).Children[(2)]).PictureData.Data)); // write and read again wb = HSSFTestDataSamples.WriteOutAndReadBack((HSSFWorkbook)wb); IList lst3 = wb.GetAllPictures(); // all three should be there Assert.AreEqual(3, lst3.Count); Assert.IsTrue(Arrays.Equals(data1, (lst3[(0)] as HSSFPictureData).Data)); Assert.IsTrue(Arrays.Equals(data2, (lst3[(1)] as HSSFPictureData).Data)); Assert.IsTrue(Arrays.Equals(data3, (lst3[(2)] as HSSFPictureData).Data)); sh = wb.GetSheet("Pictures"); dr = sh.CreateDrawingPatriarch(); Assert.AreEqual(3, ((HSSFPatriarch)dr).Children.Count); // forth picture byte[] data4 = new byte[] { 10, 11, 12 }; int idx4 = wb.AddPicture(data4, PictureType.JPEG); Assert.AreEqual(4, idx4); dr.CreatePicture(anchor, idx4); Assert.AreEqual(4, ((HSSFPatriarch)dr).Children.Count); Assert.IsTrue(Arrays.Equals(data1, ((HSSFPicture)((HSSFPatriarch)dr).Children[(0)]).PictureData.Data)); Assert.IsTrue(Arrays.Equals(data2, ((HSSFPicture)((HSSFPatriarch)dr).Children[(1)]).PictureData.Data)); Assert.IsTrue(Arrays.Equals(data3, ((HSSFPicture)((HSSFPatriarch)dr).Children[(2)]).PictureData.Data)); Assert.IsTrue(Arrays.Equals(data4, ((HSSFPicture)((HSSFPatriarch)dr).Children[(3)]).PictureData.Data)); wb = HSSFTestDataSamples.WriteOutAndReadBack((HSSFWorkbook)wb); IList lst4 = wb.GetAllPictures(); Assert.AreEqual(4, lst4.Count); Assert.IsTrue(Arrays.Equals(data1, (lst4[(0)] as HSSFPictureData).Data)); Assert.IsTrue(Arrays.Equals(data2, (lst4[(1)] as HSSFPictureData).Data)); Assert.IsTrue(Arrays.Equals(data3, (lst4[(2)] as HSSFPictureData).Data)); Assert.IsTrue(Arrays.Equals(data4, (lst4[(3)] as HSSFPictureData).Data)); sh = wb.GetSheet("Pictures"); dr = sh.CreateDrawingPatriarch(); Assert.AreEqual(4, ((HSSFPatriarch)dr).Children.Count); Assert.IsTrue(Arrays.Equals(data1, ((HSSFPicture)((HSSFPatriarch)dr).Children[(0)]).PictureData.Data)); Assert.IsTrue(Arrays.Equals(data2, ((HSSFPicture)((HSSFPatriarch)dr).Children[(1)]).PictureData.Data)); Assert.IsTrue(Arrays.Equals(data3, ((HSSFPicture)((HSSFPatriarch)dr).Children[(2)]).PictureData.Data)); Assert.IsTrue(Arrays.Equals(data4, ((HSSFPicture)((HSSFPatriarch)dr).Children[(3)]).PictureData.Data)); } [Test] public void BSEPictureRef() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sh = wb.CreateSheet("Pictures") as HSSFSheet; HSSFPatriarch dr = sh.CreateDrawingPatriarch() as HSSFPatriarch; HSSFClientAnchor anchor = new HSSFClientAnchor(); InternalSheet ish = HSSFTestHelper.GetSheetForTest(sh); //register a picture byte[] data1 = new byte[] { 1, 2, 3 }; int idx1 = wb.AddPicture(data1, PictureType.JPEG); Assert.AreEqual(1, idx1); HSSFPicture p1 = dr.CreatePicture(anchor, idx1) as HSSFPicture; EscherBSERecord bse = wb.Workbook.GetBSERecord(idx1); Assert.AreEqual(bse.Ref, 1); dr.CreatePicture(new HSSFClientAnchor(), idx1); Assert.AreEqual(bse.Ref, 2); HSSFShapeGroup gr = dr.CreateGroup(new HSSFClientAnchor()); gr.CreatePicture(new HSSFChildAnchor(), idx1); Assert.AreEqual(bse.Ref, 3); } [Test] public void ReadExistingImage() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("drawings.xls"); HSSFSheet sheet = wb.GetSheet("picture") as HSSFSheet; HSSFPatriarch Drawing = sheet.DrawingPatriarch as HSSFPatriarch; Assert.AreEqual(1, Drawing.Children.Count); HSSFPicture picture = (HSSFPicture)Drawing.Children[0]; Assert.AreEqual(picture.FileName, "test"); } [Test] public void SetGetProperties() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sh = wb.CreateSheet("Pictures") as HSSFSheet; HSSFPatriarch dr = sh.CreateDrawingPatriarch() as HSSFPatriarch; HSSFClientAnchor anchor = new HSSFClientAnchor(); //register a picture byte[] data1 = new byte[] { 1, 2, 3 }; int idx1 = wb.AddPicture(data1, PictureType.JPEG); HSSFPicture p1 = dr.CreatePicture(anchor, idx1) as HSSFPicture; Assert.AreEqual(p1.FileName, ""); p1.FileName = ("aaa"); Assert.AreEqual(p1.FileName, "aaa"); wb = HSSFTestDataSamples.WriteOutAndReadBack(wb); sh = wb.GetSheet("Pictures") as HSSFSheet; dr = sh.DrawingPatriarch as HSSFPatriarch; p1 = (HSSFPicture)dr.Children[0]; Assert.AreEqual(p1.FileName, "aaa"); } [Test] public void Bug49658() { // test if inserted EscherMetafileBlip will be read again IWorkbook wb = new HSSFWorkbook(); byte[] pictureDataEmf = POIDataSamples.GetDocumentInstance().ReadFile("vector_image.emf"); int indexEmf = wb.AddPicture(pictureDataEmf, PictureType.EMF); byte[] pictureDataPng = POIDataSamples.GetSpreadSheetInstance().ReadFile("logoKarmokar4.png"); int indexPng = wb.AddPicture(pictureDataPng, PictureType.PNG); byte[] pictureDataWmf = POIDataSamples.GetSlideShowInstance().ReadFile("santa.wmf"); int indexWmf = wb.AddPicture(pictureDataWmf, PictureType.WMF); ISheet sheet = wb.CreateSheet(); HSSFPatriarch patriarch = sheet.CreateDrawingPatriarch() as HSSFPatriarch; ICreationHelper ch = wb.GetCreationHelper(); IClientAnchor anchor = ch.CreateClientAnchor(); anchor.Col1 = (/*setter*/2); anchor.Col2 = (/*setter*/5); anchor.Row1 = (/*setter*/1); anchor.Row2 = (/*setter*/6); patriarch.CreatePicture(anchor, indexEmf); anchor = ch.CreateClientAnchor(); anchor.Col1 = (/*setter*/2); anchor.Col2 = (/*setter*/5); anchor.Row1 = (/*setter*/10); anchor.Row2 = (/*setter*/16); patriarch.CreatePicture(anchor, indexPng); anchor = ch.CreateClientAnchor(); anchor.Col1 = (/*setter*/6); anchor.Col2 = (/*setter*/9); anchor.Row1 = (/*setter*/1); anchor.Row2 = (/*setter*/6); patriarch.CreatePicture(anchor, indexWmf); wb = HSSFTestDataSamples.WriteOutAndReadBack(wb as HSSFWorkbook); byte[] pictureDataOut = (wb.GetAllPictures()[0] as HSSFPictureData).Data; Assert.IsTrue(Arrays.Equals(pictureDataEmf, pictureDataOut)); byte[] wmfNoHeader = new byte[pictureDataWmf.Length - 22]; Array.Copy(pictureDataWmf, 22, wmfNoHeader, 0, pictureDataWmf.Length - 22); pictureDataOut = (wb.GetAllPictures()[2] as HSSFPictureData).Data; Assert.IsTrue(Arrays.Equals(wmfNoHeader, pictureDataOut)); } } }
using System.IO; using UnityEngine; namespace InControl { public class TouchStickControl : TouchControl { [Header( "Position" )] [SerializeField] TouchControlAnchor anchor = TouchControlAnchor.BottomLeft; [SerializeField] TouchUnitType offsetUnitType = TouchUnitType.Percent; [SerializeField] Vector2 offset = new Vector2( 20.0f, 20.0f ); [SerializeField] TouchUnitType areaUnitType = TouchUnitType.Percent; [SerializeField] Rect activeArea = new Rect( 0.0f, 0.0f, 50.0f, 100.0f ); [Header( "Options" )] public AnalogTarget target = AnalogTarget.LeftStick; public SnapAngles snapAngles = SnapAngles.None; [Range( 0, 1 )] public float lowerDeadZone = 0.1f; [Range( 0, 1 )] public float upperDeadZone = 0.9f; public AnimationCurve inputCurve = AnimationCurve.Linear( 0.0f, 0.0f, 1.0f, 1.0f ); public bool allowDragging = false; public bool snapToInitialTouch = true; public bool resetWhenDone = true; public float resetDuration = 0.1f; [Header( "Sprites" )] public TouchSprite ring = new TouchSprite( 20.0f ); public TouchSprite knob = new TouchSprite( 10.0f ); public float knobRange = 7.5f; Vector3 resetPosition; Vector3 beganPosition; Vector3 movedPosition; float ringResetSpeed; float knobResetSpeed; Rect worldActiveArea; float worldKnobRange; Vector3 value; Vector3 snappedValue; Touch currentTouch; bool dirty; public override void CreateControl() { ring.Create( "Ring", transform, 1000 ); knob.Create( "Knob", transform, 1001 ); } public override void DestroyControl() { ring.Delete(); knob.Delete(); if (currentTouch != null) { TouchEnded( currentTouch ); currentTouch = null; } } public override void ConfigureControl() { resetPosition = OffsetToWorldPosition( anchor, offset, offsetUnitType, true ); transform.position = resetPosition; ring.Update( true ); knob.Update( true ); worldActiveArea = TouchManager.ConvertToWorld( activeArea, areaUnitType ); worldKnobRange = TouchManager.ConvertToWorld( knobRange, knob.SizeUnitType ); } public override void DrawGizmos() { ring.DrawGizmos( RingPosition, Color.yellow ); knob.DrawGizmos( KnobPosition, Color.yellow ); Utility.DrawCircleGizmo( RingPosition, worldKnobRange, Color.red ); Utility.DrawRectGizmo( worldActiveArea, Color.green ); } void Update() { if (dirty) { ConfigureControl(); dirty = false; } else { ring.Update(); knob.Update(); } if (IsNotActive) { if (resetWhenDone && KnobPosition != resetPosition) { var ringKnobDelta = KnobPosition - RingPosition; RingPosition = Vector3.MoveTowards( RingPosition, resetPosition, ringResetSpeed * Time.deltaTime ); KnobPosition = RingPosition + ringKnobDelta; } if (KnobPosition != RingPosition) { KnobPosition = Vector3.MoveTowards( KnobPosition, RingPosition, knobResetSpeed * Time.deltaTime ); } } } public override void SubmitControlState( ulong updateTick, float deltaTime ) { SubmitAnalogValue( target, snappedValue, lowerDeadZone, upperDeadZone, updateTick, deltaTime ); } public override void CommitControlState( ulong updateTick, float deltaTime ) { CommitAnalog( target ); } public override void TouchBegan( Touch touch ) { if (IsActive) { return; } beganPosition = TouchManager.ScreenToWorldPoint( touch.position ); var insideActiveArea = worldActiveArea.Contains( beganPosition ); var insideControl = ring.Contains( beganPosition ); if (snapToInitialTouch && (insideActiveArea || insideControl)) { RingPosition = beganPosition; KnobPosition = beganPosition; currentTouch = touch; } else if (insideControl) { KnobPosition = beganPosition; beganPosition = RingPosition; currentTouch = touch; } if (IsActive) { TouchMoved( touch ); ring.State = true; knob.State = true; } } public override void TouchMoved( Touch touch ) { if (currentTouch != touch) { return; } movedPosition = TouchManager.ScreenToWorldPoint( touch.position ); var vector = movedPosition - beganPosition; var normal = vector.normalized; var length = vector.magnitude; if (allowDragging) { var excess = length - worldKnobRange; if (excess < 0.0f) { excess = 0.0f; } beganPosition = beganPosition + (excess * normal); RingPosition = beganPosition; } movedPosition = beganPosition + (Mathf.Clamp( length, 0.0f, worldKnobRange ) * normal); value = (movedPosition - beganPosition) / worldKnobRange; value.x = inputCurve.Evaluate( Utility.Abs( value.x ) ) * Mathf.Sign( value.x ); value.y = inputCurve.Evaluate( Utility.Abs( value.y ) ) * Mathf.Sign( value.y ); if (snapAngles == SnapAngles.None) { snappedValue = value; KnobPosition = movedPosition; } else { snappedValue = SnapTo( value, snapAngles ); KnobPosition = beganPosition + (snappedValue * worldKnobRange); } RingPosition = beganPosition; } public override void TouchEnded( Touch touch ) { if (currentTouch != touch) { return; } value = Vector3.zero; snappedValue = Vector3.zero; var ringResetDelta = (resetPosition - RingPosition).magnitude; ringResetSpeed = Utility.IsZero( resetDuration ) ? ringResetDelta : (ringResetDelta / resetDuration); var knobResetDelta = (RingPosition - KnobPosition).magnitude; knobResetSpeed = Utility.IsZero( resetDuration ) ? knobRange : (knobResetDelta / resetDuration); currentTouch = null; ring.State = false; knob.State = false; } public bool IsActive { get { return currentTouch != null; } } public bool IsNotActive { get { return currentTouch == null; } } public Vector3 RingPosition { get { return ring.Ready ? ring.Position : transform.position; } set { if (ring.Ready) { ring.Position = value; } } } public Vector3 KnobPosition { get { return knob.Ready ? knob.Position : transform.position; } set { if (knob.Ready) { knob.Position = value; } } } public TouchControlAnchor Anchor { get { return anchor; } set { if (anchor != value) { anchor = value; dirty = true; } } } public Vector2 Offset { get { return offset; } set { if (offset != value) { offset = value; dirty = true; } } } public TouchUnitType OffsetUnitType { get { return offsetUnitType; } set { if (offsetUnitType != value) { offsetUnitType = value; dirty = true; } } } public Rect ActiveArea { get { return activeArea; } set { if (activeArea != value) { activeArea = value; dirty = true; } } } public TouchUnitType AreaUnitType { get { return areaUnitType; } set { if (areaUnitType != value) { areaUnitType = value; dirty = true; } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Discord; using Discord.Commands; using ImageSharp; using NadekoBot.Common; using NadekoBot.Common.Attributes; using NadekoBot.Core.Services; using NadekoBot.Extensions; using Image = ImageSharp.Image; namespace NadekoBot.Modules.Gambling { public partial class Gambling { [Group] public class DiceRollCommands : NadekoSubmodule { private static readonly Regex dndRegex = new Regex(@"^(?<n1>\d+)d(?<n2>\d+)(?:\+(?<add>\d+))?(?:\-(?<sub>\d+))?$", RegexOptions.Compiled); private static readonly Regex fudgeRegex = new Regex(@"^(?<n1>\d+)d(?:F|f)$", RegexOptions.Compiled); private static readonly char[] _fateRolls = { '-', ' ', '+' }; private readonly IImageCache _images; public DiceRollCommands(IDataCache data) { _images = data.LocalImages; } [NadekoCommand, Usage, Description, Aliases] public async Task Roll() { var rng = new NadekoRandom(); var gen = rng.Next(1, 101); var num1 = gen / 10; var num2 = gen % 10; var imageStream = await Task.Run(() => { var ms = new MemoryStream(); new[] { GetDice(num1), GetDice(num2) }.Merge().SaveAsPng(ms); ms.Position = 0; return ms; }).ConfigureAwait(false); await Context.Channel.SendFileAsync(imageStream, "dice.png", Context.User.Mention + " " + GetText("dice_rolled", Format.Code(gen.ToString()))).ConfigureAwait(false); } public enum RollOrderType { Ordered, Unordered } [NadekoCommand, Usage, Description, Aliases] [Priority(1)] public async Task Roll(int num) { await InternalRoll(num, true).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [Priority(1)] public async Task Rolluo(int num = 1) { await InternalRoll(num, false).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [Priority(0)] public async Task Roll(string arg) { await InternallDndRoll(arg, true).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [Priority(0)] public async Task Rolluo(string arg) { await InternallDndRoll(arg, false).ConfigureAwait(false); } private async Task InternalRoll(int num, bool ordered) { if (num < 1 || num > 30) { await ReplyErrorLocalized("dice_invalid_number", 1, 30).ConfigureAwait(false); return; } var rng = new NadekoRandom(); var dice = new List<Image<Rgba32>>(num); var values = new List<int>(num); for (var i = 0; i < num; i++) { var randomNumber = rng.Next(1, 7); var toInsert = dice.Count; if (ordered) { if (randomNumber == 6 || dice.Count == 0) toInsert = 0; else if (randomNumber != 1) for (var j = 0; j < dice.Count; j++) { if (values[j] < randomNumber) { toInsert = j; break; } } } else { toInsert = dice.Count; } dice.Insert(toInsert, GetDice(randomNumber)); values.Insert(toInsert, randomNumber); } var bitmap = dice.Merge(); var ms = new MemoryStream(); bitmap.SaveAsPng(ms); ms.Position = 0; await Context.Channel.SendFileAsync(ms, "dice.png", Context.User.Mention + " " + GetText("dice_rolled_num", Format.Bold(values.Count.ToString())) + " " + GetText("total_average", Format.Bold(values.Sum().ToString()), Format.Bold((values.Sum() / (1.0f * values.Count)).ToString("N2")))).ConfigureAwait(false); } private async Task InternallDndRoll(string arg, bool ordered) { Match match; if ((match = fudgeRegex.Match(arg)).Length != 0 && int.TryParse(match.Groups["n1"].ToString(), out int n1) && n1 > 0 && n1 < 500) { var rng = new NadekoRandom(); var rolls = new List<char>(); for (int i = 0; i < n1; i++) { rolls.Add(_fateRolls[rng.Next(0, _fateRolls.Length)]); } var embed = new EmbedBuilder().WithOkColor().WithDescription(Context.User.Mention + " " + GetText("dice_rolled_num", Format.Bold(n1.ToString()))) .AddField(efb => efb.WithName(Format.Bold("Result")) .WithValue(string.Join(" ", rolls.Select(c => Format.Code($"[{c}]"))))); await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } else if ((match = dndRegex.Match(arg)).Length != 0) { var rng = new NadekoRandom(); if (int.TryParse(match.Groups["n1"].ToString(), out n1) && int.TryParse(match.Groups["n2"].ToString(), out int n2) && n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0) { int.TryParse(match.Groups["add"].Value, out int add); int.TryParse(match.Groups["sub"].Value, out int sub); var arr = new int[n1]; for (int i = 0; i < n1; i++) { arr[i] = rng.Next(1, n2 + 1); } var sum = arr.Sum(); var embed = new EmbedBuilder().WithOkColor().WithDescription(Context.User.Mention + " " + GetText("dice_rolled_num", n1) + $"`1 - {n2}`") .AddField(efb => efb.WithName(Format.Bold("Rolls")) .WithValue(string.Join(" ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => Format.Code(x.ToString()))))) .AddField(efb => efb.WithName(Format.Bold("Sum")) .WithValue(sum + " + " + add + " - " + sub + " = " + (sum + add - sub))); await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] public async Task NRoll([Remainder] string range) { int rolled; if (range.Contains("-")) { var arr = range.Split('-') .Take(2) .Select(int.Parse) .ToArray(); if (arr[0] > arr[1]) { await ReplyErrorLocalized("second_larger_than_first").ConfigureAwait(false); return; } rolled = new NadekoRandom().Next(arr[0], arr[1] + 1); } else { rolled = new NadekoRandom().Next(0, int.Parse(range) + 1); } await ReplyConfirmLocalized("dice_rolled", Format.Bold(rolled.ToString())).ConfigureAwait(false); } private Image<Rgba32> GetDice(int num) { if (num < 0 || num > 10) throw new ArgumentOutOfRangeException(nameof(num)); if (num == 10) { var images = _images.Dice; using (var imgOneStream = images[1].ToStream()) using (var imgZeroStream = images[0].ToStream()) { var imgOne = Image.Load(imgOneStream); var imgZero = Image.Load(imgZeroStream); return new[] { imgOne, imgZero }.Merge(); } } using (var die = _images.Dice[num].ToStream()) { return Image.Load(die); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Basic scene object tests (create, read and delete but not update). /// </summary> [TestFixture] public class SceneObjectBasicTests : OpenSimTestCase { // [TearDown] // public void TearDown() // { // Console.WriteLine("TearDown"); // GC.Collect(); // Thread.Sleep(3000); // } // public class GcNotify // { // public static AutoResetEvent gcEvent = new AutoResetEvent(false); // private static bool _initialized = false; // // public static void Initialize() // { // if (!_initialized) // { // _initialized = true; // new GcNotify(); // } // } // // private GcNotify(){} // // ~GcNotify() // { // if (!Environment.HasShutdownStarted && // !AppDomain.CurrentDomain.IsFinalizingForUnload()) // { // Console.WriteLine("GcNotify called"); // gcEvent.Set(); // new GcNotify(); // } // } // } /// <summary> /// Test adding an object to a scene. /// </summary> [Test] public void TestAddSceneObject() { TestHelpers.InMethod(); Scene scene = new SceneHelpers().SetupScene(); int partsToTestCount = 3; SceneObjectGroup so = SceneHelpers.CreateSceneObject(partsToTestCount, TestHelpers.ParseTail(0x1), "obj1", 0x10); SceneObjectPart[] parts = so.Parts; Assert.That(scene.AddNewSceneObject(so, false), Is.True); SceneObjectGroup retrievedSo = scene.GetSceneObjectGroup(so.UUID); SceneObjectPart[] retrievedParts = retrievedSo.Parts; //m_log.Debug("retrievedPart : {0}", retrievedPart); // If the parts have the same UUID then we will consider them as one and the same Assert.That(retrievedSo.PrimCount, Is.EqualTo(partsToTestCount)); for (int i = 0; i < partsToTestCount; i++) { Assert.That(retrievedParts[i].Name, Is.EqualTo(parts[i].Name)); Assert.That(retrievedParts[i].UUID, Is.EqualTo(parts[i].UUID)); } } [Test] /// <summary> /// It shouldn't be possible to add a scene object if one with that uuid already exists in the scene. /// </summary> public void TestAddExistingSceneObjectUuid() { TestHelpers.InMethod(); Scene scene = new SceneHelpers().SetupScene(); string obj1Name = "Alfred"; string obj2Name = "Betty"; UUID objUuid = new UUID("00000000-0000-0000-0000-000000000001"); SceneObjectPart part1 = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = obj1Name, UUID = objUuid }; Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part1), false), Is.True); SceneObjectPart part2 = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = obj2Name, UUID = objUuid }; Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part2), false), Is.False); SceneObjectPart retrievedPart = scene.GetSceneObjectPart(objUuid); //m_log.Debug("retrievedPart : {0}", retrievedPart); // If the parts have the same UUID then we will consider them as one and the same Assert.That(retrievedPart.Name, Is.EqualTo(obj1Name)); Assert.That(retrievedPart.UUID, Is.EqualTo(objUuid)); } /// <summary> /// Test retrieving a scene object via the local id of one of its parts. /// </summary> [Test] public void TestGetSceneObjectByPartLocalId() { TestHelpers.InMethod(); Scene scene = new SceneHelpers().SetupScene(); int partsToTestCount = 3; SceneObjectGroup so = SceneHelpers.CreateSceneObject(partsToTestCount, TestHelpers.ParseTail(0x1), "obj1", 0x10); SceneObjectPart[] parts = so.Parts; scene.AddNewSceneObject(so, false); // Test getting via the root part's local id Assert.That(scene.GetGroupByPrim(so.LocalId), Is.Not.Null); // Test getting via a non root part's local id Assert.That(scene.GetGroupByPrim(parts[partsToTestCount - 1].LocalId), Is.Not.Null); // Test that we don't get back an object for a local id that doesn't exist Assert.That(scene.GetGroupByPrim(999), Is.Null); // Now delete the scene object and check again scene.DeleteSceneObject(so, false); Assert.That(scene.GetGroupByPrim(so.LocalId), Is.Null); Assert.That(scene.GetGroupByPrim(parts[partsToTestCount - 1].LocalId), Is.Null); } /// <summary> /// Test deleting an object from a scene. /// </summary> /// <remarks> /// This is the most basic form of delete. For all more sophisticated forms of derez (done asynchrnously /// and where object can be taken to user inventory, etc.), see SceneObjectDeRezTests. /// </remarks> [Test] public void TestDeleteSceneObject() { TestHelpers.InMethod(); TestScene scene = new SceneHelpers().SetupScene(); SceneObjectGroup so = SceneHelpers.AddSceneObject(scene); Assert.That(so.IsDeleted, Is.False); scene.DeleteSceneObject(so, false); Assert.That(so.IsDeleted, Is.True); SceneObjectPart retrievedPart = scene.GetSceneObjectPart(so.LocalId); Assert.That(retrievedPart, Is.Null); } /// <summary> /// Changing a scene object uuid changes the root part uuid. This is a valid operation if the object is not /// in a scene and is useful if one wants to supply a UUID directly rather than use the one generated by /// OpenSim. /// </summary> [Test] public void TestChangeSceneObjectUuid() { string rootPartName = "rootpart"; UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001"); string childPartName = "childPart"; UUID childPartUuid = new UUID("00000000-0000-0000-0001-000000000000"); SceneObjectPart rootPart = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = rootPartName, UUID = rootPartUuid }; SceneObjectPart linkPart = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = childPartName, UUID = childPartUuid }; SceneObjectGroup sog = new SceneObjectGroup(rootPart); sog.AddPart(linkPart); Assert.That(sog.UUID, Is.EqualTo(rootPartUuid)); Assert.That(sog.RootPart.UUID, Is.EqualTo(rootPartUuid)); Assert.That(sog.Parts.Length, Is.EqualTo(2)); UUID newRootPartUuid = new UUID("00000000-0000-0000-0000-000000000002"); sog.UUID = newRootPartUuid; Assert.That(sog.UUID, Is.EqualTo(newRootPartUuid)); Assert.That(sog.RootPart.UUID, Is.EqualTo(newRootPartUuid)); Assert.That(sog.Parts.Length, Is.EqualTo(2)); } } }
using System; using System.Collections; using System.IO; using System.Text; using Raksha.Bcpg; using Raksha.Bcpg.OpenPgp; using Raksha.Tests.Utilities; namespace Raksha.Tests.Bcpg.OpenPgp.Examples { /** * A simple utility class that creates clear signed files and verifies them. * <p> * To sign a file: ClearSignedFileProcessor -s fileName secretKey passPhrase. * </p> * <p> * To decrypt: ClearSignedFileProcessor -v fileName signatureFile publicKeyFile. * </p> */ public sealed class ClearSignedFileProcessor { private ClearSignedFileProcessor() { } private static int ReadInputLine( MemoryStream bOut, Stream fIn) { bOut.SetLength(0); int lookAhead = -1; int ch; while ((ch = fIn.ReadByte()) >= 0) { bOut.WriteByte((byte) ch); if (ch == '\r' || ch == '\n') { lookAhead = ReadPassedEol(bOut, ch, fIn); break; } } return lookAhead; } private static int ReadInputLine( MemoryStream bOut, int lookAhead, Stream fIn) { bOut.SetLength(0); int ch = lookAhead; do { bOut.WriteByte((byte) ch); if (ch == '\r' || ch == '\n') { lookAhead = ReadPassedEol(bOut, ch, fIn); break; } } while ((ch = fIn.ReadByte()) >= 0); if (ch < 0) { lookAhead = -1; } return lookAhead; } private static int ReadPassedEol( MemoryStream bOut, int lastCh, Stream fIn) { int lookAhead = fIn.ReadByte(); if (lastCh == '\r' && lookAhead == '\n') { bOut.WriteByte((byte) lookAhead); lookAhead = fIn.ReadByte(); } return lookAhead; } /* * verify a clear text signed file */ private static void VerifyFile( Stream inputStream, Stream keyIn, string resultName) { ArmoredInputStream aIn = new ArmoredInputStream(inputStream); Stream outStr = File.Create(resultName); // // write out signed section using the local line separator. // note: trailing white space needs to be removed from the end of // each line RFC 4880 Section 7.1 // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, aIn); byte[] lineSep = LineSeparator; if (lookAhead != -1 && aIn.IsClearText()) { byte[] line = lineOut.ToArray(); outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line)); outStr.Write(lineSep, 0, lineSep.Length); while (lookAhead != -1 && aIn.IsClearText()) { lookAhead = ReadInputLine(lineOut, lookAhead, aIn); line = lineOut.ToArray(); outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line)); outStr.Write(lineSep, 0, lineSep.Length); } } outStr.Close(); PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(keyIn); PgpObjectFactory pgpFact = new PgpObjectFactory(aIn); PgpSignatureList p3 = (PgpSignatureList) pgpFact.NextPgpObject(); PgpSignature sig = p3[0]; sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId)); // // read the input, making sure we ignore the last newline. // Stream sigIn = File.OpenRead(resultName); lookAhead = ReadInputLine(lineOut, sigIn); ProcessLine(sig, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, sigIn); sig.Update((byte) '\r'); sig.Update((byte) '\n'); ProcessLine(sig, lineOut.ToArray()); } while (lookAhead != -1); } sigIn.Close(); if (sig.Verify()) { Console.WriteLine("signature verified."); } else { Console.WriteLine("signature verification failed."); } } private static byte[] LineSeparator { get { return Encoding.ASCII.GetBytes(SimpleTest.NewLine); } } /* * create a clear text signed file. */ private static void SignFile( string fileName, Stream keyIn, Stream outputStream, char[] pass, string digestName) { HashAlgorithmTag digest; if (digestName.Equals("SHA256")) { digest = HashAlgorithmTag.Sha256; } else if (digestName.Equals("SHA384")) { digest = HashAlgorithmTag.Sha384; } else if (digestName.Equals("SHA512")) { digest = HashAlgorithmTag.Sha512; } else if (digestName.Equals("MD5")) { digest = HashAlgorithmTag.MD5; } else if (digestName.Equals("RIPEMD160")) { digest = HashAlgorithmTag.RipeMD160; } else { digest = HashAlgorithmTag.Sha1; } PgpSecretKey pgpSecKey = PgpExampleUtilities.ReadSecretKey(keyIn); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(pass); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string) enumerator.Current); sGen.SetHashedSubpackets(spGen.Generate()); } Stream fIn = File.OpenRead(fileName); ArmoredOutputStream aOut = new ArmoredOutputStream(outputStream); aOut.BeginClearText(digest); // // note the last \n/\r/\r\n in the file is ignored // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, fIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, fIn); sGen.Update((byte) '\r'); sGen.Update((byte) '\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); } while (lookAhead != -1); } fIn.Close(); aOut.EndClearText(); BcpgOutputStream bOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bOut); aOut.Close(); } private static void ProcessLine( PgpSignature sig, byte[] line) { // note: trailing white space needs to be removed from the end of // each line for signature calculation RFC 4880 Section 7.1 int length = GetLengthWithoutWhiteSpace(line); if (length > 0) { sig.Update(line, 0, length); } } private static void ProcessLine( Stream aOut, PgpSignatureGenerator sGen, byte[] line) { int length = GetLengthWithoutWhiteSpace(line); if (length > 0) { sGen.Update(line, 0, length); } aOut.Write(line, 0, line.Length); } private static int GetLengthWithoutSeparatorOrTrailingWhitespace(byte[] line) { int end = line.Length - 1; while (end >= 0 && IsWhiteSpace(line[end])) { end--; } return end + 1; } private static bool IsLineEnding( byte b) { return b == '\r' || b == '\n'; } private static int GetLengthWithoutWhiteSpace( byte[] line) { int end = line.Length - 1; while (end >= 0 && IsWhiteSpace(line[end])) { end--; } return end + 1; } private static bool IsWhiteSpace( byte b) { return IsLineEnding(b) || b == '\t' || b == ' '; } public static int Main( string[] args) { if (args[0].Equals("-s")) { Stream fis = File.OpenRead(args[2]); Stream fos = File.Create(args[1] + ".asc"); Stream keyIn = PgpUtilities.GetDecoderStream(fis); string digestName = (args.Length == 4) ? "SHA1" : args[4]; SignFile(args[1], keyIn, fos, args[3].ToCharArray(), digestName); fis.Close(); fos.Close(); } else if (args[0].Equals("-v")) { if (args[1].IndexOf(".asc") < 0) { Console.Error.WriteLine("file needs to end in \".asc\""); return 1; } Stream fin = File.OpenRead(args[1]); Stream fis = File.OpenRead(args[2]); Stream keyIn = PgpUtilities.GetDecoderStream(fis); VerifyFile(fin, keyIn, args[1].Substring(0, args[1].Length - 4)); fin.Close(); fis.Close(); } else { Console.Error.WriteLine("usage: ClearSignedFileProcessor [-s file keyfile passPhrase]|[-v sigFile keyFile]"); } return 0; } } }
/** * Copyright 2016 Dartmouth-Hitchcock * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Xml; using Legion.Core.Exceptions; namespace Legion.Core.Services { /// <summary> /// Parameter types known to ParameterSet /// </summary> public enum ParameterType { /// <summary> /// Boolean /// </summary> Bool, /// <summary> /// Double /// </summary> Double, /// <summary> /// DateTime /// </summary> DateTime, /// <summary> /// Integer /// </summary> Int, /// <summary> /// No type /// </summary> None, /// <summary> /// String (Default) /// </summary> String, /// <summary> /// Xml /// </summary> Xml } /// <summary> /// Manages paramters passed into a service /// </summary> public class ParameterSet { private Dictionary<string, string> _params; private Dictionary<string, Parameter> _parsedParams = new Dictionary<string, Parameter>(StringComparer.OrdinalIgnoreCase); #region operator overloads /// <summary> /// Gets a raw parameter value /// </summary> /// <param name="key">the key to get</param> /// <returns>a raw string parameter value</returns> public string this[string key] { get { return _params[key]; } } #endregion #region accessors /// <summary> /// The raw dictionary of unparsed parameters /// </summary> public Dictionary<string, string> Parameters { get { return _params; } } #endregion #region constructors /// <summary> /// Constructor /// </summary> /// <param name="p">The Dictionary of parameters from the service request</param> public ParameterSet(Dictionary<string, string> p) { if (p.Comparer != StringComparer.OrdinalIgnoreCase) { try { _params = new Dictionary<string, string>(p, StringComparer.OrdinalIgnoreCase); } catch (ArgumentException) { _params = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach(KeyValuePair<string, string> kvp in p) _params[kvp.Key] = kvp.Value; } } else _params = p; } #endregion #region gets /// <summary> /// Gets a bool parameter value /// </summary> /// <param name="key">the key to get</param> /// <returns>a parsed bool from the ParameterSet</returns> public bool GetBool(string key) { if (!TryParse(ParameterType.Bool, key)) throw new ParameterTypeException(ParameterType.Bool, key); return (bool)_parsedParams[key].Value; } /// <summary> /// Gets a DateTime parameter value /// </summary> /// <param name="key">the key to get</param> /// <returns>a parsed DateTime object from the ParameterSet</returns> public DateTime GetDateTime(string key) { if (!TryParse(ParameterType.DateTime, key)) throw new ParameterTypeException(ParameterType.DateTime, key); return (DateTime)_parsedParams[key].Value; } /// <summary> /// Gets a double parameter value /// </summary> /// <param name="key">the key to get</param> /// <returns>a parsed double from the ParameterSet</returns> public double GetDouble(string key) { if (!TryParse(ParameterType.Double, key)) throw new ParameterTypeException(ParameterType.Double, key); return (double)_parsedParams[key].Value; } /// <summary> /// Gets a int parameter value /// </summary> /// <param name="key">the key to get</param> /// <returns>a parsed int from the ParameterSet</returns> public int GetInt(string key) { if (!TryParse(ParameterType.Int, key)) throw new ParameterTypeException(ParameterType.Int, key); return (int)_parsedParams[key].Value; } /// <summary> /// Gets a string parameter value /// </summary> /// <param name="key">the key to get</param> /// <returns>a parsed string object from the ParameterSet</returns> public string GetString(string key) { if (!TryParse(ParameterType.String, key)) throw new ParameterTypeException(ParameterType.String, key); return (string)_parsedParams[key].Value; } /// <summary> /// Gets an XML parameter value /// </summary> /// <param name="key">the key to get</param> /// <returns>a parsed XML object from the ParameterSet</returns> public XmlDocument GetXml(string key) { if (!TryParse(ParameterType.Xml, key)) throw new ParameterTypeException(ParameterType.Xml, key); return (XmlDocument)_parsedParams[key].Value; } #endregion #region verification /// <summary> /// Verifies that one of the keys in the specified list is present in the ParameterSet /// </summary> /// <param name="keys">The list of keys to verify</param> /// <returns>true if one of the keys is found, false otherwise</returns> public bool Verify(List<string> keys) { return this.Verify(keys.ToArray()); } /// <summary> /// Verifies that one of the keys in the specified array is present in the ParameterSet /// </summary> /// <param name="keys">The array of keys to verify</param> /// <returns>true if one of the keys is found, false otherwise</returns> public bool Verify(string[] keys) { return this.Verify(new ParameterVerificationGroup(keys, true)); } /// <summary> /// Verifies an array of ParameterVerificationGroups against the ParameterSet /// </summary> /// <param name="pvgs">The ParameterVerificationGroups to verify</param> /// <returns>true if all of the ParameterVerificationGroups verified, false otherwise</returns> public bool Verify(ParameterVerificationGroup[] pvgs) { foreach (ParameterVerificationGroup pvg in pvgs) if (!this.Verify(pvg)) return false; return true; } /// <summary> /// Verifies a ParameterVerificationGroup against the ParameterSet /// </summary> /// <param name="pvg">The ParameterVerificationGroup to verify</param> /// <returns>true if the ParameterVerificationGroup verifies, false otherwise</returns> public bool Verify(ParameterVerificationGroup pvg) { int count = 0; foreach (string key in pvg.Keys) { if (pvg.IsParameterRequired) { if (!_params.ContainsKey(key)) continue; if (pvg.IsValueRequired && _params[key].Length == 0) continue; if (_params[key].Length > 0 && !TryParse(pvg.GetParameterType(key), key)) continue; } else { if (_params.ContainsKey(key)) { if (pvg.IsValueRequired && _params[key].Length == 0) continue; if (_params[key].Length > 0 && !TryParse(pvg.GetParameterType(key), key)) continue; } } if (++count >= pvg.MinimumValidParameters) return true; } return (count < pvg.MinimumValidParameters ? false : true); } #endregion #region parsing private bool TryParse(ParameterType type, string key) { bool valid = false; if (_parsedParams.ContainsKey(key) && _parsedParams[key].Type == type) valid = true; else { if (_params.ContainsKey(key)) { switch (type) { case ParameterType.None: case ParameterType.String: _parsedParams[key] = new Parameter(ParameterType.String, _params[key]); valid = true; break; case ParameterType.Bool: bool tpBool; if (Boolean.TryParse(_params[key], out tpBool)) { _parsedParams[key] = new Parameter(ParameterType.Bool, tpBool); valid = true; } break; case ParameterType.DateTime: DateTime tpDateTime; if (DateTime.TryParse(_params[key], out tpDateTime)) { _parsedParams[key] = new Parameter(ParameterType.DateTime, tpDateTime); valid = true; } break; case ParameterType.Double: double tpDouble; if (Double.TryParse(_params[key], out tpDouble)) { _parsedParams[key] = new Parameter(ParameterType.Double, tpDouble); valid = true; } break; case ParameterType.Int: int tpInt; if (Int32.TryParse(_params[key], out tpInt)) { _parsedParams[key] = new Parameter(ParameterType.Int, tpInt); valid = true; } break; case ParameterType.Xml: XmlDocument dom = new XmlDocument(); try { dom.LoadXml(_params[key]); _parsedParams[key] = new Parameter(ParameterType.Xml, dom); valid = true; } catch (Exception) { } break; default: return false; } } } return valid; } #endregion /// <summary> /// Checks if the parameter set contains the specified key /// </summary> /// <param name="key">the key to check for</param> /// <returns>true if the key is found, false otherwise</returns> public bool ContainsKey(string key) { return _params.ContainsKey(key); } /// <summary> /// Checks if a parameter is of the specified type /// </summary> /// <param name="type">the type to check for</param> /// <param name="key">the key of the parameter to look for</param> /// <returns>true if the parameter is of the specified type, false otherwise</returns> public bool CheckParameterType(ParameterType type, string key) { return TryParse(type, key); } /// <summary> /// Get a string representation of this ParameterSet /// </summary> /// <returns>Get a string representation of this ParameterSet</returns> public override string ToString() { string s = string.Empty; foreach (KeyValuePair<string, string> kvp in _params) s += string.Format("{0}: {1}\n\n", kvp.Key, (Settings.GetArray("ParameterSetLoggingHiddenParameters").Any(p => kvp.Key.ToLower().Contains(p)) ? "********" : kvp.Value)); return s; } /// <summary> /// Get an XML representation of this ParameterSet /// </summary> /// <returns>an XML representation of this ParameterSet</returns> public XmlDocument ToXml(){ string key, val; XmlDocument dom = new XmlDocument(); XmlElement parameter, root = (XmlElement)dom.AppendChild(dom.CreateElement("parameters")); SortedDictionary<string, string> sortedParams = new SortedDictionary<string,string>(_params, StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, string> kvp in sortedParams) { if (kvp.Key.Length <= 2 || kvp.Key.Substring(0, 2) != "__") { key = kvp.Key.ToLower(); val = (Settings.GetArray("ParameterSetLoggingHiddenParameters").Any(p => kvp.Key.ToLower().Contains(p)) ? "********" : kvp.Value); try { parameter = (XmlElement)root.AppendChild(dom.CreateElement(key)); parameter.AppendChild(dom.CreateCDataSection(val)); } catch (XmlException) { parameter = (XmlElement)root.AppendChild(dom.CreateElement("parameter")); parameter.SetAttribute("badname", "true"); parameter.AppendChild(dom.CreateElement("key")).AppendChild(dom.CreateCDataSection(key)); parameter.AppendChild(dom.CreateElement("value")).AppendChild(dom.CreateCDataSection(val)); } } } return dom; } /// <summary> /// Computes the SHA256 hash of the ParameterSet /// </summary> /// <returns></returns> public byte[] GetHash() { SHA256Managed crypt = new SHA256Managed(); return crypt.ComputeHash(Encoding.UTF8.GetBytes(ToXml().OuterXml)); } private class Parameter { public object Value; public ParameterType Type; public Parameter(ParameterType type, object value) { Value = value; Type = type; } } } }
// Copyright 2018 Esri. // // 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 Android.App; using Android.OS; using Android.Widget; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using Esri.ArcGISRuntime.UI.GeoAnalysis; using System; using System.Timers; using ArcGISRuntime.Samples.Managers; using Android.Views; namespace ArcGISRuntime.Samples.LineOfSightGeoElement { [Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("3af5cfec0fd24dac8d88aea679027cb9")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Line of sight (geoelement)", category: "Analysis", description: "Show a line of sight between two moving objects.", instructions: "A line of sight will display between a point on the Empire State Building (observer) and a taxi (target).", tags: new[] { "3D", "line of sight", "visibility", "visibility analysis" })] public class LineOfSightGeoElement : Activity { // Hold a reference to the SceneView private SceneView _mySceneView; // Hold the label that will show the analysis status private TextView _myStatusLabel; // Hold the slider that will control observer height private SeekBar _myHeightSlider; // URL of the elevation service - provides elevation component of the scene private readonly Uri _elevationUri = new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"); // URL of the building service - provides builidng models private readonly Uri _buildingsUri = new Uri("https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/New_York_LoD2_3D_Buildings/SceneServer/layers/0"); // Starting point of the observation point private readonly MapPoint _observerPoint = new MapPoint(-73.984988, 40.748131, 20, SpatialReferences.Wgs84); // Graphic to represent the observation point private Graphic _observerGraphic; // Graphic to represent the observed target private Graphic _taxiGraphic; // Line of Sight Analysis private GeoElementLineOfSight _geoLine; // For taxi animation - four points in a loop private readonly MapPoint[] _points = { new MapPoint(-73.984513, 40.748469, SpatialReferences.Wgs84), new MapPoint(-73.985068, 40.747786, SpatialReferences.Wgs84), new MapPoint(-73.983452, 40.747091, SpatialReferences.Wgs84), new MapPoint(-73.982961, 40.747762, SpatialReferences.Wgs84) }; // For taxi animation - tracks animation state private int _pointIndex = 0; private int _frameIndex = 0; private readonly int _frameMax = 150; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Line of sight (GeoElement)"; // Create the UI, setup the control references and execute initialization CreateLayout(); Initialize(); } private async void Initialize() { // Create scene Scene myScene = new Scene(Basemap.CreateImageryWithLabels()) { InitialViewpoint = new Viewpoint(_observerPoint, 1600) }; // Set initial viewpoint // Create the elevation source ElevationSource myElevationSource = new ArcGISTiledElevationSource(_elevationUri); // Add the elevation source to the scene myScene.BaseSurface.ElevationSources.Add(myElevationSource); // Create the building scene layer ArcGISSceneLayer mySceneLayer = new ArcGISSceneLayer(_buildingsUri); // Add the building layer to the scene myScene.OperationalLayers.Add(mySceneLayer); // Add the observer to the scene // Create a graphics overlay with relative surface placement; relative surface placement allows the Z position of the observation point to be adjusted GraphicsOverlay overlay = new GraphicsOverlay() { SceneProperties = new LayerSceneProperties(SurfacePlacement.Relative) }; // Create the symbol that will symbolize the observation point SimpleMarkerSceneSymbol symbol = new SimpleMarkerSceneSymbol(SimpleMarkerSceneSymbolStyle.Sphere, System.Drawing.Color.Red, 10, 10, 10, SceneSymbolAnchorPosition.Bottom); // Create the observation point graphic from the point and symbol _observerGraphic = new Graphic(_observerPoint, symbol); // Add the observer to the overlay overlay.Graphics.Add(_observerGraphic); // Add the overlay to the scene _mySceneView.GraphicsOverlays.Add(overlay); try { // Add the taxi to the scene // Create the model symbol for the taxi ModelSceneSymbol taxiSymbol = await ModelSceneSymbol.CreateAsync(new Uri(GetModelUri())); // Set the anchor position for the mode; ensures that the model appears above the ground taxiSymbol.AnchorPosition = SceneSymbolAnchorPosition.Bottom; // Create the graphic from the taxi starting point and the symbol _taxiGraphic = new Graphic(_points[0], taxiSymbol); // Add the taxi graphic to the overlay overlay.Graphics.Add(_taxiGraphic); // Create GeoElement Line of sight analysis (taxi to building) // Create the analysis _geoLine = new GeoElementLineOfSight(_observerGraphic, _taxiGraphic) { TargetOffsetZ = 2 }; // Apply an offset to the target. This helps avoid some false negatives // Create the analysis overlay AnalysisOverlay myAnalysisOverlay = new AnalysisOverlay(); // Add the analysis to the overlay myAnalysisOverlay.Analyses.Add(_geoLine); // Add the analysis overlay to the scene _mySceneView.AnalysisOverlays.Add(myAnalysisOverlay); // Create a timer; this will enable animating the taxi Timer timer = new Timer(60); // Move the taxi every time the timer expires timer.Elapsed += AnimationTimer_Elapsed; // Keep the timer running continuously timer.AutoReset = true; // Start the timer timer.Start(); // Subscribe to TargetVisible events; allows for updating the UI and selecting the taxi when it is visible _geoLine.TargetVisibilityChanged += Geoline_TargetVisibilityChanged; // Add the scene to the view _mySceneView.Scene = myScene; } catch (Exception e) { new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show(); } } private void AnimationTimer_Elapsed(object sender, EventArgs e) { // Note: the contents of this function are solely related to animating the taxi // Increment the frame counter _frameIndex++; // Reset the frame counter once one segment of the path has been travelled if (_frameIndex == _frameMax) { _frameIndex = 0; // Start navigating toward the next point _pointIndex++; // Restart if finished circuit if (_pointIndex == _points.Length) { _pointIndex = 0; } } // Get the point the taxi is travelling from MapPoint starting = _points[_pointIndex]; // Get the point the taxi is travelling to MapPoint ending = _points[(_pointIndex + 1) % _points.Length]; // Calculate the progress based on the current frame double progress = _frameIndex / (double)_frameMax; // Calculate the position of the taxi when it is {progress}% of the way through MapPoint intermediatePoint = InterpolatedPoint(starting, ending, progress); // Update the taxi geometry _taxiGraphic.Geometry = intermediatePoint; // Update the taxi rotation. GeodeticDistanceResult distance = GeometryEngine.DistanceGeodetic(starting, ending, LinearUnits.Meters, AngularUnits.Degrees, GeodeticCurveType.Geodesic); ((ModelSceneSymbol)_taxiGraphic.Symbol).Heading = distance.Azimuth1; } private MapPoint InterpolatedPoint(MapPoint firstPoint, MapPoint secondPoint, double progress) { // This function returns a MapPoint that is the result of travelling {progress}% of the way from {firstPoint} to {secondPoint} // Get the difference between the two points MapPoint difference = new MapPoint(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y, secondPoint.Z - firstPoint.Z, SpatialReferences.Wgs84); // Scale the difference by the progress towards the destination MapPoint scaled = new MapPoint(difference.X * progress, difference.Y * progress, difference.Z * progress); // Add the scaled progress to the starting point return new MapPoint(firstPoint.X + scaled.X, firstPoint.Y + scaled.Y, firstPoint.Z + scaled.Z); } private void Geoline_TargetVisibilityChanged(object sender, EventArgs e) { // This is needed because Runtime delivers notifications from a different thread that doesn't have access to UI controls RunOnUiThread(UpdateUiAndSelection); } private void UpdateUiAndSelection() { switch (_geoLine.TargetVisibility) { case LineOfSightTargetVisibility.Obstructed: _myStatusLabel.Text = "Status: Obstructed"; _taxiGraphic.IsSelected = false; break; case LineOfSightTargetVisibility.Visible: _myStatusLabel.Text = "Status: Visible"; _taxiGraphic.IsSelected = true; break; default: case LineOfSightTargetVisibility.Unknown: _myStatusLabel.Text = "Status: Unknown"; _taxiGraphic.IsSelected = false; break; } } private static string GetModelUri() { // Returns the taxi model return DataManager.GetDataFolder("3af5cfec0fd24dac8d88aea679027cb9", "dolmus.3ds"); } private void CreateLayout() { // Create a new vertical layout for the app LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Create the controls _myHeightSlider = new SeekBar(this) { Max = 100 }; _myStatusLabel = new TextView(this) { Text = "Status: " }; // Subscribe to height slider changes _myHeightSlider.ProgressChanged += MyHeightSlider_ProgressChanged; // Add the views to the layout layout.AddView(_myStatusLabel); layout.AddView(_myHeightSlider); _mySceneView = new SceneView(this); layout.AddView(_mySceneView); // Show the layout in the app SetContentView(layout); } private void MyHeightSlider_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { // Update the height of the observer based on the slider value // Constrain the min and max to 20 and 150 units double minHeight = 20; double maxHeight = 150; // Scale the slider value; its default range is 0-10 double value = e.Progress / 100.0; // Get the current point MapPoint oldPoint = (MapPoint)_observerGraphic.Geometry; // Create a new point with the same (x,y) but updated z MapPoint newPoint = new MapPoint(oldPoint.X, oldPoint.Y, (maxHeight - minHeight) * value + minHeight); // Apply the updated geometry to the observer point _observerGraphic.Geometry = newPoint; } protected override void OnDestroy() { base.OnDestroy(); // Remove the sceneview (_mySceneView.Parent as ViewGroup).RemoveView(_mySceneView); _mySceneView.Dispose(); _mySceneView = null; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using SharpCompress.Archive; using SharpCompress.Common; using SharpCompress.IO; namespace SharpCompress { internal static class Utility { public static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T> items) { return new ReadOnlyCollection<T>(items.ToList()); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static int URShift(int number, int bits) { if (number >= 0) return number >> bits; else return (number >> bits) + (2 << ~bits); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static int URShift(int number, long bits) { return URShift(number, (int)bits); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static long URShift(long number, int bits) { if (number >= 0) return number >> bits; else return (number >> bits) + (2L << ~bits); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static long URShift(long number, long bits) { return URShift(number, (int)bits); } /// <summary> /// Fills the array with an specific value from an specific index to an specific index. /// </summary> /// <param name="array">The array to be filled.</param> /// <param name="fromindex">The first index to be filled.</param> /// <param name="toindex">The last index to be filled.</param> /// <param name="val">The value to fill the array with.</param> public static void Fill<T>(T[] array, int fromindex, int toindex, T val) where T : struct { if (array.Length == 0) { throw new NullReferenceException(); } if (fromindex > toindex) { throw new ArgumentException(); } if ((fromindex < 0) || ((System.Array)array).Length < toindex) { throw new IndexOutOfRangeException(); } for (int index = (fromindex > 0) ? fromindex-- : fromindex; index < toindex; index++) { array[index] = val; } } /// <summary> /// Fills the array with an specific value. /// </summary> /// <param name="array">The array to be filled.</param> /// <param name="val">The value to fill the array with.</param> public static void Fill<T>(T[] array, T val) where T : struct { Fill(array, 0, array.Length, val); } public static void SetSize(this List<byte> list, int count) { if (count > list.Count) { for (int i = list.Count; i < count; i++) { list.Add(0x0); } } else { byte[] temp = new byte[count]; list.CopyTo(temp, 0); list.Clear(); list.AddRange(temp); } } /// <summary> Read a int value from the byte array at the given position (Big Endian) /// /// </summary> /// <param name="array">the array to read from /// </param> /// <param name="pos">the offset /// </param> /// <returns> the value /// </returns> public static int readIntBigEndian(byte[] array, int pos) { int temp = 0; temp |= array[pos] & 0xff; temp <<= 8; temp |= array[pos + 1] & 0xff; temp <<= 8; temp |= array[pos + 2] & 0xff; temp <<= 8; temp |= array[pos + 3] & 0xff; return temp; } /// <summary> Read a short value from the byte array at the given position (little /// Endian) /// /// </summary> /// <param name="array">the array to read from /// </param> /// <param name="pos">the offset /// </param> /// <returns> the value /// </returns> public static short readShortLittleEndian(byte[] array, int pos) { return BitConverter.ToInt16(array, pos); } /// <summary> Read an int value from the byte array at the given position (little /// Endian) /// /// </summary> /// <param name="array">the array to read from /// </param> /// <param name="pos">the offset /// </param> /// <returns> the value /// </returns> public static int readIntLittleEndian(byte[] array, int pos) { return BitConverter.ToInt32(array, pos); } /// <summary> Write an int value into the byte array at the given position (Big endian) /// /// </summary> /// <param name="array">the array /// </param> /// <param name="pos">the offset /// </param> /// <param name="value">the value to write /// </param> public static void writeIntBigEndian(byte[] array, int pos, int value) { array[pos] = (byte)((Utility.URShift(value, 24)) & 0xff); array[pos + 1] = (byte)((Utility.URShift(value, 16)) & 0xff); array[pos + 2] = (byte)((Utility.URShift(value, 8)) & 0xff); array[pos + 3] = (byte)((value) & 0xff); } /// <summary> Write a short value into the byte array at the given position (little /// endian) /// /// </summary> /// <param name="array">the array /// </param> /// <param name="pos">the offset /// </param> /// <param name="value">the value to write /// </param> public static void WriteLittleEndian(byte[] array, int pos, short value) { byte[] newBytes = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) Array.Reverse(newBytes); Array.Copy(newBytes, 0, array, pos, newBytes.Length); } /// <summary> Increment a short value at the specified position by the specified amount /// (little endian). /// </summary> public static void incShortLittleEndian(byte[] array, int pos, short incrementValue) { short existingValue = BitConverter.ToInt16(array, pos); existingValue += incrementValue; WriteLittleEndian(array, pos, existingValue); //int c = Utility.URShift(((array[pos] & 0xff) + (dv & 0xff)), 8); //array[pos] = (byte)(array[pos] + (dv & 0xff)); //if ((c > 0) || ((dv & 0xff00) != 0)) //{ // array[pos + 1] = (byte)(array[pos + 1] + ((Utility.URShift(dv, 8)) & 0xff) + c); //} } /// <summary> Write an int value into the byte array at the given position (little /// endian) /// /// </summary> /// <param name="array">the array /// </param> /// <param name="pos">the offset /// </param> /// <param name="value">the value to write /// </param> public static void WriteLittleEndian(byte[] array, int pos, int value) { byte[] newBytes = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) Array.Reverse(newBytes); Array.Copy(newBytes, 0, array, pos, newBytes.Length); } public static void Initialize<T>(this T[] array, Func<T> func) { for (int i = 0; i < array.Length; i++) { array[i] = func(); } } public static void AddRange<T>(this ICollection<T> destination, IEnumerable<T> source) { foreach (T item in source) { destination.Add(item); } } public static void ForEach<T>(this IEnumerable<T> items, Action<T> action) { foreach (T item in items) { action(item); } } public static IEnumerable<T> AsEnumerable<T>(this T item) { yield return item; } public static void CheckNotNull(this object obj, string name) { if (obj == null) { throw new ArgumentNullException(name); } } public static void CheckNotNullOrEmpty(this string obj, string name) { obj.CheckNotNull(name); if (obj.Length == 0) { throw new ArgumentException("String is empty."); } } public static void Skip(this Stream source, long advanceAmount) { byte[] buffer = new byte[32 * 1024]; int read = 0; int readCount = 0; do { readCount = buffer.Length; if (readCount > advanceAmount) { readCount = (int)advanceAmount; } read = source.Read(buffer, 0, readCount); if (read < 0) { break; } advanceAmount -= read; if (advanceAmount == 0) { break; } } while (true); } public static void SkipAll(this Stream source) { byte[] buffer = new byte[32 * 1024]; do { } while (source.Read(buffer, 0, buffer.Length) == buffer.Length); } public static byte[] UInt32ToBigEndianBytes(uint x) { return new byte[] { (byte) ((x >> 24) & 0xff), (byte) ((x >> 16) & 0xff), (byte) ((x >> 8) & 0xff), (byte) (x & 0xff) }; } public static DateTime DosDateToDateTime(UInt16 iDate, UInt16 iTime) { int year = iDate / 512 + 1980; int month = iDate % 512 / 32; int day = iDate % 512 % 32; int hour = iTime / 2048; int minute = iTime % 2048 / 32; int second = iTime % 2048 % 32 * 2; if (iDate == UInt16.MaxValue || month == 0 || day == 0) { year = 1980; month = 1; day = 1; } if (iTime == UInt16.MaxValue) { hour = minute = second = 0; } DateTime dt; try { dt = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Local); } catch { dt = new DateTime(); } return dt; } public static uint DateTimeToDosTime(this DateTime? dateTime) { if (dateTime == null) { return 0; } var localDateTime = dateTime.Value.ToLocalTime(); return (uint)( (localDateTime.Second / 2) | (localDateTime.Minute << 5) | (localDateTime.Hour << 11) | (localDateTime.Day << 16) | (localDateTime.Month << 21) | ((localDateTime.Year - 1980) << 25)); } public static DateTime DosDateToDateTime(UInt32 iTime) { return DosDateToDateTime((UInt16)(iTime / 65536), (UInt16)(iTime % 65536)); } public static DateTime DosDateToDateTime(Int32 iTime) { return DosDateToDateTime((UInt32)iTime); } public static long TransferTo(this Stream source, Stream destination) { byte[] array = new byte[81920]; int count; long total = 0; while ((count = source.Read(array, 0, array.Length)) != 0) { total += count; destination.Write(array, 0, count); } return total; } public static bool ReadFully(this Stream stream, byte[] buffer) { int total = 0; int read; while ((read = stream.Read(buffer, total, buffer.Length - total)) > 0) { total += read; if (total >= buffer.Length) { return true; } } return (total >= buffer.Length); } public static string TrimNulls(this string source) { return source.Replace('\0', ' ').Trim(); } public static bool BinaryEquals(this byte[] source, byte[] target) { if (source.Length != target.Length) { return false; } for (int i = 0; i < source.Length; ++i) { if (source[i] != target[i]) { return false; } } return true; } #if PORTABLE || NETFX_CORE public static void CopyTo(this byte[] array, byte[] destination, int index) { Array.Copy(array, 0, destination, index, array.Length); } public static long HostToNetworkOrder(long host) { return (int)((long)HostToNetworkOrder((int)host) & unchecked((long)(unchecked((ulong)-1))) << 32 | ((long)HostToNetworkOrder((int)((int)host >> 32)) & unchecked((long)(unchecked((ulong)-1))))); } public static int HostToNetworkOrder(int host) { return (int)((int)(HostToNetworkOrder((short)host) & -1) << 16 | (HostToNetworkOrder((short)(host >> 16)) & -1)); } public static short HostToNetworkOrder(short host) { return (short)((int)(host & 255) << 8 | ((int)host >> 8 & 255)); } public static long NetworkToHostOrder(long network) { return HostToNetworkOrder(network); } public static int NetworkToHostOrder(int network) { return HostToNetworkOrder(network); } public static short NetworkToHostOrder(short network) { return HostToNetworkOrder(network); } #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.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.IO { // Class for creating FileStream objects, and some basic file management // routines such as Delete, etc. public static class File { private static Encoding s_UTF8NoBOM; internal const int DefaultBufferSize = 4096; public static StreamReader OpenText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); return new StreamReader(path); } public static StreamWriter CreateText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); return new StreamWriter(path, append: false); } public static StreamWriter AppendText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); return new StreamWriter(path, append: true); } // Copies an existing file to a new file. An exception is raised if the // destination file already exists. Use the // Copy(string, string, boolean) method to allow // overwriting an existing file. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName and Create // and Write permissions to destFileName. // public static void Copy(string sourceFileName, string destFileName) { if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName); if (destFileName == null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (sourceFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName)); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); Contract.EndContractBlock(); InternalCopy(sourceFileName, destFileName, false); } // Copies an existing file to a new file. If overwrite is // false, then an IOException is thrown if the destination file // already exists. If overwrite is true, the file is // overwritten. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName // and Write permissions to destFileName. // public static void Copy(string sourceFileName, string destFileName, bool overwrite) { if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName); if (destFileName == null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (sourceFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName)); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); Contract.EndContractBlock(); InternalCopy(sourceFileName, destFileName, overwrite); } /// <devdoc> /// Note: This returns the fully qualified name of the destination file. /// </devdoc> [System.Security.SecuritySafeCritical] internal static string InternalCopy(string sourceFileName, string destFileName, bool overwrite) { Debug.Assert(sourceFileName != null); Debug.Assert(destFileName != null); Debug.Assert(sourceFileName.Length > 0); Debug.Assert(destFileName.Length > 0); string fullSourceFileName = Path.GetFullPath(sourceFileName); string fullDestFileName = Path.GetFullPath(destFileName); FileSystem.Current.CopyFile(fullSourceFileName, fullDestFileName, overwrite); return fullDestFileName; } // Creates a file in a particular path. If the file exists, it is replaced. // The file is opened with ReadWrite access and cannot be opened by another // application until it has been closed. An IOException is thrown if the // directory specified doesn't exist. // // Your application must have Create, Read, and Write permissions to // the file. // public static FileStream Create(string path) { return Create(path, DefaultBufferSize); } // Creates a file in a particular path. If the file exists, it is replaced. // The file is opened with ReadWrite access and cannot be opened by another // application until it has been closed. An IOException is thrown if the // directory specified doesn't exist. // // Your application must have Create, Read, and Write permissions to // the file. // public static FileStream Create(string path, int bufferSize) { return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize); } public static FileStream Create(string path, int bufferSize, FileOptions options) { return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, options); } // Deletes a file. The file specified by the designated path is deleted. // If the file does not exist, Delete succeeds without throwing // an exception. // // On NT, Delete will fail for a file that is open for normal I/O // or a file that is memory mapped. // // Your application must have Delete permission to the target file. // [System.Security.SecuritySafeCritical] public static void Delete(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); string fullPath = Path.GetFullPath(path); FileSystem.Current.DeleteFile(fullPath); } // Tests if a file exists. The result is true if the file // given by the specified path exists; otherwise, the result is // false. Note that if path describes a directory, // Exists will return true. // // Your application must have Read permission for the target directory. // [System.Security.SecuritySafeCritical] public static bool Exists(string path) { try { if (path == null) return false; if (path.Length == 0) return false; path = Path.GetFullPath(path); // After normalizing, check whether path ends in directory separator. // Otherwise, FillAttributeInfo removes it and we may return a false positive. // GetFullPath should never return null Debug.Assert(path != null, "File.Exists: GetFullPath returned null"); if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1])) { return false; } return InternalExists(path); } catch (ArgumentException) { } catch (NotSupportedException) { } // Security can throw this on ":" catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } [System.Security.SecurityCritical] // auto-generated internal static bool InternalExists(string path) { return FileSystem.Current.FileExists(path); } public static FileStream Open(string path, FileMode mode) { return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None); } public static FileStream Open(string path, FileMode mode, FileAccess access) { return Open(path, mode, access, FileShare.None); } public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share) { return new FileStream(path, mode, access, share); } internal static DateTimeOffset GetUtcDateTimeOffset(DateTime dateTime) { // File and Directory UTC APIs treat a DateTimeKind.Unspecified as UTC whereas // ToUniversalTime treats this as local. if (dateTime.Kind == DateTimeKind.Unspecified) { return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); } return dateTime.ToUniversalTime(); } public static void SetCreationTime(string path, DateTime creationTime) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetCreationTime(fullPath, creationTime, asDirectory: false); } public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetCreationTime(fullPath, GetUtcDateTimeOffset(creationTimeUtc), asDirectory: false); } [System.Security.SecuritySafeCritical] public static DateTime GetCreationTime(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetCreationTime(fullPath).LocalDateTime; } [System.Security.SecuritySafeCritical] // auto-generated public static DateTime GetCreationTimeUtc(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetCreationTime(fullPath).UtcDateTime; } public static void SetLastAccessTime(string path, DateTime lastAccessTime) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: false); } public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastAccessTime(fullPath, GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: false); } [System.Security.SecuritySafeCritical] public static DateTime GetLastAccessTime(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetLastAccessTime(fullPath).LocalDateTime; } [System.Security.SecuritySafeCritical] // auto-generated public static DateTime GetLastAccessTimeUtc(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetLastAccessTime(fullPath).UtcDateTime; } public static void SetLastWriteTime(string path, DateTime lastWriteTime) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: false); } public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastWriteTime(fullPath, GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: false); } [System.Security.SecuritySafeCritical] public static DateTime GetLastWriteTime(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetLastWriteTime(fullPath).LocalDateTime; } [System.Security.SecuritySafeCritical] // auto-generated public static DateTime GetLastWriteTimeUtc(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetLastWriteTime(fullPath).UtcDateTime; } [System.Security.SecuritySafeCritical] public static FileAttributes GetAttributes(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetAttributes(fullPath); } [System.Security.SecurityCritical] public static void SetAttributes(string path, FileAttributes fileAttributes) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetAttributes(fullPath, fileAttributes); } [System.Security.SecuritySafeCritical] public static FileStream OpenRead(string path) { return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); } public static FileStream OpenWrite(string path) { return new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); } [System.Security.SecuritySafeCritical] // auto-generated public static string ReadAllText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); return InternalReadAllText(path, Encoding.UTF8); } [System.Security.SecuritySafeCritical] // auto-generated public static string ReadAllText(string path, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); return InternalReadAllText(path, encoding); } [System.Security.SecurityCritical] private static string InternalReadAllText(string path, Encoding encoding) { Debug.Assert(path != null); Debug.Assert(encoding != null); Debug.Assert(path.Length > 0); using (StreamReader sr = new StreamReader(path, encoding, detectEncodingFromByteOrderMarks: true)) return sr.ReadToEnd(); } [System.Security.SecuritySafeCritical] // auto-generated public static void WriteAllText(string path, string contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); using (StreamWriter sw = new StreamWriter(path)) { sw.Write(contents); } } [System.Security.SecuritySafeCritical] // auto-generated public static void WriteAllText(string path, string contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); using (StreamWriter sw = new StreamWriter(path, false, encoding)) { sw.Write(contents); } } [System.Security.SecuritySafeCritical] // auto-generated public static byte[] ReadAllBytes(string path) { return InternalReadAllBytes(path); } [System.Security.SecurityCritical] private static byte[] InternalReadAllBytes(string path) { // bufferSize == 1 used to avoid unnecessary buffer in FileStream using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1)) { long fileLength = fs.Length; if (fileLength > int.MaxValue) throw new IOException(SR.IO_FileTooLong2GB); int index = 0; int count = (int)fileLength; byte[] bytes = new byte[count]; while (count > 0) { int n = fs.Read(bytes, index, count); if (n == 0) throw Error.GetEndOfFile(); index += n; count -= n; } return bytes; } } [System.Security.SecuritySafeCritical] // auto-generated public static void WriteAllBytes(string path, byte[] bytes) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (bytes == null) throw new ArgumentNullException(nameof(bytes)); Contract.EndContractBlock(); InternalWriteAllBytes(path, bytes); } [System.Security.SecurityCritical] private static void InternalWriteAllBytes(string path, byte[] bytes) { Debug.Assert(path != null); Debug.Assert(path.Length != 0); Debug.Assert(bytes != null); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) { fs.Write(bytes, 0, bytes.Length); } } public static string[] ReadAllLines(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); return InternalReadAllLines(path, Encoding.UTF8); } public static string[] ReadAllLines(string path, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); return InternalReadAllLines(path, encoding); } private static string[] InternalReadAllLines(string path, Encoding encoding) { Debug.Assert(path != null); Debug.Assert(encoding != null); Debug.Assert(path.Length != 0); string line; List<string> lines = new List<string>(); using (StreamReader sr = new StreamReader(path, encoding)) while ((line = sr.ReadLine()) != null) lines.Add(line); return lines.ToArray(); } public static IEnumerable<string> ReadLines(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); return ReadLinesIterator.CreateIterator(path, Encoding.UTF8); } public static IEnumerable<string> ReadLines(string path, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); return ReadLinesIterator.CreateIterator(path, encoding); } public static void WriteAllLines(string path, string[] contents) { WriteAllLines(path, (IEnumerable<string>)contents); } public static void WriteAllLines(string path, IEnumerable<string> contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); InternalWriteAllLines(new StreamWriter(path), contents); } public static void WriteAllLines(string path, string[] contents, Encoding encoding) { WriteAllLines(path, (IEnumerable<string>)contents, encoding); } public static void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); InternalWriteAllLines(new StreamWriter(path, false, encoding), contents); } private static void InternalWriteAllLines(TextWriter writer, IEnumerable<string> contents) { Debug.Assert(writer != null); Debug.Assert(contents != null); using (writer) { foreach (string line in contents) { writer.WriteLine(line); } } } public static void AppendAllText(string path, string contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); using (StreamWriter sw = new StreamWriter(path, append: true)) { sw.Write(contents); } } public static void AppendAllText(string path, string contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); using (StreamWriter sw = new StreamWriter(path, true, encoding)) { sw.Write(contents); } } public static void AppendAllLines(string path, IEnumerable<string> contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); InternalWriteAllLines(new StreamWriter(path, append: true), contents); } public static void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); Contract.EndContractBlock(); InternalWriteAllLines(new StreamWriter(path, true, encoding), contents); } public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors: false); } public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName)); if (destinationFileName == null) throw new ArgumentNullException(nameof(destinationFileName)); FileSystem.Current.ReplaceFile( Path.GetFullPath(sourceFileName), Path.GetFullPath(destinationFileName), destinationBackupFileName != null ? Path.GetFullPath(destinationBackupFileName) : null, ignoreMetadataErrors); } // Moves a specified file to a new location and potentially a new file name. // This method does work across volumes. // // The caller must have certain FileIOPermissions. The caller must // have Read and Write permission to // sourceFileName and Write // permissions to destFileName. // [System.Security.SecuritySafeCritical] public static void Move(string sourceFileName, string destFileName) { if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName); if (destFileName == null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (sourceFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName)); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); Contract.EndContractBlock(); string fullSourceFileName = Path.GetFullPath(sourceFileName); string fullDestFileName = Path.GetFullPath(destFileName); if (!InternalExists(fullSourceFileName)) { throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, fullSourceFileName), fullSourceFileName); } FileSystem.Current.MoveFile(fullSourceFileName, fullDestFileName); } public static void Encrypt(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); // TODO: Not supported on Unix or in WinRt, and the EncryptFile API isn't currently // available in OneCore. For now, we just throw PNSE everywhere. When the API is // available, we can put this into the FileSystem abstraction and implement it // properly for Win32. throw new PlatformNotSupportedException(SR.PlatformNotSupported_FileEncryption); } public static void Decrypt(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); // TODO: Not supported on Unix or in WinRt, and the EncryptFile API isn't currently // available in OneCore. For now, we just throw PNSE everywhere. When the API is // available, we can put this into the FileSystem abstraction and implement it // properly for Win32. throw new PlatformNotSupportedException(SR.PlatformNotSupported_FileEncryption); } // UTF-8 without BOM and with error detection. Same as the default encoding for StreamWriter. private static Encoding UTF8NoBOM => s_UTF8NoBOM ?? (s_UTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); // If we use the path-taking constructors we will not have FileOptions.Asynchronous set and // we will have asynchronous file access faked by the thread pool. We want the real thing. private static StreamReader AsyncStreamReader(string path, Encoding encoding) { FileStream stream = new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); return new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true); } private static StreamWriter AsyncStreamWriter(string path, Encoding encoding, bool append) { FileStream stream = new FileStream( path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); return new StreamWriter(stream, encoding); } public static Task<string> ReadAllTextAsync(string path, CancellationToken cancellationToken = default(CancellationToken)) => ReadAllTextAsync(path, Encoding.UTF8, cancellationToken); public static Task<string> ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled<string>(cancellationToken) : InternalReadAllTextAsync(path, encoding, cancellationToken); } private static async Task<string> InternalReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(encoding != null); char[] buffer = null; StringBuilder sb = null; StreamReader sr = AsyncStreamReader(path, encoding); try { cancellationToken.ThrowIfCancellationRequested(); sb = StringBuilderCache.Acquire(); buffer = ArrayPool<char>.Shared.Rent(sr.CurrentEncoding.GetMaxCharCount(DefaultBufferSize)); for (;;) { int read = await sr.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); if (read == 0) { return sb.ToString(); } sb.Append(buffer, 0, read); cancellationToken.ThrowIfCancellationRequested(); } } finally { sr.Dispose(); if (buffer != null) { ArrayPool<char>.Shared.Return(buffer); } if (sb != null) { StringBuilderCache.Release(sb); } } } public static Task WriteAllTextAsync(string path, string contents, CancellationToken cancellationToken = default(CancellationToken)) => WriteAllTextAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task WriteAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (string.IsNullOrEmpty(contents)) { new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read).Dispose(); return Task.CompletedTask; } return InternalWriteAllTextAsync(AsyncStreamWriter(path, encoding, append: false), contents, cancellationToken); } public static Task<byte[]> ReadAllBytesAsync(string path, CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<byte[]>(cancellationToken); } FileStream fs = new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); bool returningInternalTask = false; try { long fileLength = fs.Length; if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<byte[]>(cancellationToken); } if (fileLength > int.MaxValue) { return Task.FromException<byte[]>(new IOException(SR.IO_FileTooLong2GB)); } if (fileLength == 0) { return Task.FromResult(Array.Empty<byte>()); } returningInternalTask = true; return InternalReadAllBytesAsync(fs, (int)fileLength, cancellationToken); } finally { if (!returningInternalTask) { fs.Dispose(); } } } private static async Task<byte[]> InternalReadAllBytesAsync(FileStream fs, int count, CancellationToken cancellationToken) { using (fs) { int index = 0; byte[] bytes = new byte[count]; do { int n = await fs.ReadAsync(bytes, index, count - index, cancellationToken).ConfigureAwait(false); if (n == 0) { throw Error.GetEndOfFile(); } index += n; } while (index < count); return bytes; } } public static Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (bytes == null) throw new ArgumentNullException(nameof(bytes)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : InternalWriteAllBytesAsync(path, bytes, cancellationToken); } private static async Task InternalWriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(bytes != null); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan)) { await fs.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false); await fs.FlushAsync(cancellationToken).ConfigureAwait(false); } } public static Task<string[]> ReadAllLinesAsync(string path, CancellationToken cancellationToken = default(CancellationToken)) => ReadAllLinesAsync(path, Encoding.UTF8, cancellationToken); public static Task<string[]> ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled<string[]>(cancellationToken) : InternalReadAllLinesAsync(path, encoding, cancellationToken); } private static async Task<string[]> InternalReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(encoding != null); using (StreamReader sr = AsyncStreamReader(path, encoding)) { cancellationToken.ThrowIfCancellationRequested(); string line; List<string> lines = new List<string>(); while ((line = await sr.ReadLineAsync().ConfigureAwait(false)) != null) { lines.Add(line); cancellationToken.ThrowIfCancellationRequested(); } return lines.ToArray(); } } public static Task WriteAllLinesAsync(string path, IEnumerable<string> contents, CancellationToken cancellationToken = default(CancellationToken)) => WriteAllLinesAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task WriteAllLinesAsync(string path, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : InternalWriteAllLinesAsync(AsyncStreamWriter(path, encoding, append: false), contents, cancellationToken); } private static async Task InternalWriteAllLinesAsync(TextWriter writer, IEnumerable<string> contents, CancellationToken cancellationToken) { Debug.Assert(writer != null); Debug.Assert(contents != null); using (writer) { foreach (string line in contents) { cancellationToken.ThrowIfCancellationRequested(); // Note that this working depends on the fix to #14563, and cannot be ported without // either also porting that fix, or explicitly checking for line being null. await writer.WriteLineAsync(line).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); await writer.FlushAsync().ConfigureAwait(false); } } private static async Task InternalWriteAllTextAsync(StreamWriter sw, string contents, CancellationToken cancellationToken) { char[] buffer = null; try { buffer = ArrayPool<char>.Shared.Rent(DefaultBufferSize); int count = contents.Length; int index = 0; while (index < count) { int batchSize = Math.Min(DefaultBufferSize, count - index); contents.CopyTo(index, buffer, 0, batchSize); cancellationToken.ThrowIfCancellationRequested(); await sw.WriteAsync(buffer, 0, batchSize).ConfigureAwait(false); index += batchSize; } cancellationToken.ThrowIfCancellationRequested(); await sw.FlushAsync().ConfigureAwait(false); } finally { sw.Dispose(); if (buffer != null) { ArrayPool<char>.Shared.Return(buffer); } } } public static Task AppendAllTextAsync(string path, string contents, CancellationToken cancellationToken = default(CancellationToken)) => AppendAllTextAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task AppendAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (string.IsNullOrEmpty(contents)) { // Just to throw exception if there is a problem opening the file. new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read).Dispose(); return Task.CompletedTask; } return InternalWriteAllTextAsync(AsyncStreamWriter(path, encoding, append: true), contents, cancellationToken); } public static Task AppendAllLinesAsync(string path, IEnumerable<string> contents, CancellationToken cancellationToken = default(CancellationToken)) => AppendAllLinesAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task AppendAllLinesAsync(string path, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : InternalWriteAllLinesAsync(AsyncStreamWriter(path, encoding, append: true), contents, cancellationToken); } } }
/* * CP20280.cs - IBM EBCDIC (Italy) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-280.ucm". namespace I18N.Rare { using System; using I18N.Common; public class CP20280 : ByteEncoding { public CP20280() : base(20280, ToChars, "IBM EBCDIC (Italy)", "IBM280", "IBM280", "IBM280", false, false, false, false, 1252) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009', '\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087', '\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D', '\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089', '\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007', '\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095', '\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B', '\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0', '\u00E2', '\u00E4', '\u007B', '\u00E1', '\u00E3', '\u00E5', '\u005C', '\u00F1', '\u00B0', '\u002E', '\u003C', '\u0028', '\u002B', '\u0021', '\u0026', '\u005D', '\u00EA', '\u00EB', '\u007D', '\u00ED', '\u00EE', '\u00EF', '\u007E', '\u00DF', '\u00E9', '\u0024', '\u002A', '\u0029', '\u003B', '\u005E', '\u002D', '\u002F', '\u00C2', '\u00C4', '\u00C0', '\u00C1', '\u00C3', '\u00C5', '\u00C7', '\u00D1', '\u00F2', '\u002C', '\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u00C9', '\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF', '\u00CC', '\u00F9', '\u003A', '\u00A3', '\u00A7', '\u0027', '\u003D', '\u0022', '\u00D8', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1', '\u005B', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA', '\u00E6', '\u00B8', '\u00C6', '\u00A4', '\u00B5', '\u00EC', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD', '\u00DE', '\u00AE', '\u00A2', '\u0023', '\u00A5', '\u00B7', '\u00A9', '\u0040', '\u00B6', '\u00BC', '\u00BD', '\u00BE', '\u00AC', '\u007C', '\u00AF', '\u00A8', '\u00B4', '\u00D7', '\u00E0', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4', '\u00F6', '\u00A6', '\u00F3', '\u00F5', '\u00E8', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u00B9', '\u00FB', '\u00FC', '\u0060', '\u00FA', '\u00FF', '\u00E7', '\u00F7', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u00B2', '\u00D4', '\u00D6', '\u00D2', '\u00D3', '\u00D5', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB', '\u00DC', '\u00D9', '\u00DA', '\u009F', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0x4F; break; case 0x0022: ch = 0x7F; break; case 0x0023: ch = 0xB1; break; case 0x0024: ch = 0x5B; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0xB5; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0x90; break; case 0x005C: ch = 0x48; break; case 0x005D: ch = 0x51; break; case 0x005E: ch = 0x5F; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0xDD; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0x44; break; case 0x007C: ch = 0xBB; break; case 0x007D: ch = 0x54; break; case 0x007E: ch = 0x58; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0xB0; break; case 0x00A3: ch = 0x7B; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0xCD; break; case 0x00A7: ch = 0x7C; break; case 0x00A8: ch = 0xBD; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0xBA; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xBC; break; case 0x00B0: ch = 0x4A; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0xA0; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x68; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D0: ch = 0xAC; break; case 0x00D1: ch = 0x69; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0xEC; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0xFC; break; case 0x00DD: ch = 0xAD; break; case 0x00DE: ch = 0xAE; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0xC0; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0xE0; break; case 0x00E8: ch = 0xD0; break; case 0x00E9: ch = 0x5A; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0xA1; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F0: ch = 0x8C; break; case 0x00F1: ch = 0x49; break; case 0x00F2: ch = 0x6A; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xCC; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0x79; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xDC; break; case 0x00FD: ch = 0x8D; break; case 0x00FE: ch = 0x8E; break; case 0x00FF: ch = 0xDF; break; case 0x0110: ch = 0xAC; break; case 0x203E: ch = 0xBC; break; case 0xFF01: ch = 0x4F; break; case 0xFF02: ch = 0x7F; break; case 0xFF03: ch = 0xB1; break; case 0xFF04: ch = 0x5B; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0xB5; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0x90; break; case 0xFF3C: ch = 0x48; break; case 0xFF3D: ch = 0x51; break; case 0xFF3E: ch = 0x5F; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0xDD; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0x44; break; case 0xFF5C: ch = 0xBB; break; case 0xFF5D: ch = 0x54; break; case 0xFF5E: ch = 0x58; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0x4F; break; case 0x0022: ch = 0x7F; break; case 0x0023: ch = 0xB1; break; case 0x0024: ch = 0x5B; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0xB5; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0x90; break; case 0x005C: ch = 0x48; break; case 0x005D: ch = 0x51; break; case 0x005E: ch = 0x5F; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0xDD; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0x44; break; case 0x007C: ch = 0xBB; break; case 0x007D: ch = 0x54; break; case 0x007E: ch = 0x58; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0xB0; break; case 0x00A3: ch = 0x7B; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0xCD; break; case 0x00A7: ch = 0x7C; break; case 0x00A8: ch = 0xBD; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0xBA; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xBC; break; case 0x00B0: ch = 0x4A; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0xA0; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x68; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D0: ch = 0xAC; break; case 0x00D1: ch = 0x69; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0xEC; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0xFC; break; case 0x00DD: ch = 0xAD; break; case 0x00DE: ch = 0xAE; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0xC0; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0xE0; break; case 0x00E8: ch = 0xD0; break; case 0x00E9: ch = 0x5A; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0xA1; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F0: ch = 0x8C; break; case 0x00F1: ch = 0x49; break; case 0x00F2: ch = 0x6A; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xCC; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0x79; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xDC; break; case 0x00FD: ch = 0x8D; break; case 0x00FE: ch = 0x8E; break; case 0x00FF: ch = 0xDF; break; case 0x0110: ch = 0xAC; break; case 0x203E: ch = 0xBC; break; case 0xFF01: ch = 0x4F; break; case 0xFF02: ch = 0x7F; break; case 0xFF03: ch = 0xB1; break; case 0xFF04: ch = 0x5B; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0xB5; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0x90; break; case 0xFF3C: ch = 0x48; break; case 0xFF3D: ch = 0x51; break; case 0xFF3E: ch = 0x5F; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0xDD; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0x44; break; case 0xFF5C: ch = 0xBB; break; case 0xFF5D: ch = 0x54; break; case 0xFF5E: ch = 0x58; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP20280 public class ENCibm280 : CP20280 { public ENCibm280() : base() {} }; // class ENCibm280 }; // namespace I18N.Rare
using System; using System.IO; using NUnit.Framework; namespace Mercurial.Tests { [TestFixture] public class SummaryTests : MergeResolveTests { [Test] [Category("Integration")] public void Summary_NoRepository_ThrowsMercurialExecutionException() { Assert.Throws<MercurialExecutionException>(() => Repo.Summary()); } [Test] [Category("Integration")] public void Summary_InitializedRepo_HasNoNewChangesets() { Repo.Init(); RepositorySummary summary = Repo.Summary(); Assert.That(summary.NumberOfNewChangesets, Is.EqualTo(0)); } [Test] [Category("Integration")] public void Summary_InitializedRepo_ContainsRawOutput() { Repo.Init(); RepositorySummary summary = Repo.Summary(); Assert.That(summary.RawOutput, Is.StringContaining("(clean)")); } [Test] [Category("Integration")] public void Summary_RepoAtHeadMinusOne_HasOneNewChangeset() { CreateRepoWithTwoChangesets(); Repo.Update(0); RepositorySummary summary = Repo.Summary(); Assert.That(summary.NumberOfNewChangesets, Is.EqualTo(1)); } [Test] [Category("Integration")] public void Summary_RepoAtHeadMinusOne_UpdateIsPossible() { CreateRepoWithTwoChangesets(); Repo.Update(0); RepositorySummary summary = Repo.Summary(); Assert.That(summary.UpdatePossible, Is.True); } [Test] [Category("Integration")] public void Summary_InitializedRepo_ReportsDefaultBranch() { Repo.Init(); RepositorySummary summary = Repo.Summary(); Assert.That(summary.Branch, Is.EqualTo("default")); } [Test] [Category("Integration")] public void Summary_NewButUncommittedBranchChange_ReturnsNewBranchName() { Repo.Init(); Repo.Branch("newbranch"); RepositorySummary summary = Repo.Summary(); Assert.That(summary.Branch, Is.EqualTo("newbranch")); } [Test] [Category("Integration")] public void Summary_InitializedRepo_ReportsNullParent() { Repo.Init(); RepositorySummary summary = Repo.Summary(); CollectionAssert.AreEqual( new[] { -1, }, summary.ParentRevisionNumbers); } [Test] [Category("Integration")] public void Summary_RepoAtChangesetZero_ReportsParentIsZero() { CreateRepoWithTwoChangesets(); Repo.Update(0); RepositorySummary summary = Repo.Summary(); CollectionAssert.AreEqual( new[] { 0, }, summary.ParentRevisionNumbers); } [Test] [Category("Integration")] public void Summary_InitializedRepo_ReportsNoModifiedFiles() { Repo.Init(); RepositorySummary summary = Repo.Summary(); Assert.That(summary.NumberOfModifiedFiles, Is.EqualTo(0)); } [Test] [Category("Integration")] public void Summary_NewFile_ReportsUnknownFile() { Repo.Init(); File.WriteAllText(Path.Combine(Repo.Path, "dummy.txt"), "dummy"); RepositorySummary summary = Repo.Summary(); Assert.That(summary.NumberOfUnknownFiles, Is.EqualTo(1)); } [Test] [Category("Integration")] public void Summary_ChangeToTrackedFile_ReportsModifiedFile() { Repo.Init(); WriteTextFileAndCommit(Repo, "dummy.txt", "123", "123", true); File.WriteAllText(Path.Combine(Repo.Path, "dummy.txt"), "dummy"); RepositorySummary summary = Repo.Summary(); Assert.That(summary.NumberOfModifiedFiles, Is.EqualTo(1)); } [Test] [Category("Integration")] public void Summary_InitializedRepo_ReportsNoUnknownFiles() { Repo.Init(); RepositorySummary summary = Repo.Summary(); Assert.That(summary.NumberOfUnknownFiles, Is.EqualTo(0)); } [Test] [Category("Integration")] public void Summary_InitializedRepo_ReportsNoUnresolvedFiles() { Repo.Init(); RepositorySummary summary = Repo.Summary(); Assert.That(summary.NumberOfUnresolvedFiles, Is.EqualTo(0)); } [Test] [Category("Integration")] public void Summary_InitializedRepo_ReportsNotInMerge() { Repo.Init(); RepositorySummary summary = Repo.Summary(); Assert.That(summary.IsInMerge, Is.False); } [Test] [Category("Integration")] public void Summary_MergeWithConflicts_ReportsConflicts() { CreateRepositoryWithMergeConflicts(); try { Repo.Merge(new MergeCommand() .WithMergeTool(MergeTools.InternalMerge)); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); } RepositorySummary summary = Repo.Summary(); Assert.That(summary.NumberOfUnresolvedFiles, Is.EqualTo(1)); } [Test] [Category("Integration")] public void Summary_Merge_ReportsInMerge() { CreateRepositoryWithMergeConflicts(); try { Repo.Merge(new MergeCommand() .WithMergeTool(MergeTools.InternalMerge)); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); } RepositorySummary summary = Repo.Summary(); Assert.That(summary.IsInMerge, Is.True); } [Test] [Category("Integration")] public void Summary_Merge_ReportsCorrectParents() { CreateRepositoryWithMergeConflicts(); try { Repo.Merge(new MergeCommand() .WithMergeTool(MergeTools.InternalMerge)); } catch (NotSupportedException) { Assert.Inconclusive("Merge tool not supported in this version"); } RepositorySummary summary = Repo.Summary(); CollectionAssert.AreEqual(new[] { 2, 1 }, summary.ParentRevisionNumbers); } private void CreateRepoWithTwoChangesets() { Repo.Init(); WriteTextFileAndCommit(Repo, "dummy.txt", "1", "1", true); WriteTextFileAndCommit(Repo, "dummy.txt", "2", "2", false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Expressions.Tests { public static class AsNullableTests { #region Test methods [Fact] public static void CheckNullableEnumAsEnumTypeTest() { E?[] array = new E?[] { null, (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }; for (int i = 0; i < array.Length; i++) { VerifyNullableEnumAsEnumType(array[i]); } } [Fact] public static void CheckNullableEnumAsObjectTest() { E?[] array = new E?[] { null, (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }; for (int i = 0; i < array.Length; i++) { VerifyNullableEnumAsObject(array[i]); } } [Fact] public static void CheckNullableIntAsObjectTest() { int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyNullableIntAsObject(array[i]); } } [Fact] public static void CheckNullableIntAsValueTypeTest() { int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyNullableIntAsValueType(array[i]); } } [Fact] public static void CheckNullableStructAsIEquatableOfStructTest() { S?[] array = new S?[] { null, default(S), new S() }; for (int i = 0; i < array.Length; i++) { VerifyNullableStructAsIEquatableOfStruct(array[i]); } } [Fact] public static void CheckNullableStructAsObjectTest() { S?[] array = new S?[] { null, default(S), new S() }; for (int i = 0; i < array.Length; i++) { VerifyNullableStructAsObject(array[i]); } } [Fact] public static void CheckNullableStructAsValueTypeTest() { S?[] array = new S?[] { null, default(S), new S() }; for (int i = 0; i < array.Length; i++) { VerifyNullableStructAsValueType(array[i]); } } [Fact] public static void ConvertGenericWithStructRestrictionCastObjectAsEnum() { CheckGenericWithStructRestrictionAsObjectHelper<E>(); } [Fact] public static void ConvertGenericWithStructRestrictionCastObjectAsStruct() { CheckGenericWithStructRestrictionAsObjectHelper<S>(); } [Fact] public static void ConvertGenericWithStructRestrictionCastObjectAsStructWithStringAndField() { CheckGenericWithStructRestrictionAsObjectHelper<Scs>(); } [Fact] public static void ConvertGenericWithStructRestrictionCastValueTypeAsEnum() { CheckGenericWithStructRestrictionAsValueTypeHelper<E>(); } [Fact] public static void ConvertGenericWithStructRestrictionCastValueTypeAsStruct() { CheckGenericWithStructRestrictionAsValueTypeHelper<S>(); } [Fact] public static void ConvertGenericWithStructRestrictionCastValueTypeAsStructWithStringAndField() { CheckGenericWithStructRestrictionAsValueTypeHelper<Scs>(); } #endregion #region Generic helpers private static void CheckGenericWithStructRestrictionAsObjectHelper<Ts>() where Ts : struct { Ts[] array = new Ts[] { default(Ts), new Ts() }; for (int i = 0; i < array.Length; i++) { VerifyGenericWithStructRestrictionAsObject<Ts>(array[i]); } } private static void CheckGenericWithStructRestrictionAsValueTypeHelper<Ts>() where Ts : struct { Ts[] array = new Ts[] { default(Ts), new Ts() }; for (int i = 0; i < array.Length; i++) { VerifyGenericWithStructRestrictionAsValueType<Ts>(array[i]); } } #endregion #region Test verifiers private static void VerifyNullableEnumAsEnumType(E? value) { Expression<Func<Enum>> e = Expression.Lambda<Func<Enum>>( Expression.TypeAs(Expression.Constant(value, typeof(E?)), typeof(Enum)), Enumerable.Empty<ParameterExpression>()); Func<Enum> f = e.Compile(); // compute the value with the expression tree Enum etResult = default(Enum); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute the value with regular IL Enum csResult = default(Enum); Exception csException = null; try { csResult = value as Enum; } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableEnumAsObject(E? value) { Expression<Func<object>> e = Expression.Lambda<Func<object>>( Expression.TypeAs(Expression.Constant(value, typeof(E?)), typeof(object)), Enumerable.Empty<ParameterExpression>()); Func<object> f = e.Compile(); // compute the value with the expression tree object etResult = default(object); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute the value with regular IL object csResult = default(object); Exception csException = null; try { csResult = value as object; } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableIntAsObject(int? value) { Expression<Func<object>> e = Expression.Lambda<Func<object>>( Expression.TypeAs(Expression.Constant(value, typeof(int?)), typeof(object)), Enumerable.Empty<ParameterExpression>()); Func<object> f = e.Compile(); // compute the value with the expression tree object etResult = default(object); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute the value with regular IL object csResult = default(object); Exception csException = null; try { csResult = value as object; } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableIntAsValueType(int? value) { Expression<Func<ValueType>> e = Expression.Lambda<Func<ValueType>>( Expression.TypeAs(Expression.Constant(value, typeof(int?)), typeof(ValueType)), Enumerable.Empty<ParameterExpression>()); Func<ValueType> f = e.Compile(); // compute the value with the expression tree ValueType etResult = default(ValueType); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute the value with regular IL ValueType csResult = default(ValueType); Exception csException = null; try { csResult = value as ValueType; } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableStructAsIEquatableOfStruct(S? value) { Expression<Func<IEquatable<S>>> e = Expression.Lambda<Func<IEquatable<S>>>( Expression.TypeAs(Expression.Constant(value, typeof(S?)), typeof(IEquatable<S>)), Enumerable.Empty<ParameterExpression>()); Func<IEquatable<S>> f = e.Compile(); // compute the value with the expression tree IEquatable<S> etResult = default(IEquatable<S>); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute the value with regular IL IEquatable<S> csResult = default(IEquatable<S>); Exception csException = null; try { csResult = value as IEquatable<S>; } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableStructAsObject(S? value) { Expression<Func<object>> e = Expression.Lambda<Func<object>>( Expression.TypeAs(Expression.Constant(value, typeof(S?)), typeof(object)), Enumerable.Empty<ParameterExpression>()); Func<object> f = e.Compile(); // compute the value with the expression tree object etResult = default(object); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute the value with regular IL object csResult = default(object); Exception csException = null; try { csResult = value as object; } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableStructAsValueType(S? value) { Expression<Func<ValueType>> e = Expression.Lambda<Func<ValueType>>( Expression.TypeAs(Expression.Constant(value, typeof(S?)), typeof(ValueType)), Enumerable.Empty<ParameterExpression>()); Func<ValueType> f = e.Compile(); // compute the value with the expression tree ValueType etResult = default(ValueType); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute the value with regular IL ValueType csResult = default(ValueType); Exception csException = null; try { csResult = value as ValueType; } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyGenericWithStructRestrictionAsObject<Ts>(Ts value) where Ts : struct { Expression<Func<object>> e = Expression.Lambda<Func<object>>( Expression.TypeAs(Expression.Constant(value, typeof(Ts)), typeof(object)), Enumerable.Empty<ParameterExpression>()); Func<object> f = e.Compile(); // compute the value with the expression tree object etResult = default(object); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute the value with regular IL object csResult = default(object); Exception csException = null; try { csResult = value as object; } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyGenericWithStructRestrictionAsValueType<Ts>(Ts value) where Ts : struct { Expression<Func<ValueType>> e = Expression.Lambda<Func<ValueType>>( Expression.TypeAs(Expression.Constant(value, typeof(Ts)), typeof(ValueType)), Enumerable.Empty<ParameterExpression>()); Func<ValueType> f = e.Compile(); // compute the value with the expression tree ValueType etResult = default(ValueType); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute the value with regular IL ValueType csResult = default(ValueType); Exception csException = null; try { csResult = value as ValueType; } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } #endregion } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.3074 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal.ProviderControls { public partial class MailEnable_EditList { /// <summary> /// lblDescription control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblDescription; /// <summary> /// txtDescription control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtDescription; /// <summary> /// lblReplyTo control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblReplyTo; /// <summary> /// ddlReplyTo control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlReplyTo; /// <summary> /// lblPostingMode control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblPostingMode; /// <summary> /// ddlPostingMode control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlPostingMode; /// <summary> /// lblPostingPassword control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblPostingPassword; /// <summary> /// txtPassword control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtPassword; /// <summary> /// Label3 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label Label3; /// <summary> /// ddlPrefixOption control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlPrefixOption; /// <summary> /// Label4 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label Label4; /// <summary> /// txtSubjectPrefix control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtSubjectPrefix; /// <summary> /// lblModerationEnabled control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblModerationEnabled; /// <summary> /// chkModerationEnabled control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox chkModerationEnabled; /// <summary> /// lblModeratorAddress control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblModeratorAddress; /// <summary> /// txtModeratorEmail control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UserControls.EmailControl txtModeratorEmail; /// <summary> /// lblMembers control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblMembers; /// <summary> /// mailEditItems control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.MailEditItems mailEditItems; /// <summary> /// HeaderFooterSection control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel HeaderFooterSection; /// <summary> /// pHeaderFooter control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel pHeaderFooter; /// <summary> /// lblHeader control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblHeader; /// <summary> /// cbHeader control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox cbHeader; /// <summary> /// lblHeaderText control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblHeaderText; /// <summary> /// txtHeaderText control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtHeaderText; /// <summary> /// lblHeaderHtml control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblHeaderHtml; /// <summary> /// txtHeaderHtml control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtHeaderHtml; /// <summary> /// lblFooter control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblFooter; /// <summary> /// cbFooter control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox cbFooter; /// <summary> /// lblFooterText control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblFooterText; /// <summary> /// txtFooterText control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtFooterText; /// <summary> /// lblFooterHtml control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblFooterHtml; /// <summary> /// txtFooterHtml control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtFooterHtml; } }
// // Mono.WebServer.Apache/main.cs: Mod_mono Backend for XSP. // // Authors: // Gonzalo Paniagua Javier ([email protected]) // // (C) 2002,2003 Ximian, Inc (http://www.ximian.com) // (C) Copyright 2004-2009 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 System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using Mono.WebServer.Log; using Mono.WebServer.Options; namespace Mono.WebServer.Apache { public class Server : MarshalByRefObject { public static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e) { var ex = (Exception)e.ExceptionObject; Logger.Write (LogLevel.Error, "Handling exception type {0}", ex.GetType ().Name); Logger.Write (LogLevel.Error, "Message is {0}", ex.Message); Logger.Write (LogLevel.Error, "IsTerminating is set to {0}", e.IsTerminating); if (e.IsTerminating) Logger.Write (ex); } public static int Main (string [] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; try { var svr = new Server (); return svr.RealMain (args, true, null, false); } catch (ThreadAbortException) { // Single-app mode and ASP.NET appdomain unloaded Thread.ResetAbort (); } return 1; } // // Parameters: // // args - original args passed to the program // root - true means caller is in the root domain // ext_apphost - used when single app mode is used, in a recursive call to // RealMain from the single app domain // quiet - don't show messages. Used to avoid double printing of the banner // public int RealMain (string [] args, bool root, IApplicationHost ext_apphost, bool v_quiet) { var configurationManager = new ConfigurationManager ("mod_mono", v_quiet, ext_apphost == null ? null : ext_apphost.Path); if (!configurationManager.LoadCommandLineArgs (args)) return 1; // Show the help and exit. if (configurationManager.Help) { configurationManager.PrintHelp (); #if DEBUG Console.WriteLine("Press any key..."); Console.ReadKey (); #endif return 0; } // Show the version and exit. if (configurationManager.Version) { Version.Show (); return 0; } var hash = GetHash (args); if (hash == -1) { Logger.Write(LogLevel.Error, "Couldn't calculate hash - should have left earlier - something is really wrong"); return 1; } if (hash == -2) { Logger.Write(LogLevel.Error, "Couldn't calculate hash - unrecognized parameter"); return 1; } if (!configurationManager.LoadConfigFile ()) return 1; configurationManager.SetupLogger (); ushort port = configurationManager.Port ?? 0; bool useTCP = port != 0; string lockfile = useTCP ? Path.Combine (Path.GetTempPath (), "mod_mono_TCP_") : configurationManager.Filename; lockfile = String.Format ("{0}_{1}", lockfile, hash); ModMonoWebSource webSource = useTCP ? new ModMonoTCPWebSource (configurationManager.Address, port, lockfile) : new ModMonoWebSource (configurationManager.Filename, lockfile); if(configurationManager.Terminate) { if (configurationManager.Verbose) Logger.Write (LogLevel.Notice, "Shutting down running mod-mono-server..."); bool res = webSource.GracefulShutdown (); if (configurationManager.Verbose) if (res) Logger.Write (LogLevel.Notice, "Done"); else Logger.Write (LogLevel.Error, "Failed."); return res ? 0 : 1; } var server = new ApplicationServer (webSource, configurationManager.Root) { Verbose = configurationManager.Verbose, SingleApplication = !root }; #if DEBUG Console.WriteLine (Assembly.GetExecutingAssembly ().GetName ().Name); #endif if (configurationManager.Applications != null) server.AddApplicationsFromCommandLine (configurationManager.Applications); if (configurationManager.AppConfigFile != null) server.AddApplicationsFromConfigFile (configurationManager.AppConfigFile); if (configurationManager.AppConfigDir != null) server.AddApplicationsFromConfigDirectory (configurationManager.AppConfigDir); if (!configurationManager.Master && configurationManager.Applications == null && configurationManager.AppConfigDir == null && configurationManager.AppConfigFile == null) server.AddApplicationsFromCommandLine ("/:."); // TODO: do we really want this? VPathToHost vh = server.GetSingleApp (); if (root && vh != null) { // Redo in new domain vh.CreateHost (server, webSource); var svr = (Server)vh.AppHost.Domain.CreateInstanceAndUnwrap (GetType ().Assembly.GetName ().ToString (), GetType ().FullName); webSource.Dispose (); return svr.RealMain (args, false, vh.AppHost, configurationManager.Quiet); } if (ext_apphost != null) { ext_apphost.Server = server; server.AppHost = ext_apphost; } if (!configurationManager.Quiet) { if (!useTCP) Logger.Write (LogLevel.Notice, "Listening on: {0}", configurationManager.Filename); else { Logger.Write (LogLevel.Notice, "Listening on port: {0}", port); Logger.Write (LogLevel.Notice, "Listening on address: {0}", configurationManager.Address); } Logger.Write (LogLevel.Notice, "Root directory: {0}", configurationManager.Root); } try { if (!server.Start (!configurationManager.NonStop, (int)configurationManager.Backlog)) return 2; if (!configurationManager.NonStop) { Logger.Write (LogLevel.Notice, "Hit Return to stop the server."); while (true) { try { Console.ReadLine (); break; } catch (IOException) { // This might happen on appdomain unload // until the previous threads are terminated. Thread.Sleep (500); } } server.Stop (); } } catch (Exception e) { if (!(e is ThreadAbortException)) Logger.Write (e); else server.ShutdownSockets (); return 1; } return 0; } static int GetHash (IEnumerable<string> args) { int hash = args.Aggregate (23, (current, arg) => current * 37 + arg.GetHashCode ()); if (hash < 0) return -hash; return hash; } public override object InitializeLifetimeService () { return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Numerics.Tests { public class BigIntegerConstructorTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunCtorInt32Tests() { // ctor(Int32): Int32.MinValue VerifyCtorInt32(Int32.MinValue); // ctor(Int32): -1 VerifyCtorInt32((Int32)(-1)); // ctor(Int32): 0 VerifyCtorInt32((Int32)0); // ctor(Int32): 1 VerifyCtorInt32((Int32)1); // ctor(Int32): Int32.MaxValue VerifyCtorInt32(Int32.MaxValue); // ctor(Int32): Random Positive for (int i = 0; i < s_samples; ++i) { VerifyCtorInt32((Int32)s_random.Next(1, Int32.MaxValue)); } // ctor(Int32): Random Negative for (int i = 0; i < s_samples; ++i) { VerifyCtorInt32((Int32)s_random.Next(Int32.MinValue, 0)); } } private static void VerifyCtorInt32(Int32 value) { BigInteger bigInteger = new BigInteger(value); Assert.Equal(value, bigInteger); Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString())); Assert.Equal(value, (Int32)bigInteger); if (value != Int32.MaxValue) { Assert.Equal((Int32)(value + 1), (Int32)(bigInteger + 1)); } if (value != Int32.MinValue) { Assert.Equal((Int32)(value - 1), (Int32)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } [Fact] public static void RunCtorInt64Tests() { // ctor(Int64): Int64.MinValue VerifyCtorInt64(Int64.MinValue); // ctor(Int64): Int32.MinValue-1 VerifyCtorInt64(((Int64)Int32.MinValue) - 1); // ctor(Int64): Int32.MinValue VerifyCtorInt64((Int64)Int32.MinValue); // ctor(Int64): -1 VerifyCtorInt64((Int64)(-1)); // ctor(Int64): 0 VerifyCtorInt64((Int64)0); // ctor(Int64): 1 VerifyCtorInt64((Int64)1); // ctor(Int64): Int32.MaxValue VerifyCtorInt64((Int64)Int32.MaxValue); // ctor(Int64): Int32.MaxValue+1 VerifyCtorInt64(((Int64)Int32.MaxValue) + 1); // ctor(Int64): Int64.MaxValue VerifyCtorInt64(Int64.MaxValue); // ctor(Int64): Random Positive for (int i = 0; i < s_samples; ++i) { VerifyCtorInt64((Int64)(Int64.MaxValue * s_random.NextDouble())); } // ctor(Int64): Random Negative for (int i = 0; i < s_samples; ++i) { VerifyCtorInt64((Int64)(Int64.MaxValue * s_random.NextDouble()) - Int64.MaxValue); } } private static void VerifyCtorInt64(Int64 value) { BigInteger bigInteger = new BigInteger(value); Assert.Equal(value, bigInteger); Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString())); Assert.Equal(value, (Int64)bigInteger); if (value != Int64.MaxValue) { Assert.Equal((Int64)(value + 1), (Int64)(bigInteger + 1)); } if (value != Int64.MinValue) { Assert.Equal((Int64)(value - 1), (Int64)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } [Fact] public static void RunCtorUInt32Tests() { // ctor(UInt32): UInt32.MinValue VerifyCtorUInt32(UInt32.MinValue); // ctor(UInt32): 0 VerifyCtorUInt32((UInt32)0); // ctor(UInt32): 1 VerifyCtorUInt32((UInt32)1); // ctor(UInt32): Int32.MaxValue VerifyCtorUInt32((UInt32)Int32.MaxValue); // ctor(UInt32): Int32.MaxValue+1 VerifyCtorUInt32(((UInt32)Int32.MaxValue) + 1); // ctor(UInt32): UInt32.MaxValue VerifyCtorUInt32(UInt32.MaxValue); // ctor(UInt32): Random Positive for (int i = 0; i < s_samples; ++i) { VerifyCtorUInt32((UInt32)(UInt32.MaxValue * s_random.NextDouble())); } } private static void VerifyCtorUInt32(UInt32 value) { BigInteger bigInteger = new BigInteger(value); Assert.Equal(value, bigInteger); Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString())); Assert.Equal(value, (UInt32)bigInteger); if (value != UInt32.MaxValue) { Assert.Equal((UInt32)(value + 1), (UInt32)(bigInteger + 1)); } if (value != UInt32.MinValue) { Assert.Equal((UInt32)(value - 1), (UInt32)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } [Fact] public static void RunCtorUInt64Tests() { // ctor(UInt64): UInt64.MinValue VerifyCtorUInt64(UInt64.MinValue); // ctor(UInt64): 0 VerifyCtorUInt64((UInt64)0); // ctor(UInt64): 1 VerifyCtorUInt64((UInt64)1); // ctor(UInt64): Int32.MaxValue VerifyCtorUInt64((UInt64)Int32.MaxValue); // ctor(UInt64): Int32.MaxValue+1 VerifyCtorUInt64(((UInt64)Int32.MaxValue) + 1); // ctor(UInt64): UInt64.MaxValue VerifyCtorUInt64(UInt64.MaxValue); // ctor(UInt64): Random Positive for (int i = 0; i < s_samples; ++i) { VerifyCtorUInt64((UInt64)(UInt64.MaxValue * s_random.NextDouble())); } } private static void VerifyCtorUInt64(UInt64 value) { BigInteger bigInteger = new BigInteger(value); Assert.Equal(value, bigInteger); Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString())); Assert.Equal(value, (UInt64)bigInteger); if (value != UInt64.MaxValue) { Assert.Equal((UInt64)(value + 1), (UInt64)(bigInteger + 1)); } if (value != UInt64.MinValue) { Assert.Equal((UInt64)(value - 1), (UInt64)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } [Fact] public static void RunCtorSingleTests() { // ctor(Single): Single.Minvalue VerifyCtorSingle(Single.MinValue); // ctor(Single): Int32.MinValue-1 VerifyCtorSingle(((Single)Int32.MinValue) - 1); // ctor(Single): Int32.MinValue VerifyCtorSingle(((Single)Int32.MinValue)); // ctor(Single): Int32.MinValue+1 VerifyCtorSingle(((Single)Int32.MinValue) + 1); // ctor(Single): -1 VerifyCtorSingle((Single)(-1)); // ctor(Single): 0 VerifyCtorSingle((Single)0); // ctor(Single): 1 VerifyCtorSingle((Single)1); // ctor(Single): Int32.MaxValue-1 VerifyCtorSingle(((Single)Int32.MaxValue) - 1); // ctor(Single): Int32.MaxValue VerifyCtorSingle(((Single)Int32.MaxValue)); // ctor(Single): Int32.MaxValue+1 VerifyCtorSingle(((Single)Int32.MaxValue) + 1); // ctor(Single): Single.MaxValue VerifyCtorSingle(Single.MaxValue); // ctor(Single): Random Positive for (int i = 0; i < s_samples; i++) { VerifyCtorSingle((Single)(Single.MaxValue * s_random.NextDouble())); } // ctor(Single): Random Negative for (int i = 0; i < s_samples; i++) { VerifyCtorSingle(((Single)(Single.MaxValue * s_random.NextDouble())) - Single.MaxValue); } // ctor(Single): Small Random Positive with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorSingle((Single)(s_random.Next(0, 100) + s_random.NextDouble())); } // ctor(Single): Small Random Negative with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorSingle(((Single)(s_random.Next(-100, 0) - s_random.NextDouble()))); } // ctor(Single): Large Random Positive with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorSingle((Single)((Single.MaxValue * s_random.NextDouble()) + s_random.NextDouble())); } // ctor(Single): Large Random Negative with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorSingle(((Single)((-(Single.MaxValue - 1) * s_random.NextDouble()) - s_random.NextDouble()))); } // ctor(Single): Single.Epsilon VerifyCtorSingle(Single.Epsilon); // ctor(Single): Single.NegativeInfinity Assert.Throws<OverflowException>(() => new BigInteger(Single.NegativeInfinity)); // ctor(Single): Single.PositiveInfinity Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(Single.PositiveInfinity); }); // ctor(Single): Single.NaN Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(Single.NaN); }); // ctor(Single): Single.NaN 2 Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(ConvertInt32ToSingle(0x7FC00000)); }); // ctor(Single): Smallest Exponent VerifyCtorSingle((Single)Math.Pow(2, -126)); // ctor(Single): Largest Exponent VerifyCtorSingle((Single)Math.Pow(2, 127)); // ctor(Single): Largest number less than 1 Single value = 0; for (int i = 1; i <= 24; ++i) { value += (Single)(Math.Pow(2, -i)); } VerifyCtorSingle(value); // ctor(Single): Smallest number greater than 1 value = (Single)(1 + Math.Pow(2, -23)); VerifyCtorSingle(value); // ctor(Single): Largest number less than 2 value = 0; for (int i = 1; i <= 23; ++i) { value += (Single)(Math.Pow(2, -i)); } value += 1; VerifyCtorSingle(value); } private static void VerifyCtorSingle(Single value) { BigInteger bigInteger = new BigInteger(value); Single expectedValue; if (value < 0) { expectedValue = (Single)Math.Ceiling(value); } else { expectedValue = (Single)Math.Floor(value); } Assert.Equal(expectedValue, (Single)bigInteger); // Single can only accurately represent integers between -16777216 and 16777216 exclusive. // ToString starts to become inaccurate at this point. if (expectedValue < 16777216 && -16777216 < expectedValue) { Assert.True(expectedValue.ToString("G9").Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "Single.ToString() and BigInteger.ToString() not equal"); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); } [Fact] public static void RunCtorDoubleTests() { // ctor(Double): Double.Minvalue VerifyCtorDouble(Double.MinValue); // ctor(Double): Single.Minvalue VerifyCtorDouble((Double)Single.MinValue); // ctor(Double): Int64.MinValue-1 VerifyCtorDouble(((Double)Int64.MinValue) - 1); // ctor(Double): Int64.MinValue VerifyCtorDouble(((Double)Int64.MinValue)); // ctor(Double): Int64.MinValue+1 VerifyCtorDouble(((Double)Int64.MinValue) + 1); // ctor(Double): Int32.MinValue-1 VerifyCtorDouble(((Double)Int32.MinValue) - 1); // ctor(Double): Int32.MinValue VerifyCtorDouble(((Double)Int32.MinValue)); // ctor(Double): Int32.MinValue+1 VerifyCtorDouble(((Double)Int32.MinValue) + 1); // ctor(Double): -1 VerifyCtorDouble((Double)(-1)); // ctor(Double): 0 VerifyCtorDouble((Double)0); // ctor(Double): 1 VerifyCtorDouble((Double)1); // ctor(Double): Int32.MaxValue-1 VerifyCtorDouble(((Double)Int32.MaxValue) - 1); // ctor(Double): Int32.MaxValue VerifyCtorDouble(((Double)Int32.MaxValue)); // ctor(Double): Int32.MaxValue+1 VerifyCtorDouble(((Double)Int32.MaxValue) + 1); // ctor(Double): Int64.MaxValue-1 VerifyCtorDouble(((Double)Int64.MaxValue) - 1); // ctor(Double): Int64.MaxValue VerifyCtorDouble(((Double)Int64.MaxValue)); // ctor(Double): Int64.MaxValue+1 VerifyCtorDouble(((Double)Int64.MaxValue) + 1); // ctor(Double): Single.MaxValue VerifyCtorDouble((Double)Single.MaxValue); // ctor(Double): Double.MaxValue VerifyCtorDouble(Double.MaxValue); // ctor(Double): Random Positive for (int i = 0; i < s_samples; i++) { VerifyCtorDouble((Double)(Double.MaxValue * s_random.NextDouble())); } // ctor(Double): Random Negative for (int i = 0; i < s_samples; i++) { VerifyCtorDouble((Double.MaxValue * s_random.NextDouble()) - Double.MaxValue); } // ctor(Double): Small Random Positive with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorDouble((Double)(s_random.Next(0, 100) + s_random.NextDouble())); } // ctor(Double): Small Random Negative with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorDouble(((Double)(s_random.Next(-100, 0) - s_random.NextDouble()))); } // ctor(Double): Large Random Positive with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorDouble((Double)((Int64.MaxValue / 100 * s_random.NextDouble()) + s_random.NextDouble())); } // ctor(Double): Large Random Negative with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorDouble(((Double)((-(Int64.MaxValue / 100) * s_random.NextDouble()) - s_random.NextDouble()))); } // ctor(Double): Double.Epsilon VerifyCtorDouble(Double.Epsilon); // ctor(Double): Double.NegativeInfinity Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(Double.NegativeInfinity); }); // ctor(Double): Double.PositiveInfinity Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(Double.PositiveInfinity); }); // ctor(Double): Double.NaN Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(Double.NaN); }); // ctor(Double): Double.NaN 2 Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(ConvertInt64ToDouble(0x7FF8000000000000)); }); // ctor(Double): Smallest Exponent VerifyCtorDouble((Double)Math.Pow(2, -1022)); // ctor(Double): Largest Exponent VerifyCtorDouble((Double)Math.Pow(2, 1023)); // ctor(Double): Largest number less than 1 Double value = 0; for (int i = 1; i <= 53; ++i) { value += (Double)(Math.Pow(2, -i)); } VerifyCtorDouble(value); // ctor(Double): Smallest number greater than 1 value = (Double)(1 + Math.Pow(2, -52)); VerifyCtorDouble(value); // ctor(Double): Largest number less than 2 value = 0; for (int i = 1; i <= 52; ++i) { value += (Double)(Math.Pow(2, -i)); } value += 2; VerifyCtorDouble(value); } private static void VerifyCtorDouble(Double value) { BigInteger bigInteger = new BigInteger(value); Double expectedValue; if (value < 0) { expectedValue = (Double)Math.Ceiling(value); } else { expectedValue = (Double)Math.Floor(value); } Assert.Equal(expectedValue, (Double)bigInteger); // Single can only accurately represent integers between -16777216 and 16777216 exclusive. // ToString starts to become inaccurate at this point. if (expectedValue < 9007199254740992 && -9007199254740992 < expectedValue) { Assert.True(expectedValue.ToString("G17").Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "Double.ToString() and BigInteger.ToString() not equal"); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); } [Fact] public static void RunCtorDecimalTests() { Decimal value; // ctor(Decimal): Decimal.MinValue VerifyCtorDecimal(Decimal.MinValue); // ctor(Decimal): -1 VerifyCtorDecimal(-1); // ctor(Decimal): 0 VerifyCtorDecimal(0); // ctor(Decimal): 1 VerifyCtorDecimal(1); // ctor(Decimal): Decimal.MaxValue VerifyCtorDecimal(Decimal.MaxValue); // ctor(Decimal): Random Positive for (int i = 0; i < s_samples; i++) { value = new Decimal( s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), false, (byte)s_random.Next(0, 29)); VerifyCtorDecimal(value); } // ctor(Decimal): Random Negative for (int i = 0; i < s_samples; i++) { value = new Decimal( s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), true, (byte)s_random.Next(0, 29)); VerifyCtorDecimal(value); } // ctor(Decimal): Smallest Exponent unchecked { value = new Decimal(1, 0, 0, false, 0); } VerifyCtorDecimal(value); // ctor(Decimal): Largest Exponent and zero integer unchecked { value = new Decimal(0, 0, 0, false, 28); } VerifyCtorDecimal(value); // ctor(Decimal): Largest Exponent and non zero integer unchecked { value = new Decimal(1, 0, 0, false, 28); } VerifyCtorDecimal(value); // ctor(Decimal): Largest number less than 1 value = 1 - new Decimal(1, 0, 0, false, 28); VerifyCtorDecimal(value); // ctor(Decimal): Smallest number greater than 1 value = 1 + new Decimal(1, 0, 0, false, 28); VerifyCtorDecimal(value); // ctor(Decimal): Largest number less than 2 value = 2 - new Decimal(1, 0, 0, false, 28); VerifyCtorDecimal(value); } private static void VerifyCtorDecimal(Decimal value) { BigInteger bigInteger = new BigInteger(value); Decimal expectedValue; if (value < 0) { expectedValue = Math.Ceiling(value); } else { expectedValue = Math.Floor(value); } Assert.True(expectedValue.ToString().Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "Decimal.ToString() and BigInteger.ToString()"); Assert.Equal(expectedValue, (Decimal)bigInteger); if (expectedValue != Math.Floor(Decimal.MaxValue)) { Assert.Equal((Decimal)(expectedValue + 1), (Decimal)(bigInteger + 1)); } if (expectedValue != Math.Ceiling(Decimal.MinValue)) { Assert.Equal((Decimal)(expectedValue - 1), (Decimal)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); } [Fact] public static void RunCtorByteArrayTests() { UInt64 tempUInt64; byte[] tempByteArray; // ctor(byte[]): array is null Assert.Throws<ArgumentNullException>(() => { BigInteger bigInteger = new BigInteger((byte[])null); }); // ctor(byte[]): array is empty VerifyCtorByteArray(new byte[0], 0); // ctor(byte[]): array is 1 byte tempUInt64 = (UInt32)s_random.Next(0, 256); tempByteArray = BitConverter.GetBytes(tempUInt64); if (tempByteArray[0] > 127) { VerifyCtorByteArray(new byte[] { tempByteArray[0] }); VerifyCtorByteArray(new byte[] { tempByteArray[0], 0 }, tempUInt64); } else { VerifyCtorByteArray(new byte[] { tempByteArray[0] }, tempUInt64); } // ctor(byte[]): Small array with all zeros VerifyCtorByteArray(new byte[] { 0, 0, 0, 0 }); // ctor(byte[]): Large array with all zeros VerifyCtorByteArray( new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); // ctor(byte[]): Small array with all ones VerifyCtorByteArray(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }); // ctor(byte[]): Large array with all ones VerifyCtorByteArray( new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); // ctor(byte[]): array with a lot of leading zeros for (int i = 0; i < s_samples; i++) { tempUInt64 = (UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue); tempByteArray = BitConverter.GetBytes(tempUInt64); VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, tempUInt64); } // ctor(byte[]): array 4 bytes for (int i = 0; i < s_samples; i++) { tempUInt64 = (UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue); tempByteArray = BitConverter.GetBytes(tempUInt64); if (tempUInt64 > Int32.MaxValue) { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3] }); VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], 0 }, tempUInt64); } else { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3] }, tempUInt64); } } // ctor(byte[]): array 5 bytes for (int i = 0; i < s_samples; i++) { tempUInt64 = (UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue); tempUInt64 <<= 8; tempUInt64 += (UInt64)s_random.Next(0, 256); tempByteArray = BitConverter.GetBytes(tempUInt64); if (tempUInt64 >= (UInt64)0x00080000) { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4] }); VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4], 0 }, tempUInt64); } else { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4] }, tempUInt64); } } // ctor(byte[]): array 8 bytes for (int i = 0; i < s_samples; i++) { tempUInt64 = (UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue); tempUInt64 <<= 32; tempUInt64 += (UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue); tempByteArray = BitConverter.GetBytes(tempUInt64); if (tempUInt64 > Int64.MaxValue) { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4], tempByteArray[5], tempByteArray[6], tempByteArray[7] }); VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4], tempByteArray[5], tempByteArray[6], tempByteArray[7], 0 }, tempUInt64); } else { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4], tempByteArray[5], tempByteArray[6], tempByteArray[7] }, tempUInt64); } } // ctor(byte[]): array 9 bytes for (int i = 0; i < s_samples; i++) { VerifyCtorByteArray( new byte[] { (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256) }); } // ctor(byte[]): array is UInt32.MaxValue VerifyCtorByteArray(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0 }, UInt32.MaxValue); // ctor(byte[]): array is UInt32.MaxValue + 1 VerifyCtorByteArray(new byte[] { 0, 0, 0, 0, 1 }, (UInt64)UInt32.MaxValue + 1); // ctor(byte[]): array is UInt64.MaxValue VerifyCtorByteArray(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }, UInt64.MaxValue); // ctor(byte[]): UInt64.MaxValue + 1 VerifyCtorByteArray( new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 1 }); // ctor(byte[]): UInt64.MaxValue + 2^64 VerifyCtorByteArray( new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 1 }); // ctor(byte[]): array is random > UInt64 for (int i = 0; i < s_samples; i++) { tempByteArray = new byte[s_random.Next(0, 1024)]; for (int arrayIndex = 0; arrayIndex < tempByteArray.Length; ++arrayIndex) { tempByteArray[arrayIndex] = (byte)s_random.Next(0, 256); } VerifyCtorByteArray(tempByteArray); } // ctor(byte[]): array is large for (int i = 0; i < s_samples; i++) { tempByteArray = new byte[s_random.Next(16384, 2097152)]; for (int arrayIndex = 0; arrayIndex < tempByteArray.Length; ++arrayIndex) { tempByteArray[arrayIndex] = (byte)s_random.Next(0, 256); } VerifyCtorByteArray(tempByteArray); } } private static void VerifyCtorByteArray(byte[] value, UInt64 expectedValue) { BigInteger bigInteger = new BigInteger(value); Assert.Equal(expectedValue, bigInteger); Assert.True(expectedValue.ToString().Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "UInt64.ToString() and BigInteger.ToString()"); Assert.Equal(expectedValue, (UInt64)bigInteger); if (expectedValue != UInt64.MaxValue) { Assert.Equal((UInt64)(expectedValue + 1), (UInt64)(bigInteger + 1)); } if (expectedValue != UInt64.MinValue) { Assert.Equal((UInt64)(expectedValue - 1), (UInt64)(bigInteger - 1)); } VerifyCtorByteArray(value); } private static void VerifyCtorByteArray(byte[] value) { BigInteger bigInteger; byte[] roundTrippedByteArray; bool isZero = MyBigIntImp.IsZero(value); bigInteger = new BigInteger(value); roundTrippedByteArray = bigInteger.ToByteArray(); for (int i = Math.Min(value.Length, roundTrippedByteArray.Length) - 1; 0 <= i; --i) { Assert.True(value[i] == roundTrippedByteArray[i], String.Format("Round Tripped ByteArray at {0}", i)); } if (value.Length < roundTrippedByteArray.Length) { for (int i = value.Length; i < roundTrippedByteArray.Length; ++i) { Assert.True(0 == roundTrippedByteArray[i], String.Format("Round Tripped ByteArray is larger than the original array and byte is non zero at {0}", i)); } } else if (value.Length > roundTrippedByteArray.Length) { for (int i = roundTrippedByteArray.Length; i < value.Length; ++i) { Assert.False((((0 != value[i]) && ((roundTrippedByteArray[roundTrippedByteArray.Length - 1] & 0x80) == 0)) || ((0xFF != value[i]) && ((roundTrippedByteArray[roundTrippedByteArray.Length - 1] & 0x80) != 0))), String.Format("Round Tripped ByteArray is smaller than the original array and byte is non zero at {0}", i)); } } if (value.Length < 8) { byte[] newvalue = new byte[8]; for (int i = 0; i < 8; i++) { if (bigInteger < 0) { newvalue[i] = 0xFF; } else { newvalue[i] = 0; } } for (int i = 0; i < value.Length; i++) { newvalue[i] = value[i]; } value = newvalue; } else if (value.Length > 8) { int newlength = value.Length; for (; newlength > 8; newlength--) { if (bigInteger < 0) { if ((value[newlength - 1] != 0xFF) | ((value[newlength - 2] & 0x80) == 0)) { break; } } else { if ((value[newlength - 1] != 0) | ((value[newlength - 2] & 0x80) != 0)) { break; } } } byte[] newvalue = new byte[newlength]; for (int i = 0; i < newlength; i++) { newvalue[i] = value[i]; } value = newvalue; } if (IsOutOfRangeInt64(value)) { // Try subtracting a value from the BigInteger that will allow it to be represented as an Int64 byte[] tempByteArray; BigInteger tempBigInteger; bool isNeg = ((value[value.Length - 1] & 0x80) != 0); tempByteArray = new byte[value.Length]; Array.Copy(value, 8, tempByteArray, 8, value.Length - 8); tempBigInteger = bigInteger - (new BigInteger(tempByteArray)); tempByteArray = new byte[8]; Array.Copy(value, 0, tempByteArray, 0, 8); if (!(((tempByteArray[7] & 0x80) == 0) ^ isNeg)) { tempByteArray[7] ^= 0x80; tempBigInteger = tempBigInteger + (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0x80 })); } if (isNeg & (tempBigInteger > 0)) { tempBigInteger = tempBigInteger + (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0xFF })); } Assert.Equal(BitConverter.ToInt64(tempByteArray, 0), (Int64)tempBigInteger); } else { Assert.Equal(BitConverter.ToInt64(value, 0), (Int64)bigInteger); } if (IsOutOfRangeUInt64(value)) { // Try subtracting a value from the BigInteger that will allow it to be represented as an UInt64 byte[] tempByteArray; BigInteger tempBigInteger; bool isNeg = ((value[value.Length - 1] & 0x80) != 0); tempByteArray = new byte[value.Length]; Array.Copy(value, 8, tempByteArray, 8, value.Length - 8); tempBigInteger = bigInteger - (new BigInteger(tempByteArray)); tempByteArray = new byte[8]; Array.Copy(value, 0, tempByteArray, 0, 8); if ((tempByteArray[7] & 0x80) != 0) { tempByteArray[7] &= 0x7f; if (tempBigInteger < 0) { tempBigInteger = tempBigInteger - (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0x80 })); } else { tempBigInteger = tempBigInteger + (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0x80 })); } } Assert.Equal(BitConverter.ToUInt64(tempByteArray, 0), (UInt64)tempBigInteger); } else { Assert.Equal(BitConverter.ToUInt64(value, 0), (UInt64)bigInteger); } VerifyBigIntegerUsingIdentities(bigInteger, isZero); } private static Single ConvertInt32ToSingle(Int32 value) { return BitConverter.ToSingle(BitConverter.GetBytes(value), 0); } private static Double ConvertInt64ToDouble(Int64 value) { return BitConverter.ToDouble(BitConverter.GetBytes(value), 0); } private static void VerifyBigIntegerUsingIdentities(BigInteger bigInteger, bool isZero) { BigInteger tempBigInteger = new BigInteger(bigInteger.ToByteArray()); Assert.Equal(bigInteger, tempBigInteger); if (isZero) { Assert.Equal(BigInteger.Zero, bigInteger); } else { Assert.NotEqual(BigInteger.Zero, bigInteger); Assert.Equal(BigInteger.One, bigInteger / bigInteger); } // (x + 1) - 1 = x Assert.Equal(bigInteger, ((bigInteger + BigInteger.One) - BigInteger.One)); // (x + 1) - x = 1 Assert.Equal(BigInteger.One, ((bigInteger + BigInteger.One) - bigInteger)); // x - x = 0 Assert.Equal(BigInteger.Zero, (bigInteger - bigInteger)); // x + x = 2x Assert.Equal((2 * bigInteger), (bigInteger + bigInteger)); // x/1 = x Assert.Equal(bigInteger, (bigInteger / BigInteger.One)); // 1 * x = x Assert.Equal(bigInteger, (BigInteger.One * bigInteger)); } private static bool IsOutOfRangeUInt64(byte[] value) { if (value.Length == 0) { return false; } if ((0x80 & value[value.Length - 1]) != 0) { return true; } byte zeroValue = 0; if (value.Length <= 8) { return false; } for (int i = 8; i < value.Length; ++i) { if (zeroValue != value[i]) { return true; } } return false; } private static bool IsOutOfRangeInt64(byte[] value) { if (value.Length == 0) { return false; } bool isNeg = ((0x80 & value[value.Length - 1]) != 0); byte zeroValue = 0; if (isNeg) { zeroValue = 0xFF; } if (value.Length < 8) { return false; } for (int i = 8; i < value.Length; i++) { if (zeroValue != value[i]) { return true; } } return (!((0 == (0x80 & value[7])) ^ isNeg)); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.ObjectModel; using System.ComponentModel; using Windows.Devices.Bluetooth; using Windows.Devices.Bluetooth.Rfcomm; using Windows.Devices.Enumeration; using Windows.Foundation; using Windows.Networking.Sockets; using Windows.Storage.Streams; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { public sealed partial class Scenario1_ChatClient : Page { // A pointer back to the main page is required to display status messages. private MainPage rootPage = MainPage.Current; // Used to display list of available devices to chat with public ObservableCollection<RfcommChatDeviceDisplay> ResultCollection { get; private set; } private DeviceWatcher deviceWatcher = null; private StreamSocket chatSocket = null; private DataWriter chatWriter = null; private RfcommDeviceService chatService = null; private BluetoothDevice bluetoothDevice; public Scenario1_ChatClient() { this.InitializeComponent(); App.Current.Suspending += App_Suspending; } protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; ResultCollection = new ObservableCollection<RfcommChatDeviceDisplay>(); DataContext = this; } protected override void OnNavigatedFrom(NavigationEventArgs e) { StopWatcher(); } private void StopWatcher() { if (null != deviceWatcher) { if ((DeviceWatcherStatus.Started == deviceWatcher.Status || DeviceWatcherStatus.EnumerationCompleted == deviceWatcher.Status)) { deviceWatcher.Stop(); } deviceWatcher = null; } } void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) { // Make sure we clean up resources on suspend. Disconnect("App Suspension disconnects"); } /// <summary> /// When the user presses the run button, query for all nearby unpaired devices /// Note that in this case, the other device must be running the Rfcomm Chat Server before being paired. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private void RunButton_Click(object sender, RoutedEventArgs e) { if (deviceWatcher == null) { SetDeviceWatcherUI(); StartUnpairedDeviceWatcher(); } else { ResetMainUI(); } } private void SetDeviceWatcherUI() { // Disable the button while we do async operations so the user can't Run twice. RunButton.Content = "Stop"; rootPage.NotifyUser("Device watcher started", NotifyType.StatusMessage); resultsListView.Visibility = Visibility.Visible; resultsListView.IsEnabled = true; } private void ResetMainUI() { RunButton.Content = "Start"; RunButton.IsEnabled = true; ConnectButton.Visibility = Visibility.Visible; resultsListView.Visibility = Visibility.Visible; resultsListView.IsEnabled = true; // Re-set device specific UX ChatBox.Visibility = Visibility.Collapsed; RequestAccessButton.Visibility = Visibility.Collapsed; if (ConversationList.Items != null) ConversationList.Items.Clear(); StopWatcher(); } private void StartUnpairedDeviceWatcher() { // Request additional properties string[] requestedProperties = new string[] { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" }; deviceWatcher = DeviceInformation.CreateWatcher("(System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\")", requestedProperties, DeviceInformationKind.AssociationEndpoint); // Hook up handlers for the watcher events before starting the watcher deviceWatcher.Added += new TypedEventHandler<DeviceWatcher, DeviceInformation>(async (watcher, deviceInfo) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Make sure device name isn't blank if(deviceInfo.Name != "") { ResultCollection.Add(new RfcommChatDeviceDisplay(deviceInfo)); rootPage.NotifyUser( String.Format("{0} devices found.", ResultCollection.Count), NotifyType.StatusMessage); } }); }); deviceWatcher.Updated += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) => { await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { foreach (RfcommChatDeviceDisplay rfcommInfoDisp in ResultCollection) { if (rfcommInfoDisp.Id == deviceInfoUpdate.Id) { rfcommInfoDisp.Update(deviceInfoUpdate); break; } } }); }); deviceWatcher.EnumerationCompleted += new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) => { await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { rootPage.NotifyUser( String.Format("{0} devices found. Enumeration completed. Watching for updates...", ResultCollection.Count), NotifyType.StatusMessage); }); }); deviceWatcher.Removed += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { // Find the corresponding DeviceInformation in the collection and remove it foreach (RfcommChatDeviceDisplay rfcommInfoDisp in ResultCollection) { if (rfcommInfoDisp.Id == deviceInfoUpdate.Id) { ResultCollection.Remove(rfcommInfoDisp); break; } } rootPage.NotifyUser( String.Format("{0} devices found.", ResultCollection.Count), NotifyType.StatusMessage); }); }); deviceWatcher.Stopped += new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) => { await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { ResultCollection.Clear(); }); }); deviceWatcher.Start(); } /// <summary> /// Invoked once the user has selected the device to connect to. /// Once the user has selected the device, /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ConnectButton_Click(object sender, RoutedEventArgs e) { // Make sure user has selected a device first if (resultsListView.SelectedItem != null) { rootPage.NotifyUser("Connecting to remote device. Please wait...", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Please select an item to connect to", NotifyType.ErrorMessage); return; } RfcommChatDeviceDisplay deviceInfoDisp = resultsListView.SelectedItem as RfcommChatDeviceDisplay; // Perform device access checks before trying to get the device. // First, we check if consent has been explicitly denied by the user. DeviceAccessStatus accessStatus = DeviceAccessInformation.CreateFromId(deviceInfoDisp.Id).CurrentStatus; if (accessStatus == DeviceAccessStatus.DeniedByUser) { rootPage.NotifyUser("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices", NotifyType.ErrorMessage); return; } // If not, try to get the Bluetooth device try { bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfoDisp.Id); } catch (Exception ex) { rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage); ResetMainUI(); return; } // If we were unable to get a valid Bluetooth device object, // it's most likely because the user has specified that all unpaired devices // should not be interacted with. if (bluetoothDevice == null) { rootPage.NotifyUser("Bluetooth Device returned null. Access Status = " + accessStatus.ToString(), NotifyType.ErrorMessage); } // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync( RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid), BluetoothCacheMode.Uncached); if (rfcommServices.Services.Count > 0) { chatService = rfcommServices.Services[0]; } else { rootPage.NotifyUser( "Could not discover the chat service on the remote device", NotifyType.StatusMessage); ResetMainUI(); return; } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId)) { rootPage.NotifyUser( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); ResetMainUI(); return; } var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SdpServiceNameAttributeType) { rootPage.NotifyUser( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); ResetMainUI(); return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; StopWatcher(); lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); SetChatUI(attributeReader.ReadString(serviceNameLength), bluetoothDevice.Name); chatWriter = new DataWriter(chatSocket.OutputStream); DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveStringLoop(chatReader); } catch (Exception ex) when ((uint)ex.HResult == 0x80070490) // ERROR_ELEMENT_NOT_FOUND { rootPage.NotifyUser("Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); ResetMainUI(); } catch (Exception ex) when ((uint)ex.HResult == 0x80072740) // WSAEADDRINUSE { rootPage.NotifyUser("Please verify that there is no other RFCOMM connection to the same device.", NotifyType.ErrorMessage); ResetMainUI(); } } /// <summary> /// If you believe the Bluetooth device will eventually be paired with Windows, /// you might want to pre-emptively get consent to access the device. /// An explicit call to RequestAccessAsync() prompts the user for consent. /// If this is not done, a device that's working before being paired, /// will no longer work after being paired. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void RequestAccessButton_Click(object sender, RoutedEventArgs e) { // Make sure user has given consent to access device DeviceAccessStatus accessStatus = await bluetoothDevice.RequestAccessAsync(); if (accessStatus != DeviceAccessStatus.Allowed) { rootPage.NotifyUser( "Access to the device is denied because the application was not granted access", NotifyType.StatusMessage); } else { rootPage.NotifyUser( "Access granted, you are free to pair devices", NotifyType.StatusMessage); } } private void SendButton_Click(object sender, RoutedEventArgs e) { SendMessage(); } public void KeyboardKey_Pressed(object sender, KeyRoutedEventArgs e) { if (e.Key == Windows.System.VirtualKey.Enter) { SendMessage(); } } /// <summary> /// Takes the contents of the MessageTextBox and writes it to the outgoing chatWriter /// </summary> private async void SendMessage() { try { if (MessageTextBox.Text.Length != 0) { chatWriter.WriteUInt32((uint)MessageTextBox.Text.Length); chatWriter.WriteString(MessageTextBox.Text); ConversationList.Items.Add("Sent: " + MessageTextBox.Text); MessageTextBox.Text = ""; await chatWriter.StoreAsync(); } } catch (Exception ex) when ((uint)ex.HResult == 0x80072745) { // The remote device has disconnected the connection rootPage.NotifyUser("Remote side disconnect: " + ex.HResult.ToString() + " - " + ex.Message, NotifyType.StatusMessage); } } private async void ReceiveStringLoop(DataReader chatReader) { try { uint size = await chatReader.LoadAsync(sizeof(uint)); if (size < sizeof(uint)) { Disconnect("Remote device terminated connection - make sure only one instance of server is running on remote device"); return; } uint stringLength = chatReader.ReadUInt32(); uint actualStringLength = await chatReader.LoadAsync(stringLength); if (actualStringLength != stringLength) { // The underlying socket was closed before we were able to read the whole data return; } ConversationList.Items.Add("Received: " + chatReader.ReadString(stringLength)); ReceiveStringLoop(chatReader); } catch (Exception ex) { lock (this) { if (chatSocket == null) { // Do not print anything here - the user closed the socket. if ((uint)ex.HResult == 0x80072745) rootPage.NotifyUser("Disconnect triggered by remote device", NotifyType.StatusMessage); else if ((uint)ex.HResult == 0x800703E3) rootPage.NotifyUser("The I/O operation has been aborted because of either a thread exit or an application request.", NotifyType.StatusMessage); } else { Disconnect("Read stream failed with error: " + ex.Message); } } } } private void DisconnectButton_Click(object sender, RoutedEventArgs e) { Disconnect("Disconnected"); } /// <summary> /// Cleans up the socket and DataWriter and reset the UI /// </summary> /// <param name="disconnectReason"></param> private void Disconnect(string disconnectReason) { if (chatWriter != null) { chatWriter.DetachStream(); chatWriter = null; } if (chatService != null) { chatService.Dispose(); chatService = null; } lock (this) { if (chatSocket != null) { chatSocket.Dispose(); chatSocket = null; } } rootPage.NotifyUser(disconnectReason, NotifyType.StatusMessage); ResetMainUI(); } private void SetChatUI(string serviceName, string deviceName) { rootPage.NotifyUser("Connected", NotifyType.StatusMessage); ServiceName.Text = "Service Name: " + serviceName; DeviceName.Text = "Connected to: " + deviceName; RunButton.IsEnabled = false; ConnectButton.Visibility = Visibility.Collapsed; RequestAccessButton.Visibility = Visibility.Visible; resultsListView.IsEnabled = false; resultsListView.Visibility = Visibility.Collapsed; ChatBox.Visibility = Visibility.Visible; } private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { UpdatePairingButtons(); } private void UpdatePairingButtons() { RfcommChatDeviceDisplay deviceDisp = (RfcommChatDeviceDisplay)resultsListView.SelectedItem; if (null != deviceDisp) { ConnectButton.IsEnabled = true; } else { ConnectButton.IsEnabled = false; } } } public class RfcommChatDeviceDisplay : INotifyPropertyChanged { private DeviceInformation deviceInfo; public RfcommChatDeviceDisplay(DeviceInformation deviceInfoIn) { deviceInfo = deviceInfoIn; UpdateGlyphBitmapImage(); } public DeviceInformation DeviceInformation { get { return deviceInfo; } private set { deviceInfo = value; } } public string Id { get { return deviceInfo.Id; } } public string Name { get { return deviceInfo.Name; } } public BitmapImage GlyphBitmapImage { get; private set; } public void Update(DeviceInformationUpdate deviceInfoUpdate) { deviceInfo.Update(deviceInfoUpdate); UpdateGlyphBitmapImage(); } private async void UpdateGlyphBitmapImage() { DeviceThumbnail deviceThumbnail = await deviceInfo.GetGlyphThumbnailAsync(); BitmapImage glyphBitmapImage = new BitmapImage(); await glyphBitmapImage.SetSourceAsync(deviceThumbnail); GlyphBitmapImage = glyphBitmapImage; OnPropertyChanged("GlyphBitmapImage"); } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; namespace Unity.Appodeal.Xcode { public class PlistElement { protected PlistElement() {} // convenience methods public string AsString() { return ((PlistElementString)this).value; } public int AsInteger() { return ((PlistElementInteger)this).value; } public bool AsBoolean() { return ((PlistElementBoolean)this).value; } public PlistElementArray AsArray() { return (PlistElementArray)this; } public PlistElementDict AsDict() { return (PlistElementDict)this; } public PlistElement this[string key] { get { return AsDict()[key]; } set { AsDict()[key] = value; } } } public class PlistElementString : PlistElement { public PlistElementString(string v) { value = v; } public string value; } public class PlistElementInteger : PlistElement { public PlistElementInteger(int v) { value = v; } public int value; } public class PlistElementBoolean : PlistElement { public PlistElementBoolean(bool v) { value = v; } public bool value; } public class PlistElementDict : PlistElement { public PlistElementDict() : base() {} private SortedDictionary<string, PlistElement> m_PrivateValue = new SortedDictionary<string, PlistElement>(); public IDictionary<string, PlistElement> values { get { return m_PrivateValue; }} new public PlistElement this[string key] { get { if (values.ContainsKey(key)) return values[key]; return null; } set { this.values[key] = value; } } // convenience methods public void SetInteger(string key, int val) { values[key] = new PlistElementInteger(val); } public void SetString(string key, string val) { values[key] = new PlistElementString(val); } public void SetBoolean(string key, bool val) { values[key] = new PlistElementBoolean(val); } public PlistElementArray CreateArray(string key) { var v = new PlistElementArray(); values[key] = v; return v; } public PlistElementDict CreateDict(string key) { var v = new PlistElementDict(); values[key] = v; return v; } } public class PlistElementArray : PlistElement { public PlistElementArray() : base() {} public List<PlistElement> values = new List<PlistElement>(); // convenience methods public void AddString(string val) { values.Add(new PlistElementString(val)); } public void AddInteger(int val) { values.Add(new PlistElementInteger(val)); } public void AddBoolean(bool val) { values.Add(new PlistElementBoolean(val)); } public PlistElementArray AddArray() { var v = new PlistElementArray(); values.Add(v); return v; } public PlistElementDict AddDict() { var v = new PlistElementDict(); values.Add(v); return v; } } public class PlistDocument { public PlistElementDict root; public string version; public PlistDocument() { root = new PlistElementDict(); version = "1.0"; } // Parses a string that contains a XML file. No validation is done. internal static XDocument ParseXmlNoDtd(string text) { XmlReaderSettings settings = new XmlReaderSettings(); settings.ProhibitDtd = false; settings.XmlResolver = null; // prevent DTD download XmlReader xmlReader = XmlReader.Create(new StringReader(text), settings); return XDocument.Load(xmlReader); } // LINQ serializes XML DTD declaration with an explicit empty 'internal subset' // (a pair of square brackets at the end of Doctype declaration). // Even though this is valid XML, XCode does not like it, hence this workaround. internal static string CleanDtdToString(XDocument doc) { // LINQ does not support changing the DTD of existing XDocument instances, // so we create a dummy document for printing of the Doctype declaration. // A single dummy element is added to force LINQ not to omit the declaration. // Also, utf-8 encoding is forced since this is the encoding we use when writing to file in UpdateInfoPlist. if (doc.DocumentType != null) { XDocument tmpDoc = new XDocument(new XDeclaration("1.0", "utf-8", null), new XDocumentType(doc.DocumentType.Name, doc.DocumentType.PublicId, doc.DocumentType.SystemId, null), new XElement(doc.Root.Name)); return "" + tmpDoc.Declaration + "\n" + tmpDoc.DocumentType + "\n" + doc.Root; } else { XDocument tmpDoc = new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement(doc.Root.Name)); return "" + tmpDoc.Declaration + Environment.NewLine + doc.Root; } } private static string GetText(XElement xml) { return String.Join("", xml.Nodes().OfType<XText>().Select(x => x.Value).ToArray()); } private static PlistElement ReadElement(XElement xml) { switch (xml.Name.LocalName) { case "dict": { List<XElement> children = xml.Elements().ToList(); var el = new PlistElementDict(); if (children.Count % 2 == 1) throw new Exception("Malformed plist file"); for (int i = 0; i < children.Count - 1; i++) { if (children[i].Name != "key") throw new Exception("Malformed plist file"); string key = GetText(children[i]).Trim(); var newChild = ReadElement(children[i+1]); if (newChild != null) { i++; el[key] = newChild; } } return el; } case "array": { List<XElement> children = xml.Elements().ToList(); var el = new PlistElementArray(); foreach (var childXml in children) { var newChild = ReadElement(childXml); if (newChild != null) el.values.Add(newChild); } return el; } case "string": return new PlistElementString(GetText(xml)); case "integer": { int r; if (int.TryParse(GetText(xml), out r)) return new PlistElementInteger(r); return null; } case "true": return new PlistElementBoolean(true); case "false": return new PlistElementBoolean(false); default: return null; } } public void ReadFromFile(string path) { ReadFromString(File.ReadAllText(path)); } public void ReadFromStream(TextReader tr) { ReadFromString(tr.ReadToEnd()); } public void ReadFromString(string text) { XDocument doc = ParseXmlNoDtd(text); version = (string) doc.Root.Attribute("version"); XElement xml = doc.XPathSelectElement("plist/dict"); var dict = ReadElement(xml); if (dict == null) throw new Exception("Error parsing plist file"); root = dict as PlistElementDict; if (root == null) throw new Exception("Malformed plist file"); } private static XElement WriteElement(PlistElement el) { if (el is PlistElementBoolean) { var realEl = el as PlistElementBoolean; return new XElement(realEl.value ? "true" : "false"); } if (el is PlistElementInteger) { var realEl = el as PlistElementInteger; return new XElement("integer", realEl.value.ToString()); } if (el is PlistElementString) { var realEl = el as PlistElementString; return new XElement("string", realEl.value); } if (el is PlistElementDict) { var realEl = el as PlistElementDict; var dictXml = new XElement("dict"); foreach (var kv in realEl.values) { var keyXml = new XElement("key", kv.Key); var valueXml = WriteElement(kv.Value); if (valueXml != null) { dictXml.Add(keyXml); dictXml.Add(valueXml); } } return dictXml; } if (el is PlistElementArray) { var realEl = el as PlistElementArray; var arrayXml = new XElement("array"); foreach (var v in realEl.values) { var elXml = WriteElement(v); if (elXml != null) arrayXml.Add(elXml); } return arrayXml; } return null; } public void WriteToFile(string path) { File.WriteAllText(path, WriteToString()); } public void WriteToStream(TextWriter tw) { tw.Write(WriteToString()); } public string WriteToString() { var el = WriteElement(root); var rootEl = new XElement("plist"); rootEl.Add(new XAttribute("version", version)); rootEl.Add(el); var doc = new XDocument(); doc.Add(rootEl); return CleanDtdToString(doc); } } } // namespace Unity.Appodeal.Xcode
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Timers; using log4net; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim { /// <summary> /// Interactive OpenSim region server /// </summary> public class OpenSim : OpenSimBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_startupCommandsFile; protected string m_shutdownCommandsFile; protected bool m_gui = false; protected string m_consoleType = "local"; protected uint m_consolePort = 0; /// <summary> /// Prompt to use for simulator command line. /// </summary> private string m_consolePrompt; /// <summary> /// Regex for parsing out special characters in the prompt. /// </summary> private Regex m_consolePromptRegex = new Regex(@"([^\\])\\(\w)", RegexOptions.Compiled); private string m_timedScript = "disabled"; private int m_timeInterval = 1200; private Timer m_scriptTimer; public OpenSim(IConfigSource configSource) : base(configSource) { } protected override void ReadExtraConfigSettings() { base.ReadExtraConfigSettings(); IConfig startupConfig = Config.Configs["Startup"]; IConfig networkConfig = Config.Configs["Network"]; int stpMinThreads = 2; int stpMaxThreads = 15; if (startupConfig != null) { m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt"); m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt"); if (startupConfig.GetString("console", String.Empty) == String.Empty) m_gui = startupConfig.GetBoolean("gui", false); else m_consoleType= startupConfig.GetString("console", String.Empty); if (networkConfig != null) m_consolePort = (uint)networkConfig.GetInt("console_port", 0); m_timedScript = startupConfig.GetString("timer_Script", "disabled"); if (m_timedScript != "disabled") { m_timeInterval = startupConfig.GetInt("timer_Interval", 1200); } string asyncCallMethodStr = startupConfig.GetString("async_call_method", String.Empty); FireAndForgetMethod asyncCallMethod; if (!String.IsNullOrEmpty(asyncCallMethodStr) && Utils.EnumTryParse<FireAndForgetMethod>(asyncCallMethodStr, out asyncCallMethod)) Util.FireAndForgetMethod = asyncCallMethod; stpMinThreads = startupConfig.GetInt("MinPoolThreads", 15); stpMaxThreads = startupConfig.GetInt("MaxPoolThreads", 15); m_consolePrompt = startupConfig.GetString("ConsolePrompt", @"Region (\R) "); } if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool) Util.InitThreadPool(stpMinThreads, stpMaxThreads); m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod); } /// <summary> /// Performs initialisation of the scene, such as loading configuration from disk. /// </summary> protected override void StartupSpecific() { m_log.Info("===================================================================="); m_log.Info("========================= STARTING OPENSIM ========================="); m_log.Info("===================================================================="); //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString()); // http://msdn.microsoft.com/en-us/library/bb384202.aspx //GCSettings.LatencyMode = GCLatencyMode.Batch; //m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString()); if (m_gui) // Driven by external GUI { m_console = new CommandConsole("Region"); } else { switch (m_consoleType) { case "basic": m_console = new CommandConsole("Region"); break; case "rest": m_console = new RemoteConsole("Region"); ((RemoteConsole)m_console).ReadConfig(Config); break; default: m_console = new LocalConsole("Region"); break; } } MainConsole.Instance = m_console; LogEnvironmentInformation(); RegisterCommonAppenders(Config.Configs["Startup"]); RegisterConsoleCommands(); base.StartupSpecific(); MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler()); MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this)); if (userStatsURI != String.Empty) MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this)); if (managedStatsURI != String.Empty) { string urlBase = String.Format("/{0}/", managedStatsURI); MainServer.Instance.AddHTTPHandler(urlBase, StatsManager.HandleStatsRequest); m_log.InfoFormat("[OPENSIM] Enabling remote managed stats fetch. URL = {0}", urlBase); } if (m_console is RemoteConsole) { if (m_consolePort == 0) { ((RemoteConsole)m_console).SetServer(m_httpServer); } else { ((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort)); } } // Hook up to the watchdog timer Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler; PrintFileToConsole("startuplogo.txt"); // For now, start at the 'root' level by default if (SceneManager.Scenes.Count == 1) // If there is only one region, select it ChangeSelectedRegion("region", new string[] {"change", "region", SceneManager.Scenes[0].RegionInfo.RegionName}); else ChangeSelectedRegion("region", new string[] {"change", "region", "root"}); //Run Startup Commands if (String.IsNullOrEmpty(m_startupCommandsFile)) { m_log.Info("[STARTUP]: No startup command script specified. Moving on..."); } else { RunCommandScript(m_startupCommandsFile); } // Start timer script (run a script every xx seconds) if (m_timedScript != "disabled") { m_scriptTimer = new Timer(); m_scriptTimer.Enabled = true; m_scriptTimer.Interval = m_timeInterval*1000; m_scriptTimer.Elapsed += RunAutoTimerScript; } } /// <summary> /// Register standard set of region console commands /// </summary> private void RegisterConsoleCommands() { MainServer.RegisterHttpConsoleCommands(m_console); m_console.Commands.AddCommand("Objects", false, "force update", "force update", "Force the update of all objects on clients", HandleForceUpdate); m_console.Commands.AddCommand("General", false, "change region", "change region <region name>", "Change current console region", ChangeSelectedRegion); m_console.Commands.AddCommand("Archiving", false, "save xml", "save xml", "Save a region's data in XML format", SaveXml); m_console.Commands.AddCommand("Archiving", false, "save xml2", "save xml2", "Save a region's data in XML2 format", SaveXml2); m_console.Commands.AddCommand("Archiving", false, "load xml", "load xml [-newIDs [<x> <y> <z>]]", "Load a region's data from XML format", LoadXml); m_console.Commands.AddCommand("Archiving", false, "load xml2", "load xml2", "Load a region's data from XML2 format", LoadXml2); m_console.Commands.AddCommand("Archiving", false, "save prims xml2", "save prims xml2 [<prim name> <file name>]", "Save named prim to XML2", SavePrimsXml2); m_console.Commands.AddCommand("Archiving", false, "load oar", "load oar [--merge] [--skip-assets] [<OAR path>]", "Load a region's data from an OAR archive.", "--merge will merge the OAR with the existing scene." + Environment.NewLine + "--skip-assets will load the OAR but ignore the assets it contains." + Environment.NewLine + "The path can be either a filesystem location or a URI." + " If this is not given then the command looks for an OAR named region.oar in the current directory.", LoadOar); m_console.Commands.AddCommand("Archiving", false, "save oar", //"save oar [-v|--version=<N>] [-p|--profile=<url>] [<OAR path>]", "save oar [-h|--home=<url>] [--noassets] [--publish] [--perm=<permissions>] [--all] [<OAR path>]", "Save a region's data to an OAR archive.", // "-v|--version=<N> generates scene objects as per older versions of the serialization (e.g. -v=0)" + Environment.NewLine "-h|--home=<url> adds the url of the profile service to the saved user information.\n" + "--noassets stops assets being saved to the OAR.\n" + "--publish saves an OAR stripped of owner and last owner information.\n" + " on reload, the estate owner will be the owner of all objects\n" + " this is useful if you're making oars generally available that might be reloaded to the same grid from which you published\n" + "--perm=<permissions> stops objects with insufficient permissions from being saved to the OAR.\n" + " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer\n" + "--all saves all the regions in the simulator, instead of just the current region.\n" + "The OAR path must be a filesystem path." + " If this is not given then the oar is saved to region.oar in the current directory.", SaveOar); m_console.Commands.AddCommand("Objects", false, "edit scale", "edit scale <name> <x> <y> <z>", "Change the scale of a named prim", HandleEditScale); m_console.Commands.AddCommand("Users", false, "kick user", "kick user <first> <last> [--force] [message]", "Kick a user off the simulator", "The --force option will kick the user without any checks to see whether it's already in the process of closing\n" + "Only use this option if you are sure the avatar is inactive and a normal kick user operation does not removed them", KickUserCommand); m_console.Commands.AddCommand("Users", false, "show users", "show users [full]", "Show user data for users currently on the region", "Without the 'full' option, only users actually on the region are shown." + " With the 'full' option child agents of users in neighbouring regions are also shown.", HandleShow); m_console.Commands.AddCommand("Comms", false, "show connections", "show connections", "Show connection data", HandleShow); m_console.Commands.AddCommand("Comms", false, "show circuits", "show circuits", "Show agent circuit data", HandleShow); m_console.Commands.AddCommand("Comms", false, "show pending-objects", "show pending-objects", "Show # of objects on the pending queues of all scene viewers", HandleShow); m_console.Commands.AddCommand("General", false, "show modules", "show modules", "Show module data", HandleShow); m_console.Commands.AddCommand("Regions", false, "show regions", "show regions", "Show region data", HandleShow); m_console.Commands.AddCommand("Regions", false, "show ratings", "show ratings", "Show rating data", HandleShow); m_console.Commands.AddCommand("Objects", false, "backup", "backup", "Persist currently unsaved object changes immediately instead of waiting for the normal persistence call.", RunCommand); m_console.Commands.AddCommand("Regions", false, "create region", "create region [\"region name\"] <region_file.ini>", "Create a new region.", "The settings for \"region name\" are read from <region_file.ini>. Paths specified with <region_file.ini> are relative to your Regions directory, unless an absolute path is given." + " If \"region name\" does not exist in <region_file.ini>, it will be added." + Environment.NewLine + "Without \"region name\", the first region found in <region_file.ini> will be created." + Environment.NewLine + "If <region_file.ini> does not exist, it will be created.", HandleCreateRegion); m_console.Commands.AddCommand("Regions", false, "restart", "restart", "Restart all sims in this instance", RunCommand); m_console.Commands.AddCommand("General", false, "command-script", "command-script <script>", "Run a command script from file", RunCommand); m_console.Commands.AddCommand("Regions", false, "remove-region", "remove-region <name>", "Remove a region from this simulator", RunCommand); m_console.Commands.AddCommand("Regions", false, "delete-region", "delete-region <name>", "Delete a region from disk", RunCommand); } protected override void ShutdownSpecific() { if (m_shutdownCommandsFile != String.Empty) { RunCommandScript(m_shutdownCommandsFile); } base.ShutdownSpecific(); } /// <summary> /// Timer to run a specific text file as console commands. Configured in in the main ini file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RunAutoTimerScript(object sender, EventArgs e) { if (m_timedScript != "disabled") { RunCommandScript(m_timedScript); } } private void WatchdogTimeoutHandler(Watchdog.ThreadWatchdogInfo twi) { int now = Environment.TickCount & Int32.MaxValue; m_log.ErrorFormat( "[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago. {3}", twi.Thread.Name, twi.Thread.ThreadState, now - twi.LastTick, twi.AlarmMethod != null ? string.Format("Data: {0}", twi.AlarmMethod()) : ""); } #region Console Commands /// <summary> /// Kicks users off the region /// </summary> /// <param name="module"></param> /// <param name="cmdparams">name of avatar to kick</param> private void KickUserCommand(string module, string[] cmdparams) { bool force = false; OptionSet options = new OptionSet().Add("f|force", delegate (string v) { force = v != null; }); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 4) return; string alert = null; if (mainParams.Count > 4) alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4)); IList agents = SceneManager.GetCurrentSceneAvatars(); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; if (presence.Firstname.ToLower().Equals(mainParams[2].ToLower()) && presence.Lastname.ToLower().Equals(mainParams[3].ToLower())) { MainConsole.Instance.Output( String.Format( "Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}", presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName)); // kick client... if (alert != null) presence.ControllingClient.Kick(alert); else presence.ControllingClient.Kick("\nThe OpenSim manager kicked you out.\n"); presence.Scene.CloseAgent(presence.UUID, force); break; } } MainConsole.Instance.Output(""); } /// <summary> /// Opens a file and uses it as input to the console command parser. /// </summary> /// <param name="fileName">name of file to use as input to the console</param> private static void PrintFileToConsole(string fileName) { if (File.Exists(fileName)) { StreamReader readFile = File.OpenText(fileName); string currentLine; while ((currentLine = readFile.ReadLine()) != null) { m_log.Info("[!]" + currentLine); } } } /// <summary> /// Force resending of all updates to all clients in active region(s) /// </summary> /// <param name="module"></param> /// <param name="args"></param> private void HandleForceUpdate(string module, string[] args) { MainConsole.Instance.Output("Updating all clients"); SceneManager.ForceCurrentSceneClientUpdate(); } /// <summary> /// Edits the scale of a primative with the name specified /// </summary> /// <param name="module"></param> /// <param name="args">0,1, name, x, y, z</param> private void HandleEditScale(string module, string[] args) { if (args.Length == 6) { SceneManager.HandleEditCommandOnCurrentScene(args); } else { MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>"); } } /// <summary> /// Creates a new region based on the parameters specified. This will ask the user questions on the console /// </summary> /// <param name="module"></param> /// <param name="cmd">0,1,region name, region ini or XML file</param> private void HandleCreateRegion(string module, string[] cmd) { string regionName = string.Empty; string regionFile = string.Empty; if (cmd.Length == 3) { regionFile = cmd[2]; } else if (cmd.Length > 3) { regionName = cmd[2]; regionFile = cmd[3]; } string extension = Path.GetExtension(regionFile).ToLower(); bool isXml = extension.Equals(".xml"); bool isIni = extension.Equals(".ini"); if (!isXml && !isIni) { MainConsole.Instance.Output("Usage: create region [\"region name\"] <region_file.ini>"); return; } if (!Path.IsPathRooted(regionFile)) { string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim(); regionFile = Path.Combine(regionsDir, regionFile); } RegionInfo regInfo; if (isXml) { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source); } else { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source, regionName); } Scene existingScene; if (SceneManager.TryGetScene(regInfo.RegionID, out existingScene)) { MainConsole.Instance.OutputFormat( "ERROR: Cannot create region {0} with ID {1}, this ID is already assigned to region {2}", regInfo.RegionName, regInfo.RegionID, existingScene.RegionInfo.RegionName); return; } bool changed = PopulateRegionEstateInfo(regInfo); IScene scene; CreateRegion(regInfo, true, out scene); if (changed) regInfo.EstateSettings.Save(); } /// <summary> /// Runs commands issued by the server console from the operator /// </summary> /// <param name="command">The first argument of the parameter (the command)</param> /// <param name="cmdparams">Additional arguments passed to the command</param> public void RunCommand(string module, string[] cmdparams) { List<string> args = new List<string>(cmdparams); if (args.Count < 1) return; string command = args[0]; args.RemoveAt(0); cmdparams = args.ToArray(); switch (command) { case "backup": MainConsole.Instance.Output("Triggering save of pending object updates to persistent store"); SceneManager.BackupCurrentScene(); break; case "remove-region": string regRemoveName = CombineParams(cmdparams, 0); Scene removeScene; if (SceneManager.TryGetScene(regRemoveName, out removeScene)) RemoveRegion(removeScene, false); else MainConsole.Instance.Output("No region with that name"); break; case "delete-region": string regDeleteName = CombineParams(cmdparams, 0); Scene killScene; if (SceneManager.TryGetScene(regDeleteName, out killScene)) RemoveRegion(killScene, true); else MainConsole.Instance.Output("no region with that name"); break; case "restart": SceneManager.RestartCurrentScene(); break; } } /// <summary> /// Change the currently selected region. The selected region is that operated upon by single region commands. /// </summary> /// <param name="cmdParams"></param> protected void ChangeSelectedRegion(string module, string[] cmdparams) { if (cmdparams.Length > 2) { string newRegionName = CombineParams(cmdparams, 2); if (!SceneManager.TrySetCurrentScene(newRegionName)) MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName)); else RefreshPrompt(); } else { MainConsole.Instance.Output("Usage: change region <region name>"); } } /// <summary> /// Refreshs prompt with the current selection details. /// </summary> private void RefreshPrompt() { string regionName = (SceneManager.CurrentScene == null ? "root" : SceneManager.CurrentScene.RegionInfo.RegionName); MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName)); // m_log.DebugFormat("Original prompt is {0}", m_consolePrompt); string prompt = m_consolePrompt; // Replace "\R" with the region name // Replace "\\" with "\" prompt = m_consolePromptRegex.Replace(prompt, m => { // m_log.DebugFormat("Matched {0}", m.Groups[2].Value); if (m.Groups[2].Value == "R") return m.Groups[1].Value + regionName; else return m.Groups[0].Value; }); m_console.DefaultPrompt = prompt; m_console.ConsoleScene = SceneManager.CurrentScene; } protected override void HandleRestartRegion(RegionInfo whichRegion) { base.HandleRestartRegion(whichRegion); // Where we are restarting multiple scenes at once, a previous call to RefreshPrompt may have set the // m_console.ConsoleScene to null (indicating all scenes). if (m_console.ConsoleScene != null && whichRegion.RegionName == ((Scene)m_console.ConsoleScene).Name) SceneManager.TrySetCurrentScene(whichRegion.RegionName); RefreshPrompt(); } // see BaseOpenSimServer /// <summary> /// Many commands list objects for debugging. Some of the types are listed here /// </summary> /// <param name="mod"></param> /// <param name="cmd"></param> public override void HandleShow(string mod, string[] cmd) { base.HandleShow(mod, cmd); List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "users": IList agents; if (showParams.Length > 1 && showParams[1] == "full") { agents = SceneManager.GetCurrentScenePresences(); } else { agents = SceneManager.GetCurrentSceneAvatars(); } MainConsole.Instance.Output(String.Format("\nAgents connected: {0}\n", agents.Count)); MainConsole.Instance.Output( String.Format("{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", "Firstname", "Lastname", "Agent ID", "Root/Child", "Region", "Position") ); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; string regionName; if (regionInfo == null) { regionName = "Unresolvable"; } else { regionName = regionInfo.RegionName; } MainConsole.Instance.Output( String.Format( "{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", presence.Firstname, presence.Lastname, presence.UUID, presence.IsChildAgent ? "Child" : "Root", regionName, presence.AbsolutePosition.ToString()) ); } MainConsole.Instance.Output(String.Empty); break; case "connections": HandleShowConnections(); break; case "circuits": HandleShowCircuits(); break; case "modules": SceneManager.ForEachSelectedScene( scene => { MainConsole.Instance.OutputFormat("Loaded region modules in {0} are:", scene.Name); List<IRegionModuleBase> sharedModules = new List<IRegionModuleBase>(); List<IRegionModuleBase> nonSharedModules = new List<IRegionModuleBase>(); foreach (IRegionModuleBase module in scene.RegionModules.Values) { if (module.GetType().GetInterface("ISharedRegionModule") != null) nonSharedModules.Add(module); else sharedModules.Add(module); } foreach (IRegionModuleBase module in sharedModules.OrderBy(m => m.Name)) MainConsole.Instance.OutputFormat("New Region Module (Shared): {0}", module.Name); foreach (IRegionModuleBase module in nonSharedModules.OrderBy(m => m.Name)) MainConsole.Instance.OutputFormat("New Region Module (Non-Shared): {0}", module.Name); } ); MainConsole.Instance.Output(""); break; case "regions": SceneManager.ForEachScene( delegate(Scene scene) { MainConsole.Instance.Output(String.Format( "Region Name: {0}, Region XLoc: {1}, Region YLoc: {2}, Region Port: {3}, Estate Name: {4}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY, scene.RegionInfo.InternalEndPoint.Port, scene.RegionInfo.EstateSettings.EstateName)); }); break; case "ratings": SceneManager.ForEachScene( delegate(Scene scene) { string rating = ""; if (scene.RegionInfo.RegionSettings.Maturity == 1) { rating = "MATURE"; } else if (scene.RegionInfo.RegionSettings.Maturity == 2) { rating = "ADULT"; } else { rating = "PG"; } MainConsole.Instance.Output(String.Format( "Region Name: {0}, Region Rating {1}", scene.RegionInfo.RegionName, rating)); }); break; } } private void HandleShowCircuits() { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Region", 20); cdt.AddColumn("Avatar name", 24); cdt.AddColumn("Type", 5); cdt.AddColumn("Code", 10); cdt.AddColumn("IP", 16); cdt.AddColumn("Viewer Name", 24); SceneManager.ForEachScene( s => { foreach (AgentCircuitData aCircuit in s.AuthenticateHandler.GetAgentCircuits().Values) cdt.AddRow( s.Name, aCircuit.Name, aCircuit.child ? "child" : "root", aCircuit.circuitcode.ToString(), aCircuit.IPAddress != null ? aCircuit.IPAddress.ToString() : "not set", aCircuit.Viewer); }); MainConsole.Instance.Output(cdt.ToString()); } private void HandleShowConnections() { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Region", 20); cdt.AddColumn("Avatar name", 24); cdt.AddColumn("Circuit code", 12); cdt.AddColumn("Endpoint", 23); cdt.AddColumn("Active?", 7); SceneManager.ForEachScene( s => s.ForEachClient( c => cdt.AddRow( s.Name, c.Name, c.CircuitCode.ToString(), c.RemoteEndPoint.ToString(), c.IsActive.ToString()))); MainConsole.Instance.Output(cdt.ToString()); } /// <summary> /// Use XML2 format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SavePrimsXml2(string module, string[] cmdparams) { if (cmdparams.Length > 5) { SceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]); } else { SceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Use XML format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, save-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use save-xml2, please file a mantis detailing the reason."); if (cmdparams.Length > 0) { SceneManager.SaveCurrentSceneToXml(cmdparams[2]); } else { SceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Loads data and region objects from XML format. /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, load-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use load-xml2, please file a mantis detailing the reason."); Vector3 loadOffset = new Vector3(0, 0, 0); if (cmdparams.Length > 2) { bool generateNewIDS = false; if (cmdparams.Length > 3) { if (cmdparams[3] == "-newUID") { generateNewIDS = true; } if (cmdparams.Length > 4) { loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo); if (cmdparams.Length > 5) { loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo); } if (cmdparams.Length > 6) { loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo); } MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z)); } } SceneManager.LoadCurrentSceneFromXml(cmdparams[2], generateNewIDS, loadOffset); } else { try { SceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>"); } } } /// <summary> /// Serialize region data to XML2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { SceneManager.SaveCurrentSceneToXml2(cmdparams[2]); } else { SceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Load region data from Xml2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { try { SceneManager.LoadCurrentSceneFromXml2(cmdparams[2]); } catch (FileNotFoundException) { MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>"); } } else { try { SceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>"); } } } /// <summary> /// Load a whole region from an opensimulator archive. /// </summary> /// <param name="cmdparams"></param> protected void LoadOar(string module, string[] cmdparams) { try { SceneManager.LoadArchiveToCurrentScene(cmdparams); } catch (Exception e) { MainConsole.Instance.Output(e.Message); } } /// <summary> /// Save a region to a file, including all the assets needed to restore it. /// </summary> /// <param name="cmdparams"></param> protected void SaveOar(string module, string[] cmdparams) { SceneManager.SaveCurrentSceneToArchive(cmdparams); } private static string CombineParams(string[] commandParams, int pos) { string result = String.Empty; for (int i = pos; i < commandParams.Length; i++) { result += commandParams[i] + " "; } result = result.TrimEnd(' '); return result; } #endregion } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using Autodesk.Revit.DB; namespace Revit.SDK.Samples.Reinforcement.CS { #region Struct Definition /// <summary> /// a struct to store the geometry information of the rebar /// </summary> public struct RebarGeometry { // Private members Autodesk.Revit.DB.XYZ m_normal; // the direction of rebar distribution IList<Curve> m_curves; //the profile of the rebar int m_number; //the number of the rebar double m_spacing; //the spacing of the rebar /// <summary> /// get and set the value of the normal /// </summary> public Autodesk.Revit.DB.XYZ Normal { get { return m_normal; } set { m_normal = value; } } /// <summary> /// get and set the value of curve array /// </summary> public IList<Curve> Curves { get { return m_curves; } set { m_curves = value; } } /// <summary> /// get and set the number of the rebar /// </summary> public int RebarNumber { get { return m_number; } set { m_number = value; } } /// <summary> /// get and set the value of the rebar spacing /// </summary> public double RebarSpacing { get { return m_spacing; } set { m_spacing = value; } } /// <summary> /// consturctor /// </summary> /// <param name="normal">the normal information</param> /// <param name="curves">the profile of the rebars</param> /// <param name="number">the number of the rebar</param> /// <param name="spacing">the number of the rebar</param> public RebarGeometry(Autodesk.Revit.DB.XYZ normal, IList<Curve> curves, int number, double spacing) { // initialize the data members m_normal = normal; m_curves = curves; m_number = number; m_spacing = spacing; } } /// <summary> /// A struct to store the const data which support beam reinforcement creation /// </summary> public struct BeamRebarData { /// <summary> /// offset value of the top end rebar /// </summary> public const double TopEndOffset = 0.2; /// <summary> ///offset value of the top center rebar /// </summary> public const double TopCenterOffset = 0.23; /// <summary> /// offset value of the transverse rebar /// </summary> public const double TransverseOffset = 0.125; /// <summary> /// offset value of the end transverse rebar /// </summary> public const double TransverseEndOffset = 1.2; /// <summary> /// the spacing value between end and center transvers rebar /// </summary> public const double TransverseSpaceBetween = 1; /// <summary> ///offset value of bottom rebar /// </summary> public const double BottomOffset = 0.271; /// <summary> /// number of bottom rebar /// </summary> public const int BottomRebarNumber = 5; /// <summary> /// number of top rebar /// </summary> public const int TopRebarNumber = 2; } /// <summary> /// A struct to store the const data which support column reinforcement creation /// </summary> public struct ColumnRebarData { /// <summary> /// offset value of transverse rebar /// </summary> public const double TransverseOffset = 0.125; /// <summary> /// offset value of vertical rebar /// </summary> public const double VerticalOffset = 0.234; } #endregion #region Enum Definition /// <summary> /// Indicate location of top rebar /// </summary> public enum TopRebarLocation { /// <summary> /// locate start /// </summary> Start, /// <summary> /// locate center /// </summary> Center, /// <summary> /// locate end /// </summary> End } /// <summary> /// Indicate location of transverse rebar /// </summary> public enum TransverseRebarLocation { /// <summary> /// locate start /// </summary> Start, /// <summary> /// locate center /// </summary> Center, /// <summary> /// locate end /// </summary> End } /// <summary> /// Indicate location of vertical rebar /// </summary> public enum VerticalRebarLocation { /// <summary> /// locate north /// </summary> North, /// <summary> /// locate east /// </summary> East, /// <summary> /// locate south /// </summary> South, /// <summary> /// locate west /// </summary> West } #endregion /// <summary> /// A comparer for XYZ, and give a method to sort all the Autodesk.Revit.DB.XYZ points in a array /// </summary> public class XYZHeightComparer : IComparer<Autodesk.Revit.DB.XYZ> { int IComparer<Autodesk.Revit.DB.XYZ>.Compare(Autodesk.Revit.DB.XYZ first, Autodesk.Revit.DB.XYZ second) { // first compare z coordinate, then y coordinate, at last x coordinate if (GeomUtil.IsEqual(first.Z, second.Z)) { if (GeomUtil.IsEqual(first.Y, second.Y)) { if (GeomUtil.IsEqual(first.X, second.X)) { return 0; } return (first.X > second.X) ? 1 : -1; } return (first.Y > second.Y) ? 1 : -1; } return (first.Z > second.Z) ? 1 : -1; } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Xaml.PropertyGrid.Xaml File: PropertyGridEx.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Xaml.PropertyGrid { using System; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using Ecng.Common; using Ecng.Configuration; using Ecng.Xaml; using MoreLinq; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Xaml; using Xceed.Wpf.Toolkit; using Xceed.Wpf.Toolkit.Primitives; using Xceed.Wpf.Toolkit.PropertyGrid; using Selector = System.Windows.Controls.Primitives.Selector; class EnumComboBoxEx : ComboBox { public static readonly DependencyProperty SelectedEnumItemProperty = DependencyProperty.Register(nameof(SelectedEnumItem), typeof(object), typeof(EnumComboBoxEx), new PropertyMetadata((s, e) => { var ctrl = s as EnumComboBoxEx; if (ctrl == null) return; if (e.NewValue != null && ctrl.ItemsSource == null) ctrl.SetDataSource(e.NewValue.GetType()); ctrl.SelectedValue = e.NewValue; })); public object SelectedEnumItem { get { return GetValue(SelectedEnumItemProperty); } set { SetValue(SelectedEnumItemProperty, value); } } protected override void OnSelectionChanged(SelectionChangedEventArgs e) { base.OnSelectionChanged(e); SelectedEnumItem = this.GetSelectedValue(); } } /// <summary> /// The extended table of settings. /// </summary> public partial class PropertyGridEx { //private sealed class DefaultValueConverter : IValueConverter //{ // public object Convert(object value, Type targetType, object parameter, CultureInfo culture) // { // var item = value as PropertyItem; // if (item == null) // return null; // var attr = item.PropertyDescriptor.Attributes.OfType<DefaultValueAttribute>().FirstOrDefault(); // return attr != null ? attr.Value : null; // } // public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) // { // throw new NotSupportedException(); // } //} private static readonly ReadOnlyTypeDescriptionProvider _provider = new ReadOnlyTypeDescriptionProvider(); /// <summary> /// To open the enclosed properties by default. /// </summary> public bool AutoExpandProperties { get; set; } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="SecurityProvider"/>. /// </summary> public static readonly DependencyProperty SecurityProviderProperty = DependencyProperty.Register(nameof(SecurityProvider), typeof(ISecurityProvider), typeof(PropertyGridEx)); /// <summary> /// The provider of information about instruments. /// </summary> public ISecurityProvider SecurityProvider { get { return (ISecurityProvider)GetValue(SecurityProviderProperty); } set { SetValue(SecurityProviderProperty, value); } } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="ExchangeInfoProvider"/>. /// </summary> public static readonly DependencyProperty ExchangeInfoProviderProperty = DependencyProperty.Register(nameof(ExchangeInfoProvider), typeof(IExchangeInfoProvider), typeof(PropertyGridEx)); /// <summary> /// The exchange boards provider. /// </summary> public IExchangeInfoProvider ExchangeInfoProvider { get { return (IExchangeInfoProvider)GetValue(ExchangeInfoProviderProperty); } set { SetValue(ExchangeInfoProviderProperty, value); } } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="Portfolios"/>. /// </summary> public static readonly DependencyProperty PortfoliosProperty = DependencyProperty.Register(nameof(Portfolios), typeof(ThreadSafeObservableCollection<Portfolio>), typeof(PropertyGridEx)); /// <summary> /// Available portfolios. /// </summary> public ThreadSafeObservableCollection<Portfolio> Portfolios { get { return (ThreadSafeObservableCollection<Portfolio>)GetValue(PortfoliosProperty); } set { SetValue(PortfoliosProperty, value); } } /// <summary> /// The value change handle. /// </summary> /// <param name="oldValue">Previous value.</param> /// <param name="newValue">The new value.</param> protected override void OnSelectedObjectChanged(object oldValue, object newValue) { base.OnSelectedObjectChanged(oldValue, newValue); oldValue.DoIf<object, INotifyPropertiesChanged>(o => o.PropertiesChanged -= OnPropertiesChanged); newValue.DoIf<object, INotifyPropertiesChanged>(o => o.PropertiesChanged += OnPropertiesChanged); if (!AutoExpandProperties) return; Properties .OfType<PropertyItemBase>() .Where(i => i.IsExpandable) .ForEach(i => i.IsExpanded = true); } private void OnPropertiesChanged() { GuiDispatcher.GlobalDispatcher.AddAction(() => { var value = SelectedObject; SelectedObject = null; SelectedObject = value; }); } private static void SetDescriptionsProvider(bool isReadOnly) { TypeDescriptor.RemoveProvider(_provider, typeof(object)); if (isReadOnly) TypeDescriptor.AddProvider(_provider, typeof(object)); } private static EditorTemplateDefinition CreateNullableDateTimeEditor() { var binding = new Binding { Path = new PropertyPath("Value"), Mode = BindingMode.TwoWay }; var element = new FrameworkElementFactory(typeof(DateTimePicker)); element.SetBinding(DateTimePicker.ValueProperty, binding); element.SetValue(BorderThicknessProperty, new Thickness(0)); element.SetValue(InputBase.TextAlignmentProperty, TextAlignment.Right); //element.SetValue(PartEditBox.CheckBoxVisibilityProperty, Visibility.Visible); element.SetValue(MarginProperty, new Thickness(5, 0, 0, 0)); var dataTemplate = new DataTemplate { VisualTree = element }; dataTemplate.Seal(); return new EditorTemplateDefinition { EditingTemplate = dataTemplate, TargetProperties = { new TargetPropertyType { Type = typeof(DateTime?), } }, }; } private static EditorTemplateDefinition CreateNullableTimeSpanEditor() { var binding = new Binding { Path = new PropertyPath("Value"), Mode = BindingMode.TwoWay }; var element = new FrameworkElementFactory(typeof(TimeSpanUpDown)); element.SetBinding(TimeSpanUpDown.ValueProperty, binding); //element.SetBinding(TimeSpanEditBox.InitialValueProperty, new Binding(".") { Converter = new DefaultValueConverter() }); element.SetValue(BorderThicknessProperty, new Thickness(0)); //element.SetValue(TimeSpanUpDown.FormatProperty, "d hh:mm:ss"); element.SetValue(InputBase.TextAlignmentProperty, TextAlignment.Right); //element.SetValue(PartEditBox.CheckBoxVisibilityProperty, Visibility.Visible); element.SetValue(MarginProperty, new Thickness(5, 0, 0, 0)); var dataTemplate = new DataTemplate { VisualTree = element }; dataTemplate.Seal(); return new EditorTemplateDefinition { EditingTemplate = dataTemplate, TargetProperties = { new TargetPropertyType { Type = typeof(TimeSpan?), } }, }; } private static EditorTemplateDefinition CreateNullableDateTimeOffsetEditor() { var binding = new Binding { Path = new PropertyPath("Value"), Mode = BindingMode.TwoWay }; var element = new FrameworkElementFactory(typeof(DateTimeOffsetEditor)); element.SetBinding(DateTimeOffsetEditor.OffsetProperty, binding); element.SetValue(BorderThicknessProperty, new Thickness(0)); element.SetValue(InputBase.TextAlignmentProperty, TextAlignment.Right); //element.SetValue(PartEditBox.CheckBoxVisibilityProperty, Visibility.Visible); element.SetValue(MarginProperty, new Thickness(5, 0, 0, 0)); var dataTemplate = new DataTemplate { VisualTree = element }; dataTemplate.Seal(); return new EditorTemplateDefinition { EditingTemplate = dataTemplate, TargetProperties = { new TargetPropertyType { Type = typeof(DateTimeOffset?), } }, }; } private static EditorTemplateDefinition CreateExtensionInfoEditor() { var binding = new Binding { Path = new PropertyPath("Value"), Mode = BindingMode.TwoWay }; var element = new FrameworkElementFactory(typeof(ExtensionInfoPicker)); element.SetBinding(ExtensionInfoPicker.SelectedExtensionInfoProperty, binding); var dataTemplate = new DataTemplate { VisualTree = element }; dataTemplate.Seal(); return new EditorTemplateDefinition { TargetProperties = { "ExtensionInfo" }, EditingTemplate = dataTemplate, }; } private static EditorTemplateDefinition CreateNullableEnumEditor<T>(bool isEditable = false) { var binding = new Binding { Path = new PropertyPath("Value"), Mode = BindingMode.TwoWay }; var element = new FrameworkElementFactory(typeof(EnumComboBox)); element.SetValue(EnumComboBox.EnumTypeProperty, typeof(T).GetUnderlyingType()); element.SetValue(ComboBox.IsEditableProperty, isEditable); element.SetBinding(Selector.SelectedValueProperty, binding); element.SetValue(BorderThicknessProperty, new Thickness(0)); element.SetValue(MarginProperty, new Thickness(0)); var dataTemplate = new DataTemplate { VisualTree = element }; dataTemplate.Seal(); return new EditorTemplateDefinition { EditingTemplate = dataTemplate, TargetProperties = { new TargetPropertyType { Type = typeof(T) } }, }; } /// <summary> /// Initializes a new instance of the <see cref="PropertyGridEx"/>. /// </summary> public PropertyGridEx() { InitializeComponent(); if (this.IsDesignMode()) return; SetDescriptionsProvider(false); EditorDefinitions.Add(CreateNullableDateTimeEditor()); EditorDefinitions.Add(CreateNullableTimeSpanEditor()); EditorDefinitions.Add(CreateNullableDateTimeOffsetEditor()); EditorDefinitions.Add(CreateExtensionInfoEditor()); EditorDefinitions.Add(CreateNullableEnumEditor<SecurityTypes?>()); EditorDefinitions.Add(CreateNullableEnumEditor<OptionTypes?>()); EditorDefinitions.Add(CreateNullableEnumEditor<TPlusLimits?>()); EditorDefinitions.Add(CreateNullableEnumEditor<CurrencyTypes?>(true)); SecurityProvider = ConfigManager.TryGetService<ISecurityProvider>(); ExchangeInfoProvider = ConfigManager.TryGetService<IExchangeInfoProvider>(); Portfolios = ConfigManager.TryGetService<ThreadSafeObservableCollection<Portfolio>>(); ConfigManager.ServiceRegistered += (t, s) => { var sp = s as ISecurityProvider; if (sp != null) { this.GuiAsync(() => { if (SecurityProvider == null) SecurityProvider = sp; }); } var ep = s as IExchangeInfoProvider; if (ep != null) { this.GuiAsync(() => { if (ExchangeInfoProvider == null) ExchangeInfoProvider = ep; }); } var portfolios = s as ThreadSafeObservableCollection<Portfolio>; if (portfolios != null) { this.GuiAsync(() => { if (Portfolios == null) Portfolios = portfolios; }); } }; } } }
namespace ZetaResourceEditor.UI.Helper.ExtendedWebBrowser { #region Using directives. // ---------------------------------------------------------------------- using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Windows.Forms; using IDataObject=System.Runtime.InteropServices.ComTypes.IDataObject; // ---------------------------------------------------------------------- #endregion ///////////////////////////////////////////////////////////////////////// /// <summary> /// Encapsulate native P/Invoke methods that must be compiled /// with the "unsafe" switch. /// </summary> public sealed class UnsafeNativeMethods { #region IDocHostUIHandler interface. // ------------------------------------------------------------------ /// <summary> /// /// </summary> [ComImport, Guid( @"BD3F23C0-D43E-11CF-893B-00AA00BDCE1A" ), ComVisible( true ), InterfaceType( ComInterfaceType.InterfaceIsIUnknown )] public interface IDocHostUIHandler { #region Interface members. [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int ShowContextMenu( [In, MarshalAs( UnmanagedType.U4 )] int dwID, [In] NativeMethods.POINT pt, [In, MarshalAs( UnmanagedType.Interface )] object pcmdtReserved, [In, MarshalAs( UnmanagedType.Interface )] object pdispReserved ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int GetHostInfo( [In, Out] NativeMethods.DOCHOSTUIINFO info ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int ShowUI( [In, MarshalAs( UnmanagedType.I4 )] int dwID, [In] IOleInPlaceActiveObject activeObject, [In] NativeMethods.IOleCommandTarget commandTarget, [In] IOleInPlaceFrame frame, [In] IOleInPlaceUIWindow doc ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int HideUI(); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int UpdateUI(); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int EnableModeless( [In, MarshalAs( UnmanagedType.Bool )] bool fEnable ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int OnDocWindowActivate( [In, MarshalAs( UnmanagedType.Bool )] bool fActivate ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int OnFrameWindowActivate( [In, MarshalAs( UnmanagedType.Bool )] bool fActivate ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int ResizeBorder( [In] NativeMethods.COMRECT rect, [In] IOleInPlaceUIWindow doc, bool fFrameWindow ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int TranslateAccelerator( [In] ref NativeMethods.MSG msg, [In] ref Guid group, [In, MarshalAs( UnmanagedType.I4 )] int nCmdID ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int GetOptionKeyPath( [Out, MarshalAs( UnmanagedType.LPArray )] string[] pbstrKey, [In, MarshalAs( UnmanagedType.U4 )] int dw ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int GetDropTarget( [In, MarshalAs( UnmanagedType.Interface )] IOleDropTarget pDropTarget, [MarshalAs( UnmanagedType.Interface )] out IOleDropTarget ppDropTarget ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int GetExternal( [MarshalAs( UnmanagedType.Interface )] out object ppDispatch ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int TranslateUrl( [In, MarshalAs( UnmanagedType.U4 )] int dwTranslate, [In, MarshalAs( UnmanagedType.LPWStr )] string strURLIn, [MarshalAs( UnmanagedType.LPWStr )] out string pstrURLOut ); [return: MarshalAs( UnmanagedType.I4 )] [PreserveSig] int FilterDataObject( IDataObject pDO, out IDataObject ppDORet ); #endregion } // ------------------------------------------------------------------ #endregion #region ICustomDoc interface. // ------------------------------------------------------------------ /// <summary> /// /// </summary> [ComImport, InterfaceType( ComInterfaceType.InterfaceIsIUnknown ), GuidAttribute( @"3050f3f0-98b5-11cf-bb82-00aa00bdce0b" )] internal interface ICustomDoc { #region Interface members. [PreserveSig] void SetUIHandler( IDocHostUIHandler pUIHandler ); #endregion } // ------------------------------------------------------------------ #endregion #region IOleInPlaceActiveObject interface. // ------------------------------------------------------------------ /// <summary> /// /// </summary> [ComImport, Guid( @"00000117-0000-0000-C000-000000000046" ), SuppressUnmanagedCodeSecurity, InterfaceType( ComInterfaceType.InterfaceIsIUnknown )] public interface IOleInPlaceActiveObject { #region Interface members. [PreserveSig] int GetWindow( out IntPtr hwnd ); void ContextSensitiveHelp( int fEnterMode ); [PreserveSig] int TranslateAccelerator( [In] ref NativeMethods.MSG lpmsg ); void OnFrameWindowActivate( bool fActivate ); void OnDocWindowActivate( int fActivate ); void ResizeBorder( [In] NativeMethods.COMRECT prcBorder, [In] IOleInPlaceUIWindow pUIWindow, bool fFrameWindow ); void EnableModeless( int fEnable ); #endregion } // ------------------------------------------------------------------ #endregion #region IOleInPlaceUIWindow interface. // ------------------------------------------------------------------ /// <summary> /// /// </summary> [ComImport, InterfaceType( ComInterfaceType.InterfaceIsIUnknown ), Guid( @"00000115-0000-0000-C000-000000000046" )] public interface IOleInPlaceUIWindow { #region Interface members. IntPtr GetWindow(); [PreserveSig] int ContextSensitiveHelp( int fEnterMode ); [PreserveSig] int GetBorder( [Out] NativeMethods.COMRECT lprectBorder ); [PreserveSig] int RequestBorderSpace( [In] NativeMethods.COMRECT pborderwidths ); [PreserveSig] int SetBorderSpace( [In] NativeMethods.COMRECT pborderwidths ); void SetActiveObject( [In, MarshalAs( UnmanagedType.Interface )] IOleInPlaceActiveObject pActiveObject, [In, MarshalAs( UnmanagedType.LPWStr )] string pszObjName ); #endregion } // ------------------------------------------------------------------ #endregion #region IOleDropTarget interface. // ------------------------------------------------------------------ /// <summary> /// /// </summary> [ComImport, Guid( @"00000122-0000-0000-C000-000000000046" ), InterfaceType( ComInterfaceType.InterfaceIsIUnknown )] public interface IOleDropTarget { #region Interface members. [PreserveSig] int OleDragEnter( [In, MarshalAs( UnmanagedType.Interface )] object pDataObj, [In, MarshalAs( UnmanagedType.U4 )] int grfKeyState, [In, MarshalAs( UnmanagedType.U8 )] long pt, [In, Out] ref int pdwEffect ); [PreserveSig] int OleDragOver( [In, MarshalAs( UnmanagedType.U4 )] int grfKeyState, [In, MarshalAs( UnmanagedType.U8 )] long pt, [In, Out] ref int pdwEffect ); [PreserveSig] int OleDragLeave(); [PreserveSig] int OleDrop( [In, MarshalAs( UnmanagedType.Interface )] object pDataObj, [In, MarshalAs( UnmanagedType.U4 )] int grfKeyState, [In, MarshalAs( UnmanagedType.U8 )] long pt, [In, Out] ref int pdwEffect ); #endregion } // ------------------------------------------------------------------ #endregion #region IOleInPlaceFrame interface. // ------------------------------------------------------------------ /// <summary> /// /// </summary> [ComImport, Guid( @"00000116-0000-0000-C000-000000000046" ), InterfaceType( ComInterfaceType.InterfaceIsIUnknown )] public interface IOleInPlaceFrame { #region Interface members. IntPtr GetWindow(); [PreserveSig] int ContextSensitiveHelp( int fEnterMode ); [PreserveSig] int GetBorder( [Out] NativeMethods.COMRECT lprectBorder ); [PreserveSig] int RequestBorderSpace( [In] NativeMethods.COMRECT pborderwidths ); [PreserveSig] int SetBorderSpace( [In] NativeMethods.COMRECT pborderwidths ); [PreserveSig] int SetActiveObject( [In, MarshalAs( UnmanagedType.Interface )] IOleInPlaceActiveObject pActiveObject, [In, MarshalAs( UnmanagedType.LPWStr )] string pszObjName ); [PreserveSig] int InsertMenus( [In] IntPtr hmenuShared, [In, Out] NativeMethods.tagOleMenuGroupWidths lpMenuWidths ); [PreserveSig] int SetMenu( [In] IntPtr hmenuShared, [In] IntPtr holemenu, [In] IntPtr hwndActiveObject ); [PreserveSig] int RemoveMenus( [In] IntPtr hmenuShared ); [PreserveSig] int SetStatusText( [In, MarshalAs( UnmanagedType.LPWStr )] string pszStatusText ); [PreserveSig] int EnableModeless( bool fEnable ); [PreserveSig] int TranslateAccelerator( [In] ref NativeMethods.MSG lpmsg, [In, MarshalAs( UnmanagedType.U2 )] short wID ); #endregion } // ------------------------------------------------------------------ #endregion #region DWebBrowserEvents2 interface. // ------------------------------------------------------------------ [ComImport, TypeLibType( (short)0x1010 ), InterfaceType( (short)2 ), Guid( @"34A715A0-6587-11D0-924A-0020AFC7AC4D" )] public interface DWebBrowserEvents2 { [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x66 )] void StatusTextChange( [In, MarshalAs( UnmanagedType.BStr )] string Text ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x6c )] void ProgressChange( [In] int Progress, [In] int ProgressMax ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x69 )] void CommandStateChange( [In] int command, [In] bool enable ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x6a )] void DownloadBegin(); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x68 )] void DownloadComplete(); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x71 )] void TitleChange( [In, MarshalAs( UnmanagedType.BStr )] string Text ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x70 )] void PropertyChange( [In, MarshalAs( UnmanagedType.BStr )] string szProperty ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 250 )] void BeforeNavigate2( [In, MarshalAs( UnmanagedType.IDispatch )] object pDisp, [In, MarshalAs( UnmanagedType.Struct )] ref object url, [In, MarshalAs( UnmanagedType.Struct )] ref object Flags, [In, MarshalAs( UnmanagedType.Struct )] ref object TargetFrameName, [In, MarshalAs( UnmanagedType.Struct )] ref object PostData, [In, MarshalAs( UnmanagedType.Struct )] ref object Headers, [In, Out] ref bool Cancel ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0xfb )] void NewWindow2( [In, Out, MarshalAs( UnmanagedType.IDispatch )] ref object ppDisp, [In, Out] ref bool Cancel ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0xfc )] void NavigateComplete2( [In, MarshalAs( UnmanagedType.IDispatch )] object pDisp, [In, MarshalAs( UnmanagedType.Struct )] ref object url ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x103 )] void DocumentComplete( [In, MarshalAs( UnmanagedType.IDispatch )] object pDisp, [In, MarshalAs( UnmanagedType.Struct )] ref object url ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0xfd )] void OnQuit(); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0xfe )] void OnVisible( [In] bool Visible ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0xff )] void OnToolBar( [In] bool ToolBar ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x100 )] void OnMenuBar( [In] bool MenuBar ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x101 )] void OnStatusBar( [In] bool StatusBar ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x102 )] void OnFullScreen( [In] bool FullScreen ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 260 )] void OnTheaterMode( [In] bool TheaterMode ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x106 )] void WindowSetResizable( [In] bool Resizable ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x108 )] void WindowSetLeft( [In] int Left ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x109 )] void WindowSetTop( [In] int Top ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x10a )] void WindowSetWidth( [In] int Width ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x10b )] void WindowSetHeight( [In] int Height ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x107 )] void WindowClosing( [In] bool IsChildWindow, [In, Out] ref bool Cancel ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x10c )] void ClientToHostWindow( [In, Out] ref int cx, [In, Out] ref int cy ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x10d )] void SetSecureLockIcon( [In] int SecureLockIcon ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 270 )] void FileDownload( [In, Out] ref bool Cancel ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x10f )] void NavigateError( [In, MarshalAs( UnmanagedType.IDispatch )] object pDisp, [In, MarshalAs( UnmanagedType.Struct )] ref object url, [In, MarshalAs( UnmanagedType.Struct )] ref object Frame, [In, MarshalAs( UnmanagedType.Struct )] ref object StatusCode, [In, Out] ref bool Cancel ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0xe1 )] void PrintTemplateInstantiation( [In, MarshalAs( UnmanagedType.IDispatch )] object pDisp ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0xe2 )] void PrintTemplateTeardown( [In, MarshalAs( UnmanagedType.IDispatch )] object pDisp ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0xe3 )] void UpdatePageStatus( [In, MarshalAs( UnmanagedType.IDispatch )] object pDisp, [In, MarshalAs( UnmanagedType.Struct )] ref object nPage, [In, MarshalAs( UnmanagedType.Struct )] ref object fDone ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x110 )] void PrivacyImpactedStateChange( [In] bool bImpacted ); [PreserveSig, MethodImpl( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime ), DispId( 0x111 )] void NewWindow3( [In, Out, MarshalAs( UnmanagedType.IDispatch )] ref object ppDisp, [In, Out] ref bool cancel, [In] uint dwFlags, [In, MarshalAs( UnmanagedType.BStr )] string bstrUrlContext, [In, MarshalAs( UnmanagedType.BStr )] string bstrUrl ); } // ------------------------------------------------------------------ #endregion #region IWebBrowser2 interface. // ------------------------------------------------------------------ [ComImport, SuppressUnmanagedCodeSecurity, TypeLibType( TypeLibTypeFlags.FOleAutomation | (TypeLibTypeFlags.FDual | TypeLibTypeFlags.FHidden) ), Guid( @"D30C1661-CDAF-11d0-8A3E-00C04FC9E26E" )] public interface IWebBrowser2 { [DispId( 100 )] void GoBack(); [DispId( 0x65 )] void GoForward(); [DispId( 0x66 )] void GoHome(); [DispId( 0x67 )] void GoSearch(); [DispId( 0x68 )] void Navigate( [In] string Url, [In] ref object flags, [In] ref object targetFrameName, [In] ref object postData, [In] ref object headers ); [DispId( -550 )] void Refresh(); [DispId( 0x69 )] void Refresh2( [In] ref object level ); [DispId( 0x6a )] void Stop(); [DispId( 200 )] object Application { [return: MarshalAs( UnmanagedType.IDispatch )] get; } [DispId( 0xc9 )] object Parent { [return: MarshalAs( UnmanagedType.IDispatch )] get; } [DispId( 0xca )] object Container { [return: MarshalAs( UnmanagedType.IDispatch )] get; } [DispId( 0xcb )] object Document { [return: MarshalAs( UnmanagedType.IDispatch )] get; } [DispId( 0xcc )] bool TopLevelContainer { get; } [DispId( 0xcd )] string Type { get; } [DispId( 0xce )] int Left { get; set; } [DispId( 0xcf )] int Top { get; set; } [DispId( 0xd0 )] int Width { get; set; } [DispId( 0xd1 )] int Height { get; set; } [DispId( 210 )] string LocationName { get; } [DispId( 0xd3 )] string LocationURL { get; } [DispId( 0xd4 )] bool Busy { get; } [DispId( 300 )] void Quit(); [DispId( 0x12d )] void ClientToWindow( out int pcx, out int pcy ); [DispId( 0x12e )] void PutProperty( [In] string property, [In] object vtValue ); [DispId( 0x12f )] object GetProperty( [In] string property ); [DispId( 0 )] string Name { get; } [DispId( -515 )] int HWND { get; } [DispId( 400 )] string FullName { get; } [DispId( 0x191 )] string Path { get; } [DispId( 0x192 )] bool Visible { get; set; } [DispId( 0x193 )] bool StatusBar { get; set; } [DispId( 0x194 )] string StatusText { get; set; } [DispId( 0x195 )] int ToolBar { get; set; } [DispId( 0x196 )] bool MenuBar { get; set; } [DispId( 0x197 )] bool FullScreen { get; set; } [DispId( 500 )] void Navigate2( [In] ref object URL, [In] ref object flags, [In] ref object targetFrameName, [In] ref object postData, [In] ref object headers ); [DispId( 0x1f5 )] NativeMethods.OLECMDF QueryStatusWB( [In] NativeMethods.OLECMDID cmdID ); [DispId( 0x1f6 )] void ExecWB( [In] NativeMethods.OLECMDID cmdID, [In] NativeMethods.OLECMDEXECOPT cmdexecopt, ref object pvaIn, IntPtr pvaOut ); [DispId( 0x1f7 )] void ShowBrowserBar( [In] ref object pvaClsid, [In] ref object pvarShow, [In] ref object pvarSize ); [DispId( -525 )] WebBrowserReadyState ReadyState { get; } [DispId( 550 )] bool Offline { get; set; } [DispId( 0x227 )] bool Silent { get; set; } [DispId( 0x228 )] bool RegisterAsBrowser { get; set; } [DispId( 0x229 )] bool RegisterAsDropTarget { get; set; } [DispId( 0x22a )] bool TheaterMode { get; set; } [DispId( 0x22b )] bool AddressBar { get; set; } [DispId( 0x22c )] bool Resizable { get; set; } } // ------------------------------------------------------------------ #endregion #region Public methods. // ------------------------------------------------------------------ /// <summary> /// /// </summary> /// <param name="hWndFrom"></param> /// <param name="hWndTo"></param> /// <param name="pt"></param> /// <param name="cPoints"></param> /// <returns></returns> [DllImport( @"user32.dll", CharSet = CharSet.Auto, ExactSpelling = true )] public static extern int MapWindowPoints( HandleRef hWndFrom, HandleRef hWndTo, [In, Out] NativeMethods.POINT pt, int cPoints ); // ------------------------------------------------------------------ #endregion } ///////////////////////////////////////////////////////////////////////// }
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using BitCoinSharp.IO; namespace BitCoinSharp { /// <summary> /// A transfer of coins from one address to another creates a transaction in which the outputs /// can be claimed by the recipient in the input of another transaction. You can imagine a /// transaction as being a module which is wired up to others, the inputs of one have to be wired /// to the outputs of another. The exceptions are coinbase transactions, which create new coins. /// </summary> [Serializable] public class TransactionInput : Message { public static readonly byte[] EmptyArray = new byte[0]; // Allows for altering transactions after they were broadcast. Tx replacement is currently disabled in the C++ // client so this is always the UINT_MAX. // TODO: Document this in more detail and build features that use it. private uint _sequence; // Data needed to connect to the output of the transaction we're gathering coins from. internal TransactionOutPoint Outpoint { get; private set; } // The "script bytes" might not actually be a script. In coinbase transactions where new coins are minted there // is no input transaction, so instead the scriptBytes contains some extra stuff (like a rollover nonce) that we // don't care about much. The bytes are turned into a Script object (cached below) on demand via a getter. internal byte[] ScriptBytes { get; set; } // The Script object obtained from parsing scriptBytes. Only filled in on demand and if the transaction is not // coinbase. [NonSerialized] private Script _scriptSig; // A pointer to the transaction that owns this input. internal Transaction ParentTransaction { get; private set; } /// <summary> /// Used only in creation of the genesis block. /// </summary> internal TransactionInput(NetworkParameters @params, Transaction parentTransaction, byte[] scriptBytes) : base(@params) { ScriptBytes = scriptBytes; Outpoint = new TransactionOutPoint(@params, -1, null); _sequence = uint.MaxValue; ParentTransaction = parentTransaction; } /// <summary> /// Creates an UNSIGNED input that links to the given output /// </summary> internal TransactionInput(NetworkParameters @params, Transaction parentTransaction, TransactionOutput output) : base(@params) { var outputIndex = output.Index; Outpoint = new TransactionOutPoint(@params, outputIndex, output.ParentTransaction); ScriptBytes = EmptyArray; _sequence = uint.MaxValue; ParentTransaction = parentTransaction; } /// <summary> /// Deserializes an input message. This is usually part of a transaction message. /// </summary> /// <exception cref="BitCoinSharp.ProtocolException" /> public TransactionInput(NetworkParameters @params, Transaction parentTransaction, byte[] payload, int offset) : base(@params, payload, offset) { ParentTransaction = parentTransaction; } /// <exception cref="BitCoinSharp.ProtocolException" /> protected override void Parse() { Outpoint = new TransactionOutPoint(Params, Bytes, Cursor); Cursor += Outpoint.MessageSize; var scriptLen = (int) ReadVarInt(); ScriptBytes = ReadBytes(scriptLen); _sequence = ReadUint32(); } /// <exception cref="System.IO.IOException" /> public override void BitcoinSerializeToStream(Stream stream) { Outpoint.BitcoinSerializeToStream(stream); stream.Write(new VarInt((ulong) ScriptBytes.Length).Encode()); stream.Write(ScriptBytes); Utils.Uint32ToByteStreamLe(_sequence, stream); } /// <summary> /// Coinbase transactions have special inputs with hashes of zero. If this is such an input, returns true. /// </summary> public bool IsCoinBase { get { return Outpoint.Hash.All(t => t == 0); } } /// <summary> /// Returns the input script. /// </summary> /// <exception cref="BitCoinSharp.ScriptException" /> public Script ScriptSig { get { // Transactions that generate new coins don't actually have a script. Instead this // parameter is overloaded to be something totally different. if (_scriptSig == null) { Debug.Assert(ScriptBytes != null); _scriptSig = new Script(Params, ScriptBytes, 0, ScriptBytes.Length); } return _scriptSig; } } /// <summary> /// Convenience method that returns the from address of this input by parsing the scriptSig. /// </summary> /// <exception cref="BitCoinSharp.ScriptException">If the scriptSig could not be understood (eg, if this is a coinbase transaction).</exception> public Address FromAddress { get { Debug.Assert(!IsCoinBase); return ScriptSig.FromAddress; } } /// <summary> /// Returns a human readable debug string. /// </summary> public override string ToString() { if (IsCoinBase) { return "TxIn: COINBASE"; } return "TxIn from " + Utils.BytesToHexString(ScriptSig.PubKey) + " script:" + ScriptSig; } internal enum ConnectionResult { NoSuchTx, AlreadySpent, Success } // TODO: Clean all this up once TransactionOutPoint disappears. /// <summary> /// Locates the referenced output from the given pool of transactions. /// </summary> /// <returns>The TransactionOutput or null if the transactions map doesn't contain the referenced tx.</returns> internal TransactionOutput GetConnectedOutput(IDictionary<Sha256Hash, Transaction> transactions) { var h = new Sha256Hash(Outpoint.Hash); Transaction tx; if (!transactions.TryGetValue(h, out tx)) return null; var @out = tx.Outputs[Outpoint.Index]; return @out; } /// <summary> /// Connects this input to the relevant output of the referenced transaction if it's in the given map. /// Connecting means updating the internal pointers and spent flags. /// </summary> /// <param name="transactions">Map of txhash-&gt;transaction.</param> /// <param name="disconnect">Whether to abort if there's a pre-existing connection or not.</param> /// <returns>True if connection took place, false if the referenced transaction was not in the list.</returns> internal ConnectionResult Connect(IDictionary<Sha256Hash, Transaction> transactions, bool disconnect) { var h = new Sha256Hash(Outpoint.Hash); Transaction tx; if (!transactions.TryGetValue(h, out tx)) return ConnectionResult.NoSuchTx; var @out = tx.Outputs[Outpoint.Index]; if ([email protected]) { if (disconnect) @out.MarkAsUnspent(); else return ConnectionResult.AlreadySpent; } Outpoint.FromTx = tx; @out.MarkAsSpent(this); return ConnectionResult.Success; } /// <summary> /// Release the connected output, making it spendable once again. /// </summary> /// <returns>True if the disconnection took place, false if it was not connected.</returns> internal bool Disconnect() { if (Outpoint.FromTx == null) return false; Outpoint.FromTx.Outputs[Outpoint.Index].MarkAsUnspent(); Outpoint.FromTx = null; return true; } } }
namespace DocMaker2 { partial class FrmMain { /// <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 Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmMain)); this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer(); this.TabControlMain = new System.Windows.Forms.TabControl(); this.TabGeneral = new System.Windows.Forms.TabPage(); this.TxtLog = new System.Windows.Forms.TextBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.BtnGenXml = new System.Windows.Forms.Button(); this.BtnOutputXmlFile = new System.Windows.Forms.Button(); this.label7 = new System.Windows.Forms.Label(); this.TxtOutputXmlFile = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label3 = new System.Windows.Forms.Label(); this.CmbHtmlOutputCodepage = new System.Windows.Forms.ComboBox(); this.BtnGenHtml = new System.Windows.Forms.Button(); this.BtnHtmlOutputPath = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.TxtHtmlOutputPath = new System.Windows.Forms.TextBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label5 = new System.Windows.Forms.Label(); this.TxtExtensions = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.CmbInputCodepage = new System.Windows.Forms.ComboBox(); this.BtnInputPath = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.TxtInputPath = new System.Windows.Forms.TextBox(); this.TabTerms = new System.Windows.Forms.TabPage(); this.label18 = new System.Windows.Forms.Label(); this.TxtTermConstructors = new System.Windows.Forms.TextBox(); this.label17 = new System.Windows.Forms.Label(); this.TxtTermReadOnly = new System.Windows.Forms.TextBox(); this.label16 = new System.Windows.Forms.Label(); this.TxtTermGlobalVariables = new System.Windows.Forms.TextBox(); this.label15 = new System.Windows.Forms.Label(); this.TxtTermGlobalFunctions = new System.Windows.Forms.TextBox(); this.label14 = new System.Windows.Forms.Label(); this.TxtTermExample = new System.Windows.Forms.TextBox(); this.label13 = new System.Windows.Forms.Label(); this.TxtTermRemarks = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.TxtTermReturn = new System.Windows.Forms.TextBox(); this.label11 = new System.Windows.Forms.Label(); this.TxtTermParameters = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.TxtTermEvents = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.TxtTermAttributes = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.TxtTermMethods = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.TxtTermLanguage = new System.Windows.Forms.TextBox(); this.TabAbout = new System.Windows.Forms.TabPage(); this.label21 = new System.Windows.Forms.Label(); this.LnkWebsite = new System.Windows.Forms.LinkLabel(); this.label20 = new System.Windows.Forms.Label(); this.label19 = new System.Windows.Forms.Label(); this.ToolbarStrip = new System.Windows.Forms.ToolStrip(); this.openToolStripButton = new System.Windows.Forms.ToolStripButton(); this.saveToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.Tips = new System.Windows.Forms.ToolTip(this.components); this.toolStripContainer1.ContentPanel.SuspendLayout(); this.toolStripContainer1.TopToolStripPanel.SuspendLayout(); this.toolStripContainer1.SuspendLayout(); this.TabControlMain.SuspendLayout(); this.TabGeneral.SuspendLayout(); this.groupBox3.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox1.SuspendLayout(); this.TabTerms.SuspendLayout(); this.TabAbout.SuspendLayout(); this.ToolbarStrip.SuspendLayout(); this.SuspendLayout(); // // toolStripContainer1 // // // toolStripContainer1.ContentPanel // this.toolStripContainer1.ContentPanel.Controls.Add(this.TabControlMain); this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(469, 452); this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.toolStripContainer1.Location = new System.Drawing.Point(0, 0); this.toolStripContainer1.Name = "toolStripContainer1"; this.toolStripContainer1.Size = new System.Drawing.Size(469, 477); this.toolStripContainer1.TabIndex = 0; this.toolStripContainer1.Text = "toolStripContainer1"; // // toolStripContainer1.TopToolStripPanel // this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.ToolbarStrip); // // TabControlMain // this.TabControlMain.Controls.Add(this.TabGeneral); this.TabControlMain.Controls.Add(this.TabTerms); this.TabControlMain.Controls.Add(this.TabAbout); this.TabControlMain.Dock = System.Windows.Forms.DockStyle.Fill; this.TabControlMain.Location = new System.Drawing.Point(0, 0); this.TabControlMain.Name = "TabControlMain"; this.TabControlMain.SelectedIndex = 0; this.TabControlMain.Size = new System.Drawing.Size(469, 452); this.TabControlMain.TabIndex = 0; // // TabGeneral // this.TabGeneral.Controls.Add(this.TxtLog); this.TabGeneral.Controls.Add(this.groupBox3); this.TabGeneral.Controls.Add(this.groupBox2); this.TabGeneral.Controls.Add(this.groupBox1); this.TabGeneral.Location = new System.Drawing.Point(4, 22); this.TabGeneral.Name = "TabGeneral"; this.TabGeneral.Padding = new System.Windows.Forms.Padding(3); this.TabGeneral.Size = new System.Drawing.Size(461, 426); this.TabGeneral.TabIndex = 0; this.TabGeneral.Text = "General"; this.TabGeneral.UseVisualStyleBackColor = true; // // TxtLog // this.TxtLog.Dock = System.Windows.Forms.DockStyle.Bottom; this.TxtLog.Location = new System.Drawing.Point(3, 328); this.TxtLog.Multiline = true; this.TxtLog.Name = "TxtLog"; this.TxtLog.ReadOnly = true; this.TxtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.TxtLog.Size = new System.Drawing.Size(455, 95); this.TxtLog.TabIndex = 14; this.TxtLog.WordWrap = false; // // groupBox3 // this.groupBox3.Controls.Add(this.BtnGenXml); this.groupBox3.Controls.Add(this.BtnOutputXmlFile); this.groupBox3.Controls.Add(this.label7); this.groupBox3.Controls.Add(this.TxtOutputXmlFile); this.groupBox3.Location = new System.Drawing.Point(0, 236); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(458, 81); this.groupBox3.TabIndex = 13; this.groupBox3.TabStop = false; this.groupBox3.Text = "Output to XML"; // // BtnGenXml // this.BtnGenXml.Location = new System.Drawing.Point(126, 45); this.BtnGenXml.Name = "BtnGenXml"; this.BtnGenXml.Size = new System.Drawing.Size(160, 23); this.BtnGenXml.TabIndex = 3; this.BtnGenXml.Text = "Generate XML"; this.BtnGenXml.Click += new System.EventHandler(this.OnGenerateXml); // // BtnOutputXmlFile // this.BtnOutputXmlFile.Location = new System.Drawing.Point(422, 19); this.BtnOutputXmlFile.Name = "BtnOutputXmlFile"; this.BtnOutputXmlFile.Size = new System.Drawing.Size(24, 20); this.BtnOutputXmlFile.TabIndex = 2; this.BtnOutputXmlFile.Text = "..."; this.BtnOutputXmlFile.Click += new System.EventHandler(this.OnBrowseXmlFile); // // label7 // this.label7.AutoSize = true; this.label7.BackColor = System.Drawing.Color.Transparent; this.label7.Location = new System.Drawing.Point(10, 22); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(85, 13); this.label7.TabIndex = 0; this.label7.Text = "Path to XML file:"; // // TxtOutputXmlFile // this.TxtOutputXmlFile.Location = new System.Drawing.Point(126, 19); this.TxtOutputXmlFile.Name = "TxtOutputXmlFile"; this.TxtOutputXmlFile.Size = new System.Drawing.Size(290, 20); this.TxtOutputXmlFile.TabIndex = 1; this.TxtOutputXmlFile.Text = "c:\\data\\wme_docs_core.xml"; this.TxtOutputXmlFile.TextChanged += new System.EventHandler(this.OnMakeDirty); // // groupBox2 // this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.CmbHtmlOutputCodepage); this.groupBox2.Controls.Add(this.BtnGenHtml); this.groupBox2.Controls.Add(this.BtnHtmlOutputPath); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.TxtHtmlOutputPath); this.groupBox2.Location = new System.Drawing.Point(0, 121); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(458, 109); this.groupBox2.TabIndex = 12; this.groupBox2.TabStop = false; this.groupBox2.Text = "Output to HTML docs"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(10, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(93, 13); this.label3.TabIndex = 3; this.label3.Text = "Output codepage:"; // // CmbHtmlOutputCodepage // this.CmbHtmlOutputCodepage.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.CmbHtmlOutputCodepage.FormattingEnabled = true; this.CmbHtmlOutputCodepage.Location = new System.Drawing.Point(126, 45); this.CmbHtmlOutputCodepage.MaxDropDownItems = 10; this.CmbHtmlOutputCodepage.Name = "CmbHtmlOutputCodepage"; this.CmbHtmlOutputCodepage.Size = new System.Drawing.Size(160, 21); this.CmbHtmlOutputCodepage.Sorted = true; this.CmbHtmlOutputCodepage.TabIndex = 4; this.CmbHtmlOutputCodepage.SelectedIndexChanged += new System.EventHandler(this.OnMakeDirty); // // BtnGenHtml // this.BtnGenHtml.Location = new System.Drawing.Point(126, 72); this.BtnGenHtml.Name = "BtnGenHtml"; this.BtnGenHtml.Size = new System.Drawing.Size(160, 23); this.BtnGenHtml.TabIndex = 5; this.BtnGenHtml.Text = "Generate HTML"; this.BtnGenHtml.Click += new System.EventHandler(this.OnGenerateHtml); // // BtnHtmlOutputPath // this.BtnHtmlOutputPath.Location = new System.Drawing.Point(422, 19); this.BtnHtmlOutputPath.Name = "BtnHtmlOutputPath"; this.BtnHtmlOutputPath.Size = new System.Drawing.Size(24, 20); this.BtnHtmlOutputPath.TabIndex = 2; this.BtnHtmlOutputPath.Text = "..."; this.BtnHtmlOutputPath.Click += new System.EventHandler(this.OnBrowseHtmlOutput); // // label4 // this.label4.AutoSize = true; this.label4.BackColor = System.Drawing.Color.Transparent; this.label4.Location = new System.Drawing.Point(10, 23); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(98, 13); this.label4.TabIndex = 0; this.label4.Text = "Path to HTML files:"; // // TxtHtmlOutputPath // this.TxtHtmlOutputPath.Location = new System.Drawing.Point(126, 19); this.TxtHtmlOutputPath.Name = "TxtHtmlOutputPath"; this.TxtHtmlOutputPath.Size = new System.Drawing.Size(290, 20); this.TxtHtmlOutputPath.TabIndex = 1; this.TxtHtmlOutputPath.Text = "c:\\data\\html"; this.TxtHtmlOutputPath.TextChanged += new System.EventHandler(this.OnMakeDirty); // // groupBox1 // this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.TxtExtensions); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.CmbInputCodepage); this.groupBox1.Controls.Add(this.BtnInputPath); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.TxtInputPath); this.groupBox1.Location = new System.Drawing.Point(0, 6); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(458, 109); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Input"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(10, 75); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(61, 13); this.label5.TabIndex = 5; this.label5.Text = "Extensions:"; // // TxtExtensions // this.TxtExtensions.Location = new System.Drawing.Point(126, 72); this.TxtExtensions.Name = "TxtExtensions"; this.TxtExtensions.Size = new System.Drawing.Size(160, 20); this.TxtExtensions.TabIndex = 6; this.TxtExtensions.Text = "txt"; this.Tips.SetToolTip(this.TxtExtensions, "Semicolon separated list of extensions, e.g. \"txt;doc\""); this.TxtExtensions.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(10, 48); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(85, 13); this.label2.TabIndex = 3; this.label2.Text = "Input codepage:"; // // CmbInputCodepage // this.CmbInputCodepage.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.CmbInputCodepage.FormattingEnabled = true; this.CmbInputCodepage.Location = new System.Drawing.Point(126, 45); this.CmbInputCodepage.MaxDropDownItems = 10; this.CmbInputCodepage.Name = "CmbInputCodepage"; this.CmbInputCodepage.Size = new System.Drawing.Size(160, 21); this.CmbInputCodepage.Sorted = true; this.CmbInputCodepage.TabIndex = 4; this.CmbInputCodepage.SelectedIndexChanged += new System.EventHandler(this.OnMakeDirty); // // BtnInputPath // this.BtnInputPath.Location = new System.Drawing.Point(422, 19); this.BtnInputPath.Name = "BtnInputPath"; this.BtnInputPath.Size = new System.Drawing.Size(24, 20); this.BtnInputPath.TabIndex = 2; this.BtnInputPath.Text = "..."; this.BtnInputPath.Click += new System.EventHandler(this.OnBrowseInputPath); // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Location = new System.Drawing.Point(10, 22); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(110, 13); this.label1.TabIndex = 0; this.label1.Text = "Path to definition files:"; // // TxtInputPath // this.TxtInputPath.Location = new System.Drawing.Point(126, 19); this.TxtInputPath.Name = "TxtInputPath"; this.TxtInputPath.Size = new System.Drawing.Size(290, 20); this.TxtInputPath.TabIndex = 1; this.TxtInputPath.Text = "c:\\data"; this.TxtInputPath.TextChanged += new System.EventHandler(this.OnMakeDirty); // // TabTerms // this.TabTerms.Controls.Add(this.label18); this.TabTerms.Controls.Add(this.TxtTermConstructors); this.TabTerms.Controls.Add(this.label17); this.TabTerms.Controls.Add(this.TxtTermReadOnly); this.TabTerms.Controls.Add(this.label16); this.TabTerms.Controls.Add(this.TxtTermGlobalVariables); this.TabTerms.Controls.Add(this.label15); this.TabTerms.Controls.Add(this.TxtTermGlobalFunctions); this.TabTerms.Controls.Add(this.label14); this.TabTerms.Controls.Add(this.TxtTermExample); this.TabTerms.Controls.Add(this.label13); this.TabTerms.Controls.Add(this.TxtTermRemarks); this.TabTerms.Controls.Add(this.label12); this.TabTerms.Controls.Add(this.TxtTermReturn); this.TabTerms.Controls.Add(this.label11); this.TabTerms.Controls.Add(this.TxtTermParameters); this.TabTerms.Controls.Add(this.label10); this.TabTerms.Controls.Add(this.TxtTermEvents); this.TabTerms.Controls.Add(this.label9); this.TabTerms.Controls.Add(this.TxtTermAttributes); this.TabTerms.Controls.Add(this.label8); this.TabTerms.Controls.Add(this.TxtTermMethods); this.TabTerms.Controls.Add(this.label6); this.TabTerms.Controls.Add(this.TxtTermLanguage); this.TabTerms.Location = new System.Drawing.Point(4, 22); this.TabTerms.Name = "TabTerms"; this.TabTerms.Padding = new System.Windows.Forms.Padding(3); this.TabTerms.Size = new System.Drawing.Size(461, 426); this.TabTerms.TabIndex = 1; this.TabTerms.Text = "Terms"; this.TabTerms.UseVisualStyleBackColor = true; // // label18 // this.label18.AutoSize = true; this.label18.Location = new System.Drawing.Point(8, 295); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(69, 13); this.label18.TabIndex = 23; this.label18.Text = "Constructors:"; // // TxtTermConstructors // this.TxtTermConstructors.Location = new System.Drawing.Point(102, 292); this.TxtTermConstructors.Name = "TxtTermConstructors"; this.TxtTermConstructors.Size = new System.Drawing.Size(351, 20); this.TxtTermConstructors.TabIndex = 22; this.TxtTermConstructors.Text = "Constructors"; this.TxtTermConstructors.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label17 // this.label17.AutoSize = true; this.label17.Location = new System.Drawing.Point(8, 269); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(58, 13); this.label17.TabIndex = 21; this.label17.Text = "Read only:"; // // TxtTermReadOnly // this.TxtTermReadOnly.Location = new System.Drawing.Point(102, 266); this.TxtTermReadOnly.Name = "TxtTermReadOnly"; this.TxtTermReadOnly.Size = new System.Drawing.Size(351, 20); this.TxtTermReadOnly.TabIndex = 20; this.TxtTermReadOnly.Text = "read only"; this.TxtTermReadOnly.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label16 // this.label16.AutoSize = true; this.label16.Location = new System.Drawing.Point(8, 243); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(85, 13); this.label16.TabIndex = 19; this.label16.Text = "Global variables:"; // // TxtTermGlobalVariables // this.TxtTermGlobalVariables.Location = new System.Drawing.Point(102, 240); this.TxtTermGlobalVariables.Name = "TxtTermGlobalVariables"; this.TxtTermGlobalVariables.Size = new System.Drawing.Size(351, 20); this.TxtTermGlobalVariables.TabIndex = 18; this.TxtTermGlobalVariables.Text = "Global variables"; this.TxtTermGlobalVariables.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label15 // this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(8, 217); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(86, 13); this.label15.TabIndex = 17; this.label15.Text = "Global functions:"; // // TxtTermGlobalFunctions // this.TxtTermGlobalFunctions.Location = new System.Drawing.Point(102, 214); this.TxtTermGlobalFunctions.Name = "TxtTermGlobalFunctions"; this.TxtTermGlobalFunctions.Size = new System.Drawing.Size(351, 20); this.TxtTermGlobalFunctions.TabIndex = 16; this.TxtTermGlobalFunctions.Text = "Global functions"; this.TxtTermGlobalFunctions.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(8, 191); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(50, 13); this.label14.TabIndex = 15; this.label14.Text = "Example:"; // // TxtTermExample // this.TxtTermExample.Location = new System.Drawing.Point(102, 188); this.TxtTermExample.Name = "TxtTermExample"; this.TxtTermExample.Size = new System.Drawing.Size(351, 20); this.TxtTermExample.TabIndex = 14; this.TxtTermExample.Text = "Example"; this.TxtTermExample.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(8, 165); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(52, 13); this.label13.TabIndex = 13; this.label13.Text = "Remarks:"; // // TxtTermRemarks // this.TxtTermRemarks.Location = new System.Drawing.Point(102, 162); this.TxtTermRemarks.Name = "TxtTermRemarks"; this.TxtTermRemarks.Size = new System.Drawing.Size(351, 20); this.TxtTermRemarks.TabIndex = 12; this.TxtTermRemarks.Text = "Remarks"; this.TxtTermRemarks.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(8, 139); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(71, 13); this.label12.TabIndex = 11; this.label12.Text = "Return value:"; // // TxtTermReturn // this.TxtTermReturn.Location = new System.Drawing.Point(102, 136); this.TxtTermReturn.Name = "TxtTermReturn"; this.TxtTermReturn.Size = new System.Drawing.Size(351, 20); this.TxtTermReturn.TabIndex = 10; this.TxtTermReturn.Text = "Return value"; this.TxtTermReturn.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(8, 113); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(63, 13); this.label11.TabIndex = 9; this.label11.Text = "Parameters:"; // // TxtTermParameters // this.TxtTermParameters.Location = new System.Drawing.Point(102, 110); this.TxtTermParameters.Name = "TxtTermParameters"; this.TxtTermParameters.Size = new System.Drawing.Size(351, 20); this.TxtTermParameters.TabIndex = 8; this.TxtTermParameters.Text = "Parameters"; this.TxtTermParameters.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(8, 87); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(90, 13); this.label10.TabIndex = 7; this.label10.Text = "Low level events:"; // // TxtTermEvents // this.TxtTermEvents.Location = new System.Drawing.Point(102, 84); this.TxtTermEvents.Name = "TxtTermEvents"; this.TxtTermEvents.Size = new System.Drawing.Size(351, 20); this.TxtTermEvents.TabIndex = 6; this.TxtTermEvents.Text = "Low level events"; this.TxtTermEvents.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(8, 61); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(54, 13); this.label9.TabIndex = 5; this.label9.Text = "Attributes:"; // // TxtTermAttributes // this.TxtTermAttributes.Location = new System.Drawing.Point(102, 58); this.TxtTermAttributes.Name = "TxtTermAttributes"; this.TxtTermAttributes.Size = new System.Drawing.Size(351, 20); this.TxtTermAttributes.TabIndex = 4; this.TxtTermAttributes.Text = "Attributes"; this.TxtTermAttributes.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(8, 35); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(51, 13); this.label8.TabIndex = 3; this.label8.Text = "Methods:"; // // TxtTermMethods // this.TxtTermMethods.Location = new System.Drawing.Point(102, 32); this.TxtTermMethods.Name = "TxtTermMethods"; this.TxtTermMethods.Size = new System.Drawing.Size(351, 20); this.TxtTermMethods.TabIndex = 2; this.TxtTermMethods.Text = "Methods"; this.TxtTermMethods.TextChanged += new System.EventHandler(this.OnMakeDirty); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(8, 9); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(87, 13); this.label6.TabIndex = 1; this.label6.Text = "HTML language:"; // // TxtTermLanguage // this.TxtTermLanguage.Location = new System.Drawing.Point(102, 6); this.TxtTermLanguage.Name = "TxtTermLanguage"; this.TxtTermLanguage.Size = new System.Drawing.Size(351, 20); this.TxtTermLanguage.TabIndex = 0; this.TxtTermLanguage.Text = "en-us"; this.TxtTermLanguage.TextChanged += new System.EventHandler(this.OnMakeDirty); // // TabAbout // this.TabAbout.Controls.Add(this.label21); this.TabAbout.Controls.Add(this.LnkWebsite); this.TabAbout.Controls.Add(this.label20); this.TabAbout.Controls.Add(this.label19); this.TabAbout.Location = new System.Drawing.Point(4, 22); this.TabAbout.Name = "TabAbout"; this.TabAbout.Padding = new System.Windows.Forms.Padding(3); this.TabAbout.Size = new System.Drawing.Size(461, 426); this.TabAbout.TabIndex = 2; this.TabAbout.Text = "About"; this.TabAbout.UseVisualStyleBackColor = true; // // label21 // this.label21.Dock = System.Windows.Forms.DockStyle.Bottom; this.label21.Location = new System.Drawing.Point(3, 80); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(455, 343); this.label21.TabIndex = 3; this.label21.Text = resources.GetString("label21.Text"); // // LnkWebsite // this.LnkWebsite.AutoSize = true; this.LnkWebsite.Location = new System.Drawing.Point(6, 49); this.LnkWebsite.Name = "LnkWebsite"; this.LnkWebsite.Size = new System.Drawing.Size(139, 13); this.LnkWebsite.TabIndex = 2; this.LnkWebsite.TabStop = true; this.LnkWebsite.Text = "http://www.wintermute-engine.org/"; this.LnkWebsite.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.OnLinkClicked); // // label20 // this.label20.AutoSize = true; this.label20.Location = new System.Drawing.Point(6, 32); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(204, 13); this.label20.TabIndex = 1; this.label20.Text = "Copyright (c) Dead:Code Software 2005"; // // label19 // this.label19.AutoSize = true; this.label19.Location = new System.Drawing.Point(6, 15); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(105, 13); this.label19.TabIndex = 0; this.label19.Text = "WME DocMaker 2.0"; // // ToolbarStrip // this.ToolbarStrip.Dock = System.Windows.Forms.DockStyle.None; this.ToolbarStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.ToolbarStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openToolStripButton, this.saveToolStripButton, this.toolStripButton1}); this.ToolbarStrip.Location = new System.Drawing.Point(0, 0); this.ToolbarStrip.Name = "ToolbarStrip"; this.ToolbarStrip.Size = new System.Drawing.Size(469, 25); this.ToolbarStrip.Stretch = true; this.ToolbarStrip.TabIndex = 0; this.ToolbarStrip.Text = "toolStrip1"; // // openToolStripButton // this.openToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.openToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripButton.Image"))); this.openToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.openToolStripButton.Name = "openToolStripButton"; this.openToolStripButton.Size = new System.Drawing.Size(23, 22); this.openToolStripButton.Text = "&Open"; this.openToolStripButton.Click += new System.EventHandler(this.OnLoadSettings); // // saveToolStripButton // this.saveToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.saveToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripButton.Image"))); this.saveToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.saveToolStripButton.Name = "saveToolStripButton"; this.saveToolStripButton.Size = new System.Drawing.Size(23, 22); this.saveToolStripButton.Text = "&Save"; this.saveToolStripButton.Click += new System.EventHandler(this.OnSaveSettings); // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(61, 22); this.toolStripButton1.Text = "Save as..."; this.toolStripButton1.Click += new System.EventHandler(this.OnSaveSettingsAs); // // FrmMain // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(469, 477); this.Controls.Add(this.toolStripContainer1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.Name = "FrmMain"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "WME DocMaker"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.OnFormClosed); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.OnFormClosing); this.Load += new System.EventHandler(this.OnFormLoad); this.toolStripContainer1.ContentPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.PerformLayout(); this.toolStripContainer1.ResumeLayout(false); this.toolStripContainer1.PerformLayout(); this.TabControlMain.ResumeLayout(false); this.TabGeneral.ResumeLayout(false); this.TabGeneral.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.TabTerms.ResumeLayout(false); this.TabTerms.PerformLayout(); this.TabAbout.ResumeLayout(false); this.TabAbout.PerformLayout(); this.ToolbarStrip.ResumeLayout(false); this.ToolbarStrip.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ToolStripContainer toolStripContainer1; private System.Windows.Forms.ToolStrip ToolbarStrip; private System.Windows.Forms.ToolStripButton openToolStripButton; private System.Windows.Forms.ToolStripButton saveToolStripButton; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.TabControl TabControlMain; private System.Windows.Forms.TabPage TabGeneral; private System.Windows.Forms.TabPage TabTerms; private System.Windows.Forms.Button BtnGenHtml; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox CmbHtmlOutputCodepage; private System.Windows.Forms.Button BtnHtmlOutputPath; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox TxtHtmlOutputPath; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox CmbInputCodepage; private System.Windows.Forms.Button BtnInputPath; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox TxtInputPath; private System.Windows.Forms.TextBox TxtExtensions; private System.Windows.Forms.Label label5; private System.Windows.Forms.ToolTip Tips; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Button BtnGenXml; private System.Windows.Forms.Button BtnOutputXmlFile; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox TxtOutputXmlFile; private System.Windows.Forms.TextBox TxtLog; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox TxtTermLanguage; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox TxtTermMethods; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox TxtTermAttributes; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox TxtTermEvents; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox TxtTermParameters; private System.Windows.Forms.Label label12; private System.Windows.Forms.TextBox TxtTermReturn; private System.Windows.Forms.Label label13; private System.Windows.Forms.TextBox TxtTermRemarks; private System.Windows.Forms.Label label14; private System.Windows.Forms.TextBox TxtTermExample; private System.Windows.Forms.Label label15; private System.Windows.Forms.TextBox TxtTermGlobalFunctions; private System.Windows.Forms.Label label16; private System.Windows.Forms.TextBox TxtTermGlobalVariables; private System.Windows.Forms.Label label17; private System.Windows.Forms.TextBox TxtTermReadOnly; private System.Windows.Forms.Label label18; private System.Windows.Forms.TextBox TxtTermConstructors; private System.Windows.Forms.TabPage TabAbout; private System.Windows.Forms.Label label20; private System.Windows.Forms.Label label19; private System.Windows.Forms.LinkLabel LnkWebsite; private System.Windows.Forms.Label label21; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data; using System.IO; using System.Runtime.CompilerServices; using Xunit; namespace System.Data.OleDb.Tests { [Collection("System.Data.OleDb")] // not let tests run in parallel public class OleDbCommandTests : OleDbTestBase { [ConditionalFact(Helpers.IsDriverAvailable)] public void UpdatedRowSource_SetInvalidValue_Throws() { const int InvalidValue = 50; using (var cmd = (OleDbCommand)OleDbFactory.Instance.CreateCommand()) { Assert.Equal(UpdateRowSource.Both, cmd.UpdatedRowSource); cmd.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord; Assert.Equal(UpdateRowSource.FirstReturnedRecord, cmd.UpdatedRowSource); if (PlatformDetection.IsFullFramework) { AssertExtensions.Throws<ArgumentOutOfRangeException>( () => cmd.UpdatedRowSource = (UpdateRowSource)InvalidValue, $"The {nameof(UpdateRowSource)} enumeration value, {InvalidValue}, is invalid.\r\nParameter name: {nameof(UpdateRowSource)}" ); } else { AssertExtensions.Throws<ArgumentOutOfRangeException>( () => cmd.UpdatedRowSource = (UpdateRowSource)InvalidValue, $"The {nameof(UpdateRowSource)} enumeration value, {InvalidValue}, is invalid. (Parameter \'{nameof(UpdateRowSource)}\')" ); } } } [ConditionalFact(Helpers.IsDriverAvailable)] public void CommandTimeout_SetInvalidValue_Throws() { const int InvalidValue = -1; using (var cmd = new OleDbCommand(default, connection, transaction)) { if (PlatformDetection.IsFullFramework) { AssertExtensions.Throws<ArgumentException>( () => cmd.CommandTimeout = InvalidValue, $"Invalid CommandTimeout value {InvalidValue}; the value must be >= 0.\r\nParameter name: {nameof(cmd.CommandTimeout)}" ); } else { AssertExtensions.Throws<ArgumentException>( () => cmd.CommandTimeout = InvalidValue, $"Invalid CommandTimeout value {InvalidValue}; the value must be >= 0. (Parameter \'{nameof(cmd.CommandTimeout)}\')" ); } } } [ConditionalFact(Helpers.IsDriverAvailable)] public void ResetCommandTimeout_ResetsToDefault() { using (var cmd = new OleDbCommand(default, connection, transaction)) { const int DefaultValue = 30; Assert.Equal(DefaultValue, cmd.CommandTimeout); cmd.CommandTimeout = DefaultValue + 50; Assert.Equal(DefaultValue + 50, cmd.CommandTimeout); cmd.ResetCommandTimeout(); Assert.Equal(DefaultValue, cmd.CommandTimeout); } } [ConditionalFact(Helpers.IsDriverAvailable)] public void CommandType_SetInvalidValue_Throws() { const int InvalidValue = 0; using (var cmd = (OleDbCommand)OleDbFactory.Instance.CreateCommand()) { if (PlatformDetection.IsFullFramework) { AssertExtensions.Throws<ArgumentOutOfRangeException>( () => cmd.CommandType = (CommandType)InvalidValue, $"The CommandType enumeration value, {InvalidValue}, is invalid.\r\nParameter name: {nameof(cmd.CommandType)}" ); } else { AssertExtensions.Throws<ArgumentOutOfRangeException>( () => cmd.CommandType = (CommandType)InvalidValue, $"The CommandType enumeration value, {InvalidValue}, is invalid. (Parameter \'{nameof(cmd.CommandType)}\')" ); } } } [OuterLoop] [ConditionalFact(Helpers.IsDriverAvailable)] public void Prepare_ClosedConnection_Throws() { RunTest((command, tableName) => { command.CommandText = @"SELECT * FROM " + tableName; connection.Close(); AssertExtensions.Throws<InvalidOperationException>( () => command.Prepare(), $"{nameof(command.Prepare)} requires an open and available Connection. The connection's current state is closed." ); connection.Open(); // reopen when done }); } [OuterLoop] [ConditionalFact(Helpers.IsDriverAvailable)] public void Prepare_MultipleCases_ThrowsForInvalidQuery() { RunTest((command, tableName) => { Assert.Equal(ConnectionState.Open, connection.State); command.CommandText = "INVALID_STATEMENT"; AssertExtensions.Throws<OleDbException>( () => command.Prepare(), "Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'." ); command.CommandText = @"UPDATE " + tableName + " SET NumPlants ? WHERE Firstname = ?"; AssertExtensions.Throws<OleDbException>( () => command.Prepare(), $"Syntax error in UPDATE statement." ); }); } [OuterLoop] [ConditionalFact(Helpers.IsDriverAvailable)] public void Prepare_InsertMultipleItems_UseTableDirectToVerify() { RunTest((command, tableName) => { command.CommandText = @"INSERT INTO " + tableName + " (Firstname, NumPlants) VALUES (?, ?)"; command.Prepare(); // Good to use when command used multiple times command.Parameters.Add(command.CreateParameter()); command.Parameters.Add(command.CreateParameter()); object[] newItems = new object[] { new { Firstname = "John", NumPlants = 7 }, new { Firstname = "Mark", NumPlants = 12 }, new { Firstname = "Nick", NumPlants = 6 } }; foreach (dynamic item in newItems) { command.Parameters[0].Value = item.Firstname; command.Parameters[1].Value = item.NumPlants; command.ExecuteNonQuery(); } var currentCommandType = command.CommandType; command.CommandType = CommandType.TableDirect; command.CommandText = tableName; using (OleDbDataReader reader = command.ExecuteReader()) { Assert.True(reader.Read(), "skip existing row"); Assert.True(reader.Read(), "skip existing row"); foreach (dynamic item in newItems) { Assert.True(reader.Read(), "validate new row"); Assert.Equal(item.Firstname, reader["Firstname"]); Assert.Equal(item.NumPlants, reader["NumPlants"]); } object x; AssertExtensions.Throws<IndexOutOfRangeException>(() => x = reader["MissingColumn"], "MissingColumn"); } command.CommandType = currentCommandType; }); } [OuterLoop] [ConditionalFact(Helpers.IsDriverAvailable)] public void Parameters_AddNullParameter_Throws() { RunTest((command, tableName) => { if (PlatformDetection.IsFullFramework) { AssertExtensions.Throws<ArgumentNullException>( () => command.Parameters.Add(null), $"The {nameof(OleDbParameterCollection)} only accepts non-null {nameof(OleDbParameter)} type objects.\r\nParameter name: value" ); } else { AssertExtensions.Throws<ArgumentNullException>( () => command.Parameters.Add(null), $"The {nameof(OleDbParameterCollection)} only accepts non-null {nameof(OleDbParameter)} type objects. (Parameter \'value\')" ); } command.CommandText = "SELECT * FROM " + tableName + " WHERE NumPlants = ?"; command.Parameters.Add(new OleDbParameter("@p1", 7)); using (OleDbDataReader reader = command.ExecuteReader()) { Assert.True(reader.Read()); Assert.Equal("John", reader["Firstname"]); Assert.Equal(7, reader["NumPlants"]); Assert.False(reader.Read(), "Expected to find only one item"); } }); } [OuterLoop] [ConditionalFact(Helpers.IsDriverAvailable)] public void ExecuteNonQuery_NullConnection_Throws() { RunTest((command, tableName) => { command.CommandText = @"SELECT * FROM " + tableName; var currentConnection = command.Connection; command.Connection = null; AssertExtensions.Throws<InvalidOperationException>( () => command.ExecuteNonQuery(), $"{nameof(command.ExecuteNonQuery)}: {nameof(command.Connection)} property has not been initialized." ); command.Connection = currentConnection; }); } [OuterLoop] [ConditionalFact(Helpers.IsDriverAvailable)] public void CommandType_InvalidType_Throws() { RunTest((command, tableName) => { using (var innerCommand = new OleDbCommand(cmdText: @"SELECT * FROM " + tableName)) { Assert.Throws<ArgumentOutOfRangeException>(() => innerCommand.CommandType = (CommandType)0); } }); } [OuterLoop] [ConditionalFact(Helpers.IsDriverAvailable)] public void ExecuteScalar_Select_ComputesSumAndCount() { RunTest((command, tableName) => { command.CommandText = @"SELECT Count(*) FROM " + tableName; Assert.Equal(2, Convert.ToInt32(command.ExecuteScalar())); command.CommandText = @"SELECT Sum(NumPlants) FROM " + tableName; Assert.Equal(13, Convert.ToInt32(command.ExecuteScalar())); }); } private void RunTest(Action<OleDbCommand, string> testAction, [CallerMemberName] string memberName = null) { string tableName = Helpers.GetTableName(memberName); Assert.False(File.Exists(Path.Combine(TestDirectory, tableName))); command.CommandText = @"CREATE TABLE " + tableName + @" ( Firstname NVARCHAR(5), NumPlants INT)"; command.ExecuteNonQuery(); Assert.True(File.Exists(Path.Combine(TestDirectory, tableName))); command.CommandText = @"INSERT INTO " + tableName + @" ( Firstname, NumPlants) VALUES ( 'John', 7 );"; command.ExecuteNonQuery(); command.CommandText = @"INSERT INTO " + tableName + @" ( Firstname, NumPlants) VALUES ( 'Sam', 6 );"; command.ExecuteNonQuery(); testAction(command, tableName); command.CommandText = @"DROP TABLE " + tableName; command.ExecuteNonQuery(); } } }
using System; using System.Linq; using <%=assemblyName%>.Data.Model; using <%=assemblyName%>.Contract; using <%=assemblyName%>.Contract.Security; namespace <%=assemblyName%>.Data { public static partial class Extensions { private const string AdminEmail = "webmaster@<%=assemblyName.toLowerCase()%>.org"; public static void EnsureSeedData(this DbContextBase db, ICryptoService crypto) { EnsureLocalProvider(db); EnsureExternalProviders(db); User admin = EnsureAdmin(db, crypto); EnsureAuthorizationClaims(db, admin); EnsureSystemRoles(db, admin); } private static void EnsureAuthorizationClaims(DbContextBase db, User admin) { string[] claims = new string[] { SecurityClaimTypes.Example }; foreach (string claim in claims) { var securityClaim = db.SecurityClaim.FirstOrDefault(o => o.SecurityClaimId == claim); if (securityClaim == null) { securityClaim = new SecurityClaim() { CreatedBy = admin.UserId, CreatedOn = DateTime.UtcNow, Description = claim, Enabled = true, Origin = "System", ValidationPattern = SecurityClaimTypes.AllowedValuesPattern, SecurityClaimId = claim }; db.SecurityClaim.Add(securityClaim); db.SaveChanges(); } } } private static Provider EnsureExternalProviders(DbContextBase db) { Provider provider = db.Provider.FirstOrDefault(o => o.ProviderId == ProviderTypes.Google); if (provider == null) { provider = new Provider() { ProviderId = ProviderTypes.Google, Name = "Google", Description = "Logon using your google account", Enabled = true }; db.Provider.Add(provider); db.SaveChanges(); } provider = db.Provider.FirstOrDefault(o => o.ProviderId == ProviderTypes.Microsoft); if (provider == null) { provider = new Provider() { ProviderId = ProviderTypes.Microsoft, Name = "Microsoft", Description = "Logon using your microsoft account", Enabled = true }; db.Provider.Add(provider); db.SaveChanges(); } return provider; } private static Provider EnsureLocalProvider(DbContextBase db) { Provider provider = db.Provider.FirstOrDefault(o => o.ProviderId == ProviderTypes.Local); if (provider == null) { provider = new Provider() { ProviderId = ProviderTypes.Local, Name = "Site", Description = "Authenticate with a username/password provider by this site", Enabled = true }; db.Provider.Add(provider); db.SaveChanges(); } return provider; } private static void EnsureSystemRoles(DbContextBase db, User admin) { foreach (var systemRole in RoleTypes.System) { Role role = db.Role.FirstOrDefault(o => o.RoleId == systemRole.Key); if (role == null) { role = new Role() { CreatedBy = admin.UserId, Enabled = true, Name = systemRole.Value, RoleId = systemRole.Key }; if (systemRole.Key == RoleTypes.User) { var claim = db.SecurityClaim.SingleOrDefault(o => o.SecurityClaimId == SecurityClaimTypes.Example); if (claim != null) role.SecurityClaims.Add(new RoleSecurityClaim() { Role = role, SecurityClaimId = SecurityClaimTypes.Example, Value = SecurityClaimValueTypes.Read.ToString() }); } db.Role.Add(role); db.SaveChanges(); } } } private static User EnsureAdmin(DbContextBase db, ICryptoService crypto) { User adminUser = db.User.SingleOrDefault(o => o.Username == AdminEmail); if (adminUser == null) { adminUser = new User() { CultureName = "en", DisplayName = "Webmaster", Enabled = true, TimeZoneId = Globalization.DefaultTimeZoneId, Username = AdminEmail }; db.User.Add(adminUser); db.SaveChanges(); } Role adminRole = db.Role.FirstOrDefault(o => o.RoleId == RoleTypes.Admin); if (adminRole == null) { adminRole = new Role() { CreatedByUser = adminUser, Enabled = true, Name = "Administrator", RoleId = RoleTypes.Admin }; db.Role.Add(adminRole); db.SaveChanges(); } if (!db.UserRole.Any()) { var userRole = new UserRole() { Role = adminRole, User = adminUser }; string salt = crypto.CreateSalt(); string hash = crypto.CreateKey(salt, "P@ssw0rd"); var userProvider = new UserProviderLocal { ProviderId = ProviderTypes.Local, PasswordSalt = salt, PasswordHash = hash, User = adminUser, }; db.UserRole.Add(userRole); db.UserProvider.Add(userProvider); db.SaveChanges(); } return adminUser; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using Xunit; namespace System.Linq.Expressions.Tests { public class ParameterBlockTests : SharedBlockTests { private static IEnumerable<ParameterExpression> SingleParameter { get { return Enumerable.Repeat(Expression.Variable(typeof(int)), 1); } } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void SingleElementBlock(object value, bool useInterpreter) { Type type = value.GetType(); ConstantExpression constant = Expression.Constant(value, type); BlockExpression block = Expression.Block( SingleParameter, constant ); Assert.Equal(type, block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void DoubleElementBlock(object value, bool useInterpreter) { Type type = value.GetType(); ConstantExpression constant = Expression.Constant(value, type); BlockExpression block = Expression.Block( SingleParameter, Expression.Empty(), constant ); Assert.Equal(type, block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Fact] public void NullExpicitType() { Assert.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Expression.Constant(0))); Assert.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Enumerable.Repeat(Expression.Constant(0), 1))); } [Fact] public void NullExpressionList() { Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(Expression[]))); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(IEnumerable<Expression>))); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(Expression[]))); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(IEnumerable<Expression>))); } [Theory] [MemberData(nameof(BlockSizes))] public void NullExpressionInExpressionList(int size) { List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList(); for (int i = 0; i < expressionList.Count; ++i) { Expression[] expressions = expressionList.ToArray(); expressions[i] = null; Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, expressions)); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, expressions.Skip(0))); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, expressions)); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0))); } } [Theory] [MemberData(nameof(BlockSizes))] public void UnreadableExpressionInExpressionList(int size) { List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList(); for (int i = 0; i != expressionList.Count; ++i) { Expression[] expressions = expressionList.ToArray(); expressions[i] = UnreadableExpression; Assert.Throws<ArgumentException>("expressions", () => Expression.Block(SingleParameter, expressions)); Assert.Throws<ArgumentException>("expressions", () => Expression.Block(SingleParameter, expressions.Skip(0))); Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), SingleParameter, expressions)); Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0))); } } [Theory] [PerCompilationType(nameof(ObjectAssignableConstantValuesAndSizes))] public void BlockExplicitType(object value, int blockSize, bool useInterpreter) { ConstantExpression constant = Expression.Constant(value, value.GetType()); BlockExpression block = Expression.Block(typeof(object), SingleParameter, PadBlock(blockSize - 1, constant)); Assert.Equal(typeof(object), block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(BlockSizes))] public void BlockInvalidExplicitType(int blockSize) { ConstantExpression constant = Expression.Constant(0); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0)); Assert.Throws<ArgumentException>(() => Expression.Block(typeof(string), SingleParameter, expressions)); Assert.Throws<ArgumentException>(() => Expression.Block(typeof(string), SingleParameter, expressions.ToArray())); } [Theory] [PerCompilationType(nameof(ConstantValuesAndSizes))] public void BlockFromEmptyParametersSameAsFromParams(object value, int blockSize, bool useInterpreter) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression fromParamsBlock = Expression.Block(SingleParameter, expressions.ToArray()); BlockExpression fromEnumBlock = Expression.Block(SingleParameter, expressions); Assert.Equal(fromParamsBlock.GetType(), fromEnumBlock.GetType()); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromParamsBlock)).Compile(useInterpreter)()); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromEnumBlock)).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void InvalidExpressionIndex(object value, int blockSize) { BlockExpression block = Expression.Block(SingleParameter, PadBlock(blockSize - 1, Expression.Constant(value, value.GetType()))); Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[-1]); Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[blockSize]); } [Fact] public void EmptyBlockWithParametersAndNonVoidTypeNotAllowed() { Assert.Throws<ArgumentException>(() => Expression.Block(typeof(int), SingleParameter)); Assert.Throws<ArgumentException>(() => Expression.Block(typeof(int), SingleParameter, Enumerable.Empty<Expression>())); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void ResultPropertyFromParams(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(SingleParameter, expressions.ToArray()); Assert.Same(constant, block.Result); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void ResultPropertyFromEnumerable(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(SingleParameter, expressions); Assert.Same(constant, block.Result); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void VariableCountCorrect(object value, int blockSize) { IEnumerable<ParameterExpression> vars = Enumerable.Range(0, blockSize).Select(i => Expression.Variable(value.GetType())); BlockExpression block = Expression.Block(vars, Expression.Constant(value, value.GetType())); Assert.Equal(blockSize, block.Variables.Count); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] [ActiveIssue(3958)] public void RewriteToSameWithSameValues(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray(); BlockExpression block = Expression.Block(SingleParameter, expressions); Assert.Same(block, block.Update(block.Variables.ToArray(), expressions)); Assert.Same(block, block.Update(block.Variables.ToArray(), expressions)); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void CanFindItems(object value, int blockSize) { ConstantExpression[] values = new ConstantExpression[blockSize]; for (int i = 0; i != values.Length; ++i) values[i] = Expression.Constant(value); BlockExpression block = Expression.Block(SingleParameter, values); IList<Expression> expressions = block.Expressions; for (int i = 0; i != values.Length; ++i) Assert.Equal(i, expressions.IndexOf(values[i])); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void IdentifyNonAbsentItemAsAbsent(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(SingleParameter, expressions); Assert.Equal(-1, block.Expressions.IndexOf(Expression.Default(typeof(long)))); Assert.False(block.Expressions.Contains(null)); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void ExpressionsEnumerable(object value, int blockSize) { ConstantExpression[] values = new ConstantExpression[blockSize]; for (int i = 0; i != values.Length; ++i) values[i] = Expression.Constant(value); BlockExpression block = Expression.Block(SingleParameter, values); Assert.True(values.SequenceEqual(block.Expressions)); int index = 0; foreach (Expression exp in ((IEnumerable)block.Expressions)) Assert.Same(exp, values[index++]); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void UpdateWithExpressionsReturnsSame(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(SingleParameter, expressions); Assert.Same(block, block.Update(block.Variables, block.Expressions)); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void Visit(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(SingleParameter, expressions); Assert.NotSame(block, new TestVistor().Visit(block)); } [Theory] [MemberData(nameof(ObjectAssignableConstantValuesAndSizes))] public void VisitTyped(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(typeof(object), SingleParameter, expressions); Assert.NotSame(block, new TestVistor().Visit(block)); } [Theory] [MemberData(nameof(BlockSizes))] public void NullVariables(int blockSize) { IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0)); IEnumerable<ParameterExpression> vars = Enumerable.Repeat(default(ParameterExpression), 1); Assert.Throws<ArgumentNullException>(() => Expression.Block(vars, expressions)); Assert.Throws<ArgumentNullException>(() => Expression.Block(vars, expressions.ToArray())); Assert.Throws<ArgumentNullException>(() => Expression.Block(typeof(object), vars, expressions)); Assert.Throws<ArgumentNullException>(() => Expression.Block(typeof(object), vars, expressions.ToArray())); } [Theory] [MemberData(nameof(BlockSizes))] public void ByRefVariables(int blockSize) { IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0)); IEnumerable<ParameterExpression> vars = Enumerable.Repeat(Expression.Parameter(typeof(int).MakeByRefType()), 1); Assert.Throws<ArgumentException>(() => Expression.Block(vars, expressions)); Assert.Throws<ArgumentException>(() => Expression.Block(vars, expressions.ToArray())); Assert.Throws<ArgumentException>(() => Expression.Block(typeof(object), vars, expressions)); Assert.Throws<ArgumentException>(() => Expression.Block(typeof(object), vars, expressions.ToArray())); } [Theory] [MemberData(nameof(BlockSizes))] public void RepeatedVariables(int blockSize) { IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0)); ParameterExpression variable = Expression.Variable(typeof(int)); IEnumerable<ParameterExpression> vars = Enumerable.Repeat(variable, 2); Assert.Throws<ArgumentException>(() => Expression.Block(vars, expressions)); Assert.Throws<ArgumentException>(() => Expression.Block(vars, expressions.ToArray())); Assert.Throws<ArgumentException>(() => Expression.Block(typeof(object), vars, expressions)); Assert.Throws<ArgumentException>(() => Expression.Block(typeof(object), vars, expressions.ToArray())); } } }
// <copyright file="ExceptionRaiserTests.cs" company="Heleonix - Hennadii Lutsyshyn"> // Copyright (c) 2017-present Heleonix - Hennadii Lutsyshyn. All rights reserved. // Licensed under the MIT license. See LICENSE file in the repository root for full license information. // </copyright> namespace Heleonix.Utilities.Tests.Exceptions { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using Heleonix.Testing.NUnit.Aaa; using Heleonix.Utilities.Exceptions; using NUnit.Framework; using static Heleonix.Testing.NUnit.Aaa.AaaSpec; /// <summary> /// Tests the <see cref="ExceptionRaiser"/>. /// </summary> [ComponentTest(Type = typeof(ExceptionRaiser))] public static class ExceptionRaiserTests { /// <summary> /// Tests all the exceptions having constructors <see cref="Exception.Exception(string, Exception)"/> /// </summary> [MemberTest(Name = nameof(Exception) + "(string, Exception)")] public static void Exception() { var when = false; string message = null; Exception innerException = null; IEnumerable<MethodInfo> exceptionRaisers = null; var thrownExceptions = new List<Exception>(); Arrange(() => { exceptionRaisers = from methodInfo in typeof(ExceptionRaiser).GetMethods() let parameters = methodInfo.GetParameters() where parameters.Count() == 3 && parameters[0].ParameterType == typeof(bool) && parameters[1].ParameterType == typeof(string) && parameters[2].ParameterType == typeof(Exception) select methodInfo; thrownExceptions.Clear(); }); When("exception raisers are executed", () => { Act(() => { foreach (var exceptionRaiser in exceptionRaisers) { try { exceptionRaiser.Invoke(Guard.Throw, new object[] { when, message, innerException }); } catch (TargetInvocationException e) { thrownExceptions.Add(e.InnerException); } } }); And("a 'when' parameter is false", () => { when = false; Should("not throw any exception", () => { Assert.That(thrownExceptions, Is.Empty); }); }); And("a 'when' parameter is true", () => { when = true; And("a message is provided", () => { message = "exception message"; Should("throw all exceptions with the provided message", () => { foreach (var thrownException in thrownExceptions) { Assert.That(thrownException.Message, Is.EqualTo(message)); Assert.That(thrownException.InnerException, Is.EqualTo(innerException)); } }); And("an inner exception is provided", () => { innerException = new Exception(); Should("throw all exceptions with the provided message and inner exception", () => { foreach (var thrownException in thrownExceptions) { Assert.That(thrownException.Message, Is.EqualTo(message)); Assert.That(thrownException.InnerException, Is.EqualTo(innerException)); } }); }); }); }); }); } /// <summary> /// Tests all the exceptions having constructors <see cref="MissingFieldException.MissingFieldException(string, string)"/> /// </summary> [MemberTest(Name = nameof(Exception) + "(string, string)")] public static void Exception2() { var when = false; string string1 = null; string string2 = null; IEnumerable<MethodInfo> exceptionRaisers = null; var thrownExceptions = new List<Exception>(); Arrange(() => { exceptionRaisers = from methodInfo in typeof(ExceptionRaiser).GetMethods() let parameters = methodInfo.GetParameters() where parameters.Count() == 3 && parameters[0].ParameterType == typeof(bool) && parameters[1].ParameterType == typeof(string) && parameters[2].ParameterType == typeof(string) select methodInfo; thrownExceptions.Clear(); }); When("exception raisers are executed", () => { Act(() => { foreach (var exceptionRaiser in exceptionRaisers) { try { exceptionRaiser.Invoke(Guard.Throw, new object[] { when, string1, string2 }); } catch (TargetInvocationException e) { thrownExceptions.Add(e.InnerException); } } }); And("a 'when' parameter is false", () => { when = false; Should("not throw any exception", () => { Assert.That(thrownExceptions, Is.Empty); }); }); And("a 'when' parameter is true", () => { when = true; And("a first string is provided", () => { string1 = "string 1"; Should("throw all exceptions with the provided first string", () => { foreach (var thrownException in thrownExceptions) { AssertExceptionParameters( thrownException, new[] { typeof(string), typeof(string) }, new[] { string1, string2 }); } }); And("a second string is provided", () => { string2 = "string 2"; Should("throw all exceptions with the provided first and second strings", () => { foreach (var thrownException in thrownExceptions) { AssertExceptionParameters( thrownException, new[] { typeof(string), typeof(string) }, new[] { string1, string2 }); } }); }); }); }); }); } /// <summary> /// Tests all the exceptions having constructors <see cref="FileLoadException.FileLoadException(string, string, Exception)"/> /// </summary> [MemberTest(Name = nameof(Exception) + "(string, string, Exception)")] public static void Exception3() { var when = false; string string1 = null; string string2 = null; Exception innerException = null; IEnumerable<MethodInfo> exceptionRaisers = null; var thrownExceptions = new List<Exception>(); Arrange(() => { exceptionRaisers = from methodInfo in typeof(ExceptionRaiser).GetMethods() let parameters = methodInfo.GetParameters() where parameters.Count() == 4 && parameters[0].ParameterType == typeof(bool) && parameters[1].ParameterType == typeof(string) && parameters[2].ParameterType == typeof(string) && parameters[3].ParameterType == typeof(Exception) select methodInfo; thrownExceptions.Clear(); }); When("exception raisers are executed", () => { Act(() => { foreach (var exceptionRaiser in exceptionRaisers) { try { exceptionRaiser.Invoke(Guard.Throw, new object[] { when, string1, string2, innerException }); } catch (TargetInvocationException e) { thrownExceptions.Add(e.InnerException); } } }); And("a 'when' parameter is false", () => { when = false; Should("not throw any exception", () => { Assert.That(thrownExceptions, Is.Empty); }); }); And("a 'when' parameter is true", () => { when = true; And("a first string is provided", () => { string1 = "string 1"; Should("throw all exceptions with the provided first string", () => { foreach (var thrownException in thrownExceptions) { AssertExceptionParameters( thrownException, new[] { typeof(string), typeof(string), typeof(Exception) }, new object[] { string1, string2, innerException }); } }); And("a second string is provided", () => { string2 = "string 2"; Should("throw all exceptions with the provided first and second strings", () => { foreach (var thrownException in thrownExceptions) { AssertExceptionParameters( thrownException, new[] { typeof(string), typeof(string), typeof(Exception) }, new object[] { string1, string2, innerException }); } }); And("an inner exception is provided", () => { innerException = new Exception(); Should("throw all exceptions with the provided first string, second string and inner exception", () => { foreach (var thrownException in thrownExceptions) { AssertExceptionParameters( thrownException, new[] { typeof(string), typeof(string), typeof(Exception) }, new object[] { string1, string2, innerException }); } }); }); }); }); }); }); } private static void AssertExceptionParameters(Exception e, Type[] ctorParamTypes, object[] expectedParams) { var ctorParams = e.GetType().GetConstructor(ctorParamTypes).GetParameters(); for (int i = 0; i < ctorParams.Length; i++) { var ctorParamName = ctorParams[i].Name; var propName = char.ToUpper(ctorParamName[0], CultureInfo.CurrentCulture) + ctorParamName.Substring(1); if (propName != "Message") { var propInfo = e.GetType().GetProperty(propName); if (propInfo != null) { Assert.That(propInfo.GetValue(e), Is.EqualTo(expectedParams[i])); } else if (expectedParams[i] is string) { Assert.That(e.Message, Contains.Substring(expectedParams[i].ToString())); } } else if (expectedParams[i] != null) { Assert.That(e.Message, Contains.Substring(expectedParams[i].ToString())); } } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/appengine/v1/deploy.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.Appengine.V1 { /// <summary>Holder for reflection information generated from google/appengine/v1/deploy.proto</summary> public static partial class DeployReflection { #region Descriptor /// <summary>File descriptor for google/appengine/v1/deploy.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static DeployReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiBnb29nbGUvYXBwZW5naW5lL3YxL2RlcGxveS5wcm90bxITZ29vZ2xlLmFw", "cGVuZ2luZS52MRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90byL2AQoK", "RGVwbG95bWVudBI5CgVmaWxlcxgBIAMoCzIqLmdvb2dsZS5hcHBlbmdpbmUu", "djEuRGVwbG95bWVudC5GaWxlc0VudHJ5EjUKCWNvbnRhaW5lchgCIAEoCzIi", "Lmdvb2dsZS5hcHBlbmdpbmUudjEuQ29udGFpbmVySW5mbxIpCgN6aXAYAyAB", "KAsyHC5nb29nbGUuYXBwZW5naW5lLnYxLlppcEluZm8aSwoKRmlsZXNFbnRy", "eRILCgNrZXkYASABKAkSLAoFdmFsdWUYAiABKAsyHS5nb29nbGUuYXBwZW5n", "aW5lLnYxLkZpbGVJbmZvOgI4ASJDCghGaWxlSW5mbxISCgpzb3VyY2VfdXJs", "GAEgASgJEhAKCHNoYTFfc3VtGAIgASgJEhEKCW1pbWVfdHlwZRgDIAEoCSIe", "Cg1Db250YWluZXJJbmZvEg0KBWltYWdlGAEgASgJIjIKB1ppcEluZm8SEgoK", "c291cmNlX3VybBgDIAEoCRITCgtmaWxlc19jb3VudBgEIAEoBUJmChdjb20u", "Z29vZ2xlLmFwcGVuZ2luZS52MUILRGVwbG95UHJvdG9QAVo8Z29vZ2xlLmdv", "bGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hcHBlbmdpbmUvdjE7YXBw", "ZW5naW5lYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Appengine.V1.Deployment), global::Google.Appengine.V1.Deployment.Parser, new[]{ "Files", "Container", "Zip" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Appengine.V1.FileInfo), global::Google.Appengine.V1.FileInfo.Parser, new[]{ "SourceUrl", "Sha1Sum", "MimeType" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Appengine.V1.ContainerInfo), global::Google.Appengine.V1.ContainerInfo.Parser, new[]{ "Image" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Appengine.V1.ZipInfo), global::Google.Appengine.V1.ZipInfo.Parser, new[]{ "SourceUrl", "FilesCount" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Code and application artifacts used to deploy a version to App Engine. /// </summary> public sealed partial class Deployment : pb::IMessage<Deployment> { private static readonly pb::MessageParser<Deployment> _parser = new pb::MessageParser<Deployment>(() => new Deployment()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Deployment> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Appengine.V1.DeployReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Deployment() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Deployment(Deployment other) : this() { files_ = other.files_.Clone(); Container = other.container_ != null ? other.Container.Clone() : null; Zip = other.zip_ != null ? other.Zip.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Deployment Clone() { return new Deployment(this); } /// <summary>Field number for the "files" field.</summary> public const int FilesFieldNumber = 1; private static readonly pbc::MapField<string, global::Google.Appengine.V1.FileInfo>.Codec _map_files_codec = new pbc::MapField<string, global::Google.Appengine.V1.FileInfo>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Google.Appengine.V1.FileInfo.Parser), 10); private readonly pbc::MapField<string, global::Google.Appengine.V1.FileInfo> files_ = new pbc::MapField<string, global::Google.Appengine.V1.FileInfo>(); /// <summary> /// Manifest of the files stored in Google Cloud Storage that are included /// as part of this version. All files must be readable using the /// credentials supplied with this call. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::MapField<string, global::Google.Appengine.V1.FileInfo> Files { get { return files_; } } /// <summary>Field number for the "container" field.</summary> public const int ContainerFieldNumber = 2; private global::Google.Appengine.V1.ContainerInfo container_; /// <summary> /// A Docker image that App Engine uses to run the version. /// Only applicable for instances in App Engine flexible environment. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Appengine.V1.ContainerInfo Container { get { return container_; } set { container_ = value; } } /// <summary>Field number for the "zip" field.</summary> public const int ZipFieldNumber = 3; private global::Google.Appengine.V1.ZipInfo zip_; /// <summary> /// The zip file for this deployment, if this is a zip deployment. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Appengine.V1.ZipInfo Zip { get { return zip_; } set { zip_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Deployment); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Deployment other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!Files.Equals(other.Files)) return false; if (!object.Equals(Container, other.Container)) return false; if (!object.Equals(Zip, other.Zip)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= Files.GetHashCode(); if (container_ != null) hash ^= Container.GetHashCode(); if (zip_ != null) hash ^= Zip.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) { files_.WriteTo(output, _map_files_codec); if (container_ != null) { output.WriteRawTag(18); output.WriteMessage(Container); } if (zip_ != null) { output.WriteRawTag(26); output.WriteMessage(Zip); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += files_.CalculateSize(_map_files_codec); if (container_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Container); } if (zip_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Zip); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Deployment other) { if (other == null) { return; } files_.Add(other.files_); if (other.container_ != null) { if (container_ == null) { container_ = new global::Google.Appengine.V1.ContainerInfo(); } Container.MergeFrom(other.Container); } if (other.zip_ != null) { if (zip_ == null) { zip_ = new global::Google.Appengine.V1.ZipInfo(); } Zip.MergeFrom(other.Zip); } } [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: { files_.AddEntriesFrom(input, _map_files_codec); break; } case 18: { if (container_ == null) { container_ = new global::Google.Appengine.V1.ContainerInfo(); } input.ReadMessage(container_); break; } case 26: { if (zip_ == null) { zip_ = new global::Google.Appengine.V1.ZipInfo(); } input.ReadMessage(zip_); break; } } } } } /// <summary> /// Single source file that is part of the version to be deployed. Each source /// file that is deployed must be specified separately. /// </summary> public sealed partial class FileInfo : pb::IMessage<FileInfo> { private static readonly pb::MessageParser<FileInfo> _parser = new pb::MessageParser<FileInfo>(() => new FileInfo()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<FileInfo> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Appengine.V1.DeployReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FileInfo() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FileInfo(FileInfo other) : this() { sourceUrl_ = other.sourceUrl_; sha1Sum_ = other.sha1Sum_; mimeType_ = other.mimeType_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FileInfo Clone() { return new FileInfo(this); } /// <summary>Field number for the "source_url" field.</summary> public const int SourceUrlFieldNumber = 1; private string sourceUrl_ = ""; /// <summary> /// URL source to use to fetch this file. Must be a URL to a resource in /// Google Cloud Storage in the form /// 'http(s)://storage.googleapis.com/\&lt;bucket\>/\&lt;object\>'. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SourceUrl { get { return sourceUrl_; } set { sourceUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "sha1_sum" field.</summary> public const int Sha1SumFieldNumber = 2; private string sha1Sum_ = ""; /// <summary> /// The SHA1 hash of the file, in hex. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Sha1Sum { get { return sha1Sum_; } set { sha1Sum_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "mime_type" field.</summary> public const int MimeTypeFieldNumber = 3; private string mimeType_ = ""; /// <summary> /// The MIME type of the file. /// /// Defaults to the value from Google Cloud Storage. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MimeType { get { return mimeType_; } set { mimeType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as FileInfo); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(FileInfo other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (SourceUrl != other.SourceUrl) return false; if (Sha1Sum != other.Sha1Sum) return false; if (MimeType != other.MimeType) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (SourceUrl.Length != 0) hash ^= SourceUrl.GetHashCode(); if (Sha1Sum.Length != 0) hash ^= Sha1Sum.GetHashCode(); if (MimeType.Length != 0) hash ^= MimeType.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 (SourceUrl.Length != 0) { output.WriteRawTag(10); output.WriteString(SourceUrl); } if (Sha1Sum.Length != 0) { output.WriteRawTag(18); output.WriteString(Sha1Sum); } if (MimeType.Length != 0) { output.WriteRawTag(26); output.WriteString(MimeType); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (SourceUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SourceUrl); } if (Sha1Sum.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Sha1Sum); } if (MimeType.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MimeType); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(FileInfo other) { if (other == null) { return; } if (other.SourceUrl.Length != 0) { SourceUrl = other.SourceUrl; } if (other.Sha1Sum.Length != 0) { Sha1Sum = other.Sha1Sum; } if (other.MimeType.Length != 0) { MimeType = other.MimeType; } } [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: { SourceUrl = input.ReadString(); break; } case 18: { Sha1Sum = input.ReadString(); break; } case 26: { MimeType = input.ReadString(); break; } } } } } /// <summary> /// Docker image that is used to start a VM container for the version you /// deploy. /// </summary> public sealed partial class ContainerInfo : pb::IMessage<ContainerInfo> { private static readonly pb::MessageParser<ContainerInfo> _parser = new pb::MessageParser<ContainerInfo>(() => new ContainerInfo()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ContainerInfo> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Appengine.V1.DeployReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ContainerInfo() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ContainerInfo(ContainerInfo other) : this() { image_ = other.image_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ContainerInfo Clone() { return new ContainerInfo(this); } /// <summary>Field number for the "image" field.</summary> public const int ImageFieldNumber = 1; private string image_ = ""; /// <summary> /// URI to the hosted container image in a Docker repository. The URI must be /// fully qualified and include a tag or digest. /// Examples: "gcr.io/my-project/image:tag" or "gcr.io/my-project/image@digest" /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Image { get { return image_; } set { image_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ContainerInfo); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ContainerInfo other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Image != other.Image) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Image.Length != 0) hash ^= Image.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 (Image.Length != 0) { output.WriteRawTag(10); output.WriteString(Image); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Image.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Image); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ContainerInfo other) { if (other == null) { return; } if (other.Image.Length != 0) { Image = other.Image; } } [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: { Image = input.ReadString(); break; } } } } } public sealed partial class ZipInfo : pb::IMessage<ZipInfo> { private static readonly pb::MessageParser<ZipInfo> _parser = new pb::MessageParser<ZipInfo>(() => new ZipInfo()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ZipInfo> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Appengine.V1.DeployReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ZipInfo() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ZipInfo(ZipInfo other) : this() { sourceUrl_ = other.sourceUrl_; filesCount_ = other.filesCount_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ZipInfo Clone() { return new ZipInfo(this); } /// <summary>Field number for the "source_url" field.</summary> public const int SourceUrlFieldNumber = 3; private string sourceUrl_ = ""; /// <summary> /// URL of the zip file to deploy from. Must be a URL to a resource in /// Google Cloud Storage in the form /// 'http(s)://storage.googleapis.com/\&lt;bucket\>/\&lt;object\>'. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SourceUrl { get { return sourceUrl_; } set { sourceUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "files_count" field.</summary> public const int FilesCountFieldNumber = 4; private int filesCount_; /// <summary> /// An estimate of the number of files in a zip for a zip deployment. /// If set, must be greater than or equal to the actual number of files. /// Used for optimizing performance; if not provided, deployment may be slow. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int FilesCount { get { return filesCount_; } set { filesCount_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ZipInfo); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ZipInfo other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (SourceUrl != other.SourceUrl) return false; if (FilesCount != other.FilesCount) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (SourceUrl.Length != 0) hash ^= SourceUrl.GetHashCode(); if (FilesCount != 0) hash ^= FilesCount.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 (SourceUrl.Length != 0) { output.WriteRawTag(26); output.WriteString(SourceUrl); } if (FilesCount != 0) { output.WriteRawTag(32); output.WriteInt32(FilesCount); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (SourceUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SourceUrl); } if (FilesCount != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(FilesCount); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ZipInfo other) { if (other == null) { return; } if (other.SourceUrl.Length != 0) { SourceUrl = other.SourceUrl; } if (other.FilesCount != 0) { FilesCount = other.FilesCount; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 26: { SourceUrl = input.ReadString(); break; } case 32: { FilesCount = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using dia2; using Microsoft.Extensions.Logging; namespace Microsoft.Extensions.Testing.Abstractions { public class SourceInformationProvider : ISourceInformationProvider { //private readonly IMetadataProjectReference _project; private readonly string _pdbPath; private readonly ILogger _logger; private bool? _isInitialized; private IDiaDataSource _diaDataSource; private IDiaSession _diaSession; private AssemblyData _assemblyData; public SourceInformationProvider( string pdbPath, ILogger logger) { if (String.IsNullOrWhiteSpace(pdbPath) || !File.Exists(pdbPath)) { throw new ArgumentException($"The file '{pdbPath}' does not exist.", nameof(pdbPath)); } _pdbPath = pdbPath; _logger = logger; } public SourceInformation GetSourceInformation(MethodInfo method) { if (method == null) { throw new ArgumentNullException(nameof(method)); } if (!EnsureInitialized()) { // Unable to load DIA or we had a failure reading the symbols. return null; } Debug.Assert(_isInitialized == true); Debug.Assert(_diaSession != null); Debug.Assert(_assemblyData != null); // We need a MethodInfo so we can deal with cases where no user code shows up for provided // method and class name. In particular: // // 1) inherited test methods (method.DeclaringType) // 2) async test methods (see StateMachineAttribute). // // Note that this doesn't deal gracefully with overloaded methods. Symbol APIs don't provide // a way to match overloads. We'd really need MetadataTokens to do this correctly (missing in // CoreCLR). method = ResolveBestMethodInfo(method); var className = method.DeclaringType.FullName; var methodName = method.Name; // The DIA code doesn't include a + for nested classes, just a dot. var symbolId = FindMethodSymbolId(className.Replace('+', '.'), methodName); if (symbolId == null) { // No matching method in the symbol. return null; } try { return GetSourceInformation(symbolId.Value); } catch (Exception ex) { _logger.LogWarning("Failed to access source information in symbol.", ex); return null; } } private MethodInfo ResolveBestMethodInfo(MethodInfo method) { Debug.Assert(_isInitialized == true); // If a method has a StateMachineAttribute, then all of the user code will show up // in the symbols associated with the compiler-generated code. So, we need to look // for the 'MoveNext' on the generated type and resolve symbols for that. var attribute = method.GetCustomAttribute<StateMachineAttribute>(); if (attribute?.StateMachineType == null) { return method; } return attribute.StateMachineType.GetMethod( "MoveNext", BindingFlags.Instance | BindingFlags.NonPublic); } private uint? FindMethodSymbolId(string className, string methodName) { Debug.Assert(_isInitialized == true); ClassData classData; if (_assemblyData.Classes.TryGetValue(className, out classData)) { MethodData methodData; if (classData.Methods.TryGetValue(methodName, out methodData)) { return methodData.SymbolId; } } return null; } private SourceInformation GetSourceInformation(uint symbolId) { Debug.Assert(_isInitialized == true); string filename = null; int? lineNumber = null; IDiaSymbol diaSymbol; _diaSession.symbolById(symbolId, out diaSymbol); if (diaSymbol == null) { // Doesn't seem like this should happen, since DIA gave us the id. return null; } IDiaEnumLineNumbers diaLineNumbers; _diaSession.findLinesByAddr( diaSymbol.addressSection, diaSymbol.addressOffset, (uint)diaSymbol.length, out diaLineNumbers); // Resist the user to use foreach here. It doesn't work well with these APIs. IDiaLineNumber diaLineNumber; var lineNumbersFetched = 0u; diaLineNumbers.Next(1u, out diaLineNumber, out lineNumbersFetched); while (lineNumbersFetched == 1 && diaLineNumber != null) { if (filename == null) { var diaFile = diaLineNumber.sourceFile; if (diaFile != null) { filename = diaFile.fileName; } } if (diaLineNumber.lineNumber != 16707566u) { // We'll see multiple line numbers for the same method, but we just want the first one. lineNumber = Math.Min(lineNumber ?? Int32.MaxValue, (int)diaLineNumber.lineNumber); } diaLineNumbers.Next(1u, out diaLineNumber, out lineNumbersFetched); } if (filename == null || lineNumber == null) { return null; } else { return new SourceInformation(filename, lineNumber.Value); } } private bool EnsureInitialized() { if (_isInitialized.HasValue) { return _isInitialized.Value; } try { _diaDataSource = (IDiaDataSource)new DiaDataSource(); _isInitialized = true; } catch (Exception ex) { _logger.LogWarning("Failed to create DIA DataSource. No source information will be available.", ex); _isInitialized = false; return _isInitialized.Value; } // We have a project, and we successfully loaded DIA, so let's capture the symbols // and create a session. try { _diaDataSource.loadDataFromPdb(_pdbPath); _diaDataSource.openSession(out _diaSession); } catch (Exception ex) { _logger.LogWarning("Failed to load symbols. No source information will be available.", ex); _isInitialized = false; return _isInitialized.Value; } try { _assemblyData = FetchSymbolData(_diaSession); } catch (Exception ex) { _logger.LogWarning("Failed to read symbols. No source information will be available.", ex); _isInitialized = false; return _isInitialized.Value; } _isInitialized = true; return _isInitialized.Value; } // Builds a lookup table of class+method name. // // It's easier to build it at once by enumerating, once we have the table, we // can use the symbolIds to look up the sources when we need them. private static AssemblyData FetchSymbolData(IDiaSession session) { // This will be a *flat* enumerator of all classes. // // A nested class will not contain a '+' in it's name, just a '.' separating the parent class name from // the child class name. IDiaEnumSymbols diaClasses; session.findChildren( session.globalScope, // Search at the top-level. SymTagEnum.SymTagCompiland, // Just find classes. name: null, // Don't filter by name. compareFlags: 0u, // doesn't matter because name is null. ppResult: out diaClasses); var assemblyData = new AssemblyData(); // Resist the urge to use foreach here. It doesn't work well with these APIs. var classesFetched = 0u; IDiaSymbol diaClass; diaClasses.Next(1u, out diaClass, out classesFetched); while (classesFetched == 1 && diaClass != null) { var classData = new ClassData() { Name = diaClass.name, SymbolId = diaClass.symIndexId, }; assemblyData.Classes.Add(diaClass.name, classData); IDiaEnumSymbols diaMethods; session.findChildren( diaClass, SymTagEnum.SymTagFunction, name: null, // Don't filter by name. compareFlags: 0u, // doesn't matter because name is null. ppResult: out diaMethods); // Resist the urge to use foreach here. It doesn't work well with these APIs. var methodsFetched = 0u; IDiaSymbol diaMethod; diaMethods.Next(1u, out diaMethod, out methodsFetched); while (methodsFetched == 1 && diaMethod != null) { classData.Methods[diaMethod.name] = new MethodData() { Name = diaMethod.name, SymbolId = diaMethod.symIndexId, }; diaMethods.Next(1u, out diaMethod, out methodsFetched); } diaClasses.Next(1u, out diaClass, out classesFetched); } return assemblyData; } private class AssemblyData { public IDictionary<string, ClassData> Classes { get; } = new Dictionary<string, ClassData>(); } private class ClassData { public string Name { get; set; } public uint SymbolId { get; set; } public IDictionary<string, MethodData> Methods { get; } = new Dictionary<string, MethodData>(); } private class MethodData { public string Name { get; set; } public uint SymbolId { get; set; } } } }
using System; using System.Collections.Generic; using AsmResolver.DotNet.Signatures; using AsmResolver.DotNet.Signatures.Types; using AsmResolver.PE.DotNet.Metadata.Tables; namespace AsmResolver.DotNet { /// <summary> /// Provides a default implementation for the <see cref="IMetadataResolver"/> interface. /// </summary> public class DefaultMetadataResolver : IMetadataResolver { private readonly IDictionary<ITypeDescriptor, TypeDefinition> _typeCache; private readonly SignatureComparer _comparer = new() { AcceptNewerAssemblyVersionNumbers = true }; /// <summary> /// Creates a new metadata resolver. /// </summary> /// <param name="assemblyResolver">The resolver to use for resolving external assemblies.</param> public DefaultMetadataResolver(IAssemblyResolver assemblyResolver) { AssemblyResolver = assemblyResolver ?? throw new ArgumentNullException(nameof(assemblyResolver)); _typeCache = new Dictionary<ITypeDescriptor, TypeDefinition>(); } /// <inheritdoc /> public IAssemblyResolver AssemblyResolver { get; } /// <inheritdoc /> public TypeDefinition? ResolveType(ITypeDescriptor? type) { return type switch { TypeDefinition definition => definition, TypeReference reference => ResolveTypeReference(reference), TypeSpecification specification => ResolveType(specification.Signature), TypeSignature signature => ResolveTypeSignature(signature), ExportedType exportedType => ResolveExportedType(exportedType), _ => null }; } private TypeDefinition? LookupInCache(ITypeDescriptor type) { if (_typeCache.TryGetValue(type, out var typeDef)) { // Check if type definition has changed since last lookup. if (typeDef.IsTypeOf(type.Namespace, type.Name)) return typeDef; _typeCache.Remove(type); } return null; } private TypeDefinition? ResolveTypeReference(TypeReference? reference) { if (reference is null) return null; var resolvedType = LookupInCache(reference); if (resolvedType is not null) return resolvedType; var resolution = new TypeResolution(AssemblyResolver); resolvedType = resolution.ResolveTypeReference(reference); if (resolvedType is not null) _typeCache[reference] = resolvedType; return resolvedType; } private TypeDefinition? ResolveExportedType(ExportedType? exportedType) { if (exportedType is null) return null; var resolvedType = LookupInCache(exportedType); if (resolvedType != null) return resolvedType; var resolution = new TypeResolution(AssemblyResolver); resolvedType = resolution.ResolveExportedType(exportedType); if (resolvedType != null) _typeCache[exportedType] = resolvedType; return resolvedType; } private TypeDefinition? ResolveTypeSignature(TypeSignature? signature) { var type = signature?.GetUnderlyingTypeDefOrRef(); if (type is null) return null; return type.MetadataToken.Table switch { TableIndex.TypeDef => (TypeDefinition) type, TableIndex.TypeRef => ResolveTypeReference((TypeReference) type), TableIndex.TypeSpec => ResolveTypeSignature(((TypeSpecification) type).Signature), _ => null }; } /// <inheritdoc /> public MethodDefinition? ResolveMethod(IMethodDescriptor? method) { if (method is null) return null; var declaringType = ResolveType(method.DeclaringType); if (declaringType is null) return null; for (int i = 0; i < declaringType.Methods.Count; i++) { var candidate = declaringType.Methods[i]; if (candidate.Name == method.Name && _comparer.Equals(method.Signature, candidate.Signature)) return candidate; } return null; } /// <inheritdoc /> public FieldDefinition? ResolveField(IFieldDescriptor? field) { if (field is null) return null; var declaringType = ResolveType(field.DeclaringType); if (declaringType is null) return null; for (int i = 0; i < declaringType.Fields.Count; i++) { var candidate = declaringType.Fields[i]; if (candidate.Name == field.Name && _comparer.Equals(field.Signature, candidate.Signature)) return candidate; } return null; } private readonly struct TypeResolution { private readonly IAssemblyResolver _assemblyResolver; private readonly Stack<IResolutionScope> _scopeStack; private readonly Stack<IImplementation> _implementationStack; public TypeResolution(IAssemblyResolver resolver) { _assemblyResolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); _scopeStack = new Stack<IResolutionScope>(); _implementationStack = new Stack<IImplementation>(); } public TypeDefinition? ResolveTypeReference(TypeReference? reference) { var scope = reference?.Scope; if (reference?.Name is null || scope is null || _scopeStack.Contains(scope)) return null; _scopeStack.Push(scope); switch (scope.MetadataToken.Table) { case TableIndex.AssemblyRef: var assemblyDefScope = _assemblyResolver.Resolve((AssemblyReference) scope); return assemblyDefScope != null ? FindTypeInAssembly(assemblyDefScope, reference.Namespace, reference.Name) : null; case TableIndex.Module: return FindTypeInModule((ModuleDefinition) scope, reference.Namespace, reference.Name); case TableIndex.TypeRef: var typeDefScope = ResolveTypeReference((TypeReference) scope); return typeDefScope != null ? FindTypeInType(typeDefScope, reference.Name) : null; default: return null; } } public TypeDefinition? ResolveExportedType(ExportedType? exportedType) { var implementation = exportedType?.Implementation; if (exportedType?.Name is null || implementation is null || _implementationStack.Contains(implementation)) return null; _implementationStack.Push(implementation); switch (implementation.MetadataToken.Table) { case TableIndex.AssemblyRef: var assembly = _assemblyResolver.Resolve((AssemblyReference) implementation); return assembly is {} ? FindTypeInAssembly(assembly, exportedType.Namespace, exportedType.Name) : null; case TableIndex.File when !string.IsNullOrEmpty(implementation.Name): var module = FindModuleInAssembly(exportedType.Module!.Assembly!, implementation.Name!); return module is {} ? FindTypeInModule(module, exportedType.Namespace, exportedType.Name) : null; case TableIndex.ExportedType: var exportedDeclaringType = (ExportedType) implementation; var declaringType = ResolveExportedType(exportedDeclaringType); return declaringType is {} ? FindTypeInType(declaringType, exportedType.Name) : null; default: throw new ArgumentOutOfRangeException(); } } private TypeDefinition? FindTypeInAssembly(AssemblyDefinition assembly, string? ns, string name) { for (int i = 0; i < assembly.Modules.Count; i++) { var module = assembly.Modules[i]; var type = FindTypeInModule(module, ns, name); if (type != null) return type; } return null; } private TypeDefinition? FindTypeInModule(ModuleDefinition module, string? ns, string name) { for (int i = 0; i < module.ExportedTypes.Count; i++) { var exportedType = module.ExportedTypes[i]; if (exportedType.IsTypeOf(ns, name)) return ResolveExportedType(exportedType); } for (int i = 0; i < module.TopLevelTypes.Count; i++) { var type = module.TopLevelTypes[i]; if (type.IsTypeOf(ns, name)) return type; } return null; } private static TypeDefinition? FindTypeInType(TypeDefinition enclosingType, string name) { for (int i = 0; i < enclosingType.NestedTypes.Count; i++) { var type = enclosingType.NestedTypes[i]; if (type.Name == name) return type; } return null; } private static ModuleDefinition? FindModuleInAssembly(AssemblyDefinition assembly, string name) { for (int i = 0; i < assembly.Modules.Count; i++) { var module = assembly.Modules[i]; if (module.Name == name) return module; } return null; } } } }
//----------------------------------------------------------------------- // <copyright file="NFCProperty.cs"> // Copyright (C) 2015-2015 lvsheng.huang <https://github.com/ketoo/NFrame> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using System.Text; using System.Collections; using System.Collections.Generic; namespace NFrame { public class NFCProperty : NFIProperty { public NFCProperty( NFGUID self, string strPropertyName, NFIDataList varData) { mSelf = self; msPropertyName = strPropertyName; mxData = new NFIDataList.TData(varData.GetType(0)); switch (varData.GetType(0)) { case NFIDataList.VARIANT_TYPE.VTYPE_INT: mxData.Set(varData.IntVal(0)); break; case NFIDataList.VARIANT_TYPE.VTYPE_FLOAT: mxData.Set(varData.FloatVal(0)); break; case NFIDataList.VARIANT_TYPE.VTYPE_OBJECT: mxData.Set(varData.ObjectVal(0)); break; case NFIDataList.VARIANT_TYPE.VTYPE_STRING: mxData.Set(varData.StringVal(0)); break; case NFIDataList.VARIANT_TYPE.VTYPE_VECTOR2: mxData.Set(varData.Vector2Val(0)); break; case NFIDataList.VARIANT_TYPE.VTYPE_VECTOR3: mxData.Set(varData.Vector3Val(0)); break; default: break; } } public NFCProperty(NFGUID self, string strPropertyName, NFIDataList.TData varData) { mSelf = self; msPropertyName = strPropertyName; mxData = new NFIDataList.TData(varData); } public override string GetKey() { return msPropertyName; } public override NFIDataList.VARIANT_TYPE GetType() { return mxData.GetType(); } public override NFIDataList.TData GetData() { return mxData; } public override void SetUpload(bool upload) { mbUpload = upload; } public override bool GetUpload() { return mbUpload; } public override Int64 QueryInt() { if (NFIDataList.VARIANT_TYPE.VTYPE_INT == mxData.GetType()) { return mxData.IntVal(); } return NFIDataList.NULL_INT; } public override double QueryFloat() { if (NFIDataList.VARIANT_TYPE.VTYPE_FLOAT == mxData.GetType()) { return (double)mxData.FloatVal(); } return NFIDataList.NULL_DOUBLE; } public override string QueryString() { if (NFIDataList.VARIANT_TYPE.VTYPE_STRING == mxData.GetType()) { return mxData.StringVal(); } return NFIDataList.NULL_STRING; } public override NFGUID QueryObject() { if (NFIDataList.VARIANT_TYPE.VTYPE_INT == mxData.GetType()) { return (NFGUID)mxData.ObjectVal(); } return NFIDataList.NULL_OBJECT; } public override NFVector2 QueryVector2() { if (NFIDataList.VARIANT_TYPE.VTYPE_VECTOR2 == mxData.GetType()) { return (NFVector2)mxData.Vector2Val(); } return NFIDataList.NULL_VECTOR2; } public override NFVector3 QueryVector3() { if (NFIDataList.VARIANT_TYPE.VTYPE_VECTOR3 == mxData.GetType()) { return (NFVector3)mxData.Vector3Val(); } return NFIDataList.NULL_VECTOR3; } public override bool SetInt(Int64 value) { if (mxData.IntVal() != value) { NFIDataList.TData oldValue = new NFIDataList.TData(mxData); NFIDataList.TData newValue = new NFIDataList.TData(NFIDataList.VARIANT_TYPE.VTYPE_INT); newValue.Set(value); mxData.Set(value); if (null != doHandleDel) { doHandleDel(mSelf, msPropertyName, oldValue, newValue); } } return true; } public override bool SetFloat(double value) { if (mxData.FloatVal() - value > NFIDataList.EPS_DOUBLE || mxData.FloatVal() - value < -NFIDataList.EPS_DOUBLE) { NFIDataList.TData oldValue = new NFIDataList.TData(mxData); NFIDataList.TData newValue = new NFIDataList.TData(NFIDataList.VARIANT_TYPE.VTYPE_FLOAT); newValue.Set(value); mxData.Set(value); if (null != doHandleDel) { doHandleDel(mSelf, msPropertyName, oldValue, newValue); } } return true; } public override bool SetString(string value) { if (mxData.StringVal() != value) { NFIDataList.TData oldValue = new NFIDataList.TData(mxData); NFIDataList.TData newValue = new NFIDataList.TData(NFIDataList.VARIANT_TYPE.VTYPE_STRING); newValue.Set(value); mxData.Set(value); if (null != doHandleDel) { doHandleDel(mSelf, msPropertyName, oldValue, newValue); } } return true; } public override bool SetObject(NFGUID value) { if (mxData.ObjectVal() != value) { NFIDataList.TData oldValue = new NFIDataList.TData(mxData); NFIDataList.TData newValue = new NFIDataList.TData(NFIDataList.VARIANT_TYPE.VTYPE_OBJECT); newValue.Set(value); mxData.Set(value); if (null != doHandleDel) { doHandleDel(mSelf, msPropertyName, oldValue, newValue); } } return true; } public override bool SetVector2(NFVector2 value) { if (mxData.Vector2Val() != value) { NFIDataList.TData oldValue = new NFIDataList.TData(mxData); NFIDataList.TData newValue = new NFIDataList.TData(NFIDataList.VARIANT_TYPE.VTYPE_VECTOR2); newValue.Set(value); mxData.Set(value); if (null != doHandleDel) { doHandleDel(mSelf, msPropertyName, oldValue, newValue); } } return true; } public override bool SetVector3(NFVector3 value) { if (mxData.Vector3Val() != value) { NFIDataList.TData oldValue = new NFIDataList.TData(mxData); NFIDataList.TData newValue = new NFIDataList.TData(NFIDataList.VARIANT_TYPE.VTYPE_VECTOR3); newValue.Set(value); mxData.Set(value); if (null != doHandleDel) { doHandleDel(mSelf, msPropertyName, oldValue, newValue); } } return true; } public override bool SetData(NFIDataList.TData x) { if (NFIDataList.VARIANT_TYPE.VTYPE_UNKNOWN == mxData.GetType() || x.GetType() == mxData.GetType()) { switch (mxData.GetType()) { case NFIDataList.VARIANT_TYPE.VTYPE_INT: SetInt(x.IntVal()); break; case NFIDataList.VARIANT_TYPE.VTYPE_STRING: SetString(x.StringVal()); break; case NFIDataList.VARIANT_TYPE.VTYPE_FLOAT: SetFloat(x.FloatVal()); break; case NFIDataList.VARIANT_TYPE.VTYPE_OBJECT: SetObject(x.ObjectVal()); break; case NFIDataList.VARIANT_TYPE.VTYPE_VECTOR2: SetVector2(x.Vector2Val()); break; case NFIDataList.VARIANT_TYPE.VTYPE_VECTOR3: SetVector3(x.Vector3Val()); break; default: break; } return true; } return false; } public override void RegisterCallback(PropertyEventHandler handler) { doHandleDel += handler; } PropertyEventHandler doHandleDel; NFGUID mSelf; string msPropertyName; NFIDataList.TData mxData; bool mbUpload; } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Orleans.Runtime.Configuration; namespace Orleans.Runtime.Scheduler { [DebuggerDisplay("OrleansTaskScheduler RunQueue={RunQueue.Length}")] internal class OrleansTaskScheduler : TaskScheduler, ITaskScheduler, IHealthCheckParticipant { private readonly TraceLogger logger = TraceLogger.GetLogger("Scheduler.OrleansTaskScheduler", TraceLogger.LoggerType.Runtime); private readonly ConcurrentDictionary<ISchedulingContext, WorkItemGroup> workgroupDirectory; // work group directory private bool applicationTurnsStopped; internal WorkQueue RunQueue { get; private set; } internal WorkerPool Pool { get; private set; } internal static TimeSpan TurnWarningLengthThreshold { get; set; } internal TimeSpan DelayWarningThreshold { get; private set; } public static OrleansTaskScheduler Instance { get; private set; } public int RunQueueLength { get { return RunQueue.Length; } } public OrleansTaskScheduler(int maxActiveThreads) : this(maxActiveThreads, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100), NodeConfiguration.INJECT_MORE_WORKER_THREADS) { } public OrleansTaskScheduler(GlobalConfiguration globalConfig, NodeConfiguration config) : this(config.MaxActiveThreads, config.DelayWarningThreshold, config.ActivationSchedulingQuantum, config.TurnWarningLengthThreshold, config.InjectMoreWorkerThreads) { } private OrleansTaskScheduler(int maxActiveThreads, TimeSpan delayWarningThreshold, TimeSpan activationSchedulingQuantum, TimeSpan turnWarningLengthThreshold, bool injectMoreWorkerThreads) { Instance = this; DelayWarningThreshold = delayWarningThreshold; WorkItemGroup.ActivationSchedulingQuantum = activationSchedulingQuantum; TurnWarningLengthThreshold = turnWarningLengthThreshold; applicationTurnsStopped = false; workgroupDirectory = new ConcurrentDictionary<ISchedulingContext, WorkItemGroup>(); RunQueue = new WorkQueue(); logger.Info("Starting OrleansTaskScheduler with {0} Max Active application Threads and 1 system thread.", maxActiveThreads); Pool = new WorkerPool(this, maxActiveThreads, injectMoreWorkerThreads); IntValueStatistic.FindOrCreate(StatisticNames.SCHEDULER_WORKITEMGROUP_COUNT, () => WorkItemGroupCount); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_INSTANTANEOUS_PER_QUEUE, "Scheduler.LevelOne"), () => RunQueueLength); if (!StatisticsCollector.CollectShedulerQueuesStats) return; FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageRunQueueLengthLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageEnqueuedLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageArrivalRateLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumRunQueueLengthLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumEnqueuedLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumArrivalRateLevelTwo); } public int WorkItemGroupCount { get { return workgroupDirectory.Count; } } private float AverageRunQueueLengthLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght) / (float)workgroupDirectory.Values.Count; } } private float AverageEnqueuedLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests) / (float)workgroupDirectory.Values.Count; } } private float AverageArrivalRateLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate) / (float)workgroupDirectory.Values.Count; } } private float SumRunQueueLengthLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght); } } private float SumEnqueuedLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests); } } private float SumArrivalRateLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate); } } public void Start() { Pool.Start(); } public void StopApplicationTurns() { #if DEBUG if (logger.IsVerbose) logger.Verbose("StopApplicationTurns"); #endif RunQueue.RunDownApplication(); applicationTurnsStopped = true; foreach (var group in workgroupDirectory.Values) { if (!group.IsSystem) group.Stop(); } } public void Stop() { RunQueue.RunDown(); Pool.Stop(); } protected override IEnumerable<Task> GetScheduledTasks() { return new Task[0]; } protected override void QueueTask(Task task) { var contextObj = task.AsyncState; #if DEBUG if (logger.IsVerbose2) logger.Verbose2("QueueTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif var context = contextObj as ISchedulingContext; var workItemGroup = GetWorkItemGroup(context); if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystem) { // Drop the task on the floor if it's an application work item and application turns are stopped logger.Warn(ErrorCode.SchedulerAppTurnsStopped, string.Format("Dropping Task {0} because applicaiton turns are stopped", task)); return; } if (workItemGroup == null) { var todo = new TaskWorkItem(this, task, context); RunQueue.Add(todo); } else { var error = String.Format("QueueTask was called on OrleansTaskScheduler for task {0} on Context {1}." + " Should only call OrleansTaskScheduler.QueueTask with tasks on the null context.", task.Id, context); logger.Error(ErrorCode.SchedulerQueueTaskWrongCall, error); throw new InvalidOperationException(error); } } // Enqueue a work item to a given context public void QueueWorkItem(IWorkItem workItem, ISchedulingContext context) { #if DEBUG if (logger.IsVerbose2) logger.Verbose2("QueueWorkItem " + context); #endif if (workItem is TaskWorkItem) { var error = String.Format("QueueWorkItem was called on OrleansTaskScheduler for TaskWorkItem {0} on Context {1}." + " Should only call OrleansTaskScheduler.QueueWorkItem on WorkItems that are NOT TaskWorkItem. Tasks should be queued to the scheduler via QueueTask call.", workItem.ToString(), context); logger.Error(ErrorCode.SchedulerQueueWorkItemWrongCall, error); throw new InvalidOperationException(error); } var workItemGroup = GetWorkItemGroup(context); if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystem) { // Drop the task on the floor if it's an application work item and application turns are stopped var msg = string.Format("Dropping work item {0} because applicaiton turns are stopped", workItem); logger.Warn(ErrorCode.SchedulerAppTurnsStopped, msg); return; } workItem.SchedulingContext = context; // We must wrap any work item in Task and enqueue it as a task to the right scheduler via Task.Start. // This will make sure the TaskScheduler.Current is set correctly on any task that is created implicitly in the execution of this workItem. if (workItemGroup == null) { Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem, context, this); t.Start(this); } else { // Create Task wrapper for this work item Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem, context, workItemGroup.TaskRunner); t.Start(workItemGroup.TaskRunner); } } // Only required if you have work groups flagged by a context that is not a WorkGroupingContext public WorkItemGroup RegisterWorkContext(ISchedulingContext context) { if (context == null) return null; var wg = new WorkItemGroup(this, context); workgroupDirectory.TryAdd(context, wg); return wg; } // Only required if you have work groups flagged by a context that is not a WorkGroupingContext public void UnregisterWorkContext(ISchedulingContext context) { if (context == null) return; WorkItemGroup workGroup; if (workgroupDirectory.TryRemove(context, out workGroup)) workGroup.Stop(); } // public for testing only -- should be private, otherwise public WorkItemGroup GetWorkItemGroup(ISchedulingContext context) { WorkItemGroup workGroup = null; if (context != null) workgroupDirectory.TryGetValue(context, out workGroup); return workGroup; } public TaskScheduler GetTaskScheduler(ISchedulingContext context) { if (context == null) return this; WorkItemGroup workGroup; return workgroupDirectory.TryGetValue(context, out workGroup) ? (TaskScheduler) workGroup.TaskRunner : this; } public override int MaximumConcurrencyLevel { get { return Pool.MaxActiveThreads; } } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { //bool canExecuteInline = WorkerPoolThread.CurrentContext != null; var ctx = RuntimeContext.Current; bool canExecuteInline = ctx == null || ctx.ActivationContext==null; #if DEBUG if (logger.IsVerbose2) { logger.Verbose2("TryExecuteTaskInline Id={0} with Status={1} PreviouslyQueued={2} CanExecute={3}", task.Id, task.Status, taskWasPreviouslyQueued, canExecuteInline); } #endif if (!canExecuteInline) return false; if (taskWasPreviouslyQueued) canExecuteInline = TryDequeue(task); if (!canExecuteInline) return false; // We can't execute tasks in-line on non-worker pool threads // We are on a worker pool thread, so can execute this task bool done = TryExecuteTask(task); if (!done) { logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete1, "TryExecuteTaskInline: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}", task.Id, task.Status); } return done; } /// <summary> /// Run the specified task synchronously on the current thread /// </summary> /// <param name="task"><c>Task</c> to be executed</param> public void RunTask(Task task) { #if DEBUG if (logger.IsVerbose2) logger.Verbose2("RunTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif var context = RuntimeContext.CurrentActivationContext; var workItemGroup = GetWorkItemGroup(context); if (workItemGroup == null) { RuntimeContext.SetExecutionContext(null, this); bool done = TryExecuteTask(task); if (!done) logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete2, "RunTask: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}", task.Id, task.Status); } else { var error = String.Format("RunTask was called on OrleansTaskScheduler for task {0} on Context {1}. Should only call OrleansTaskScheduler.RunTask on tasks queued on a null context.", task.Id, context); logger.Error(ErrorCode.SchedulerTaskRunningOnWrongScheduler1, error); throw new InvalidOperationException(error); } #if DEBUG if (logger.IsVerbose2) logger.Verbose2("RunTask: Completed Id={0} with Status={1} task.AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif } // Returns true if healthy, false if not public bool CheckHealth(DateTime lastCheckTime) { return Pool.DoHealthCheck(); } /// <summary> /// Action to be invoked when there is no more work for this scheduler /// </summary> internal Action OnIdle { get; set; } /// <summary> /// Invoked by WorkerPool when all threads go idle /// </summary> internal void OnAllWorkerThreadsIdle() { if (OnIdle == null || RunQueueLength != 0) return; #if DEBUG if (logger.IsVerbose2) logger.Verbose2("OnIdle"); #endif OnIdle(); } internal void PrintStatistics() { if (!logger.IsInfo) return; var stats = Utils.EnumerableToString(workgroupDirectory.Values.OrderBy(wg => wg.Name), wg => string.Format("--{0}", wg.DumpStatus()), "\r\n"); if (stats.Length > 0) logger.LogWithoutBulkingAndTruncating(Logger.Severity.Info, ErrorCode.SchedulerStatistics, "OrleansTaskScheduler.PrintStatistics(): RunQueue={0}, WorkItems={1}, Directory:\n{2}", RunQueue.Length, WorkItemGroupCount, stats); } internal void DumpSchedulerStatus(bool alwaysOutput = true) { if (!logger.IsVerbose && !alwaysOutput) return; PrintStatistics(); var sb = new StringBuilder(); sb.AppendLine("Dump of current OrleansTaskScheduler status:"); sb.AppendFormat("CPUs={0} RunQueue={1}, WorkItems={2} {3}", Environment.ProcessorCount, RunQueue.Length, workgroupDirectory.Count, applicationTurnsStopped ? "STOPPING" : "").AppendLine(); sb.AppendLine("RunQueue:"); RunQueue.DumpStatus(sb); Pool.DumpStatus(sb); foreach (var workgroup in workgroupDirectory.Values) sb.AppendLine(workgroup.DumpStatus()); logger.LogWithoutBulkingAndTruncating(Logger.Severity.Info, ErrorCode.SchedulerStatus, sb.ToString()); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Threading; using System.Collections.Generic; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client; using Apache.Geode.Client.UnitTests; using Region = Apache.Geode.Client.IRegion<Object, Object>; using Apache.Geode.Client.Tests; #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* class CSTXListener<TKey, TVal> : TransactionListenerAdapter<TKey, TVal> { public CSTXListener(string cacheName) { m_cacheName = cacheName; } public override void AfterCommit(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; afterCommitEvents++; afterCommitKeyEvents += te.Events.Length; } public override void AfterFailedCommit(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; afterFailedCommitEvents++; afterFailedCommitKeyEvents += te.Events.Length; } public override void AfterRollback(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; afterRollbackEvents++; afterRollbackKeyEvents += te.Events.Length; } public override void Close() { closeEvent++; } public void ShowTallies() { Util.Log("CSTXListener state: (afterCommitEvents = {0}, afterRollbackEvents = {1}, afterFailedCommitEvents = {2}, afterCommitRegionEvents = {3}, afterRollbackRegionEvents = {4}, afterFailedCommitRegionEvents = {5}, closeEvent = {6})", afterCommitEvents, afterRollbackEvents, afterFailedCommitEvents, afterCommitKeyEvents, afterRollbackKeyEvents, afterFailedCommitKeyEvents, closeEvent); } public int AfterCommitEvents { get { return afterCommitEvents; } } public int AfterRollbackEvents { get { return afterRollbackEvents; } } public int AfterFailedCommitEvents { get { return afterFailedCommitEvents; } } public int AfterCommitKeyEvents { get { return afterCommitKeyEvents; } } public int AfterRollbackKeyEvents { get { return afterRollbackKeyEvents; } } public int AfterFailedCommitKeyEvents { get { return afterFailedCommitKeyEvents; } } public int CloseEvent { get { return closeEvent; } } public bool IncorrectCacheName { get { return incorrectCacheName; } } private int afterCommitEvents = 0; private int afterRollbackEvents = 0; private int afterFailedCommitEvents = 0; private int afterCommitKeyEvents = 0; private int afterRollbackKeyEvents = 0; private int afterFailedCommitKeyEvents = 0; private int closeEvent = 0; private string m_cacheName = null; private bool incorrectCacheName = false; } class CSTXWriter<TKey, TVal> : TransactionWriterAdapter<TKey, TVal> { public CSTXWriter(string cacheName, string instanceName) { m_instanceName = instanceName; m_cacheName = cacheName; } public override void BeforeCommit(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; beforeCommitEvents++; beforeCommitKeyEvents += te.Events.Length; } public int BeforeCommitEvents { get { return beforeCommitEvents; } } public int BeforeCommitKeyEvents { get { return beforeCommitKeyEvents; } } public string InstanceName { get { return m_instanceName; } } public bool IncorrectCacheName { get { return incorrectCacheName; } } public void ShowTallies() { Util.Log("CSTXWriter state: (beforeCommitEvents = {0}, beforeCommitRegionEvents = {1}, instanceName = {2})", beforeCommitEvents, beforeCommitKeyEvents, m_instanceName); } private int beforeCommitEvents = 0; private int beforeCommitKeyEvents = 0; private string m_cacheName = null; private string m_instanceName; private bool incorrectCacheName = false; } */ #endregion [TestFixture] [Category("group1")] [Category("unicast_only")] public class ThinClientCSTX : ThinClientRegionSteps { #region CSTX_COMMENTED - transaction listener and writer are disabled for now /*private CSTXWriter<object, object> m_writer1; private CSTXWriter<object, object> m_writer2; private CSTXListener<object, object> m_listener1; private CSTXListener<object, object> m_listener2;*/ #endregion RegionOperation o_region1; RegionOperation o_region2; private TallyListener<object, object> m_listener; private static string[] cstxRegions = new string[] { "cstx1", "cstx2", "cstx3" }; private UnitProcess m_client1; protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); return new ClientBase[] { m_client1 }; } public void CreateRegion(string regionName, string locators, bool listener) { if (listener) m_listener = new TallyListener<object, object>(); else m_listener = null; Region region = null; region = CacheHelper.CreateTCRegion_Pool<object, object>(regionName, false, false, m_listener, locators, "__TESTPOOL1_", false); } #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* public void ValidateCSTXListenerWriter() { Util.Log("tallies for listener 1"); m_listener1.ShowTallies(); Util.Log("tallies for writer 1"); m_writer1.ShowTallies(); Util.Log("tallies for listener 2"); m_listener2.ShowTallies(); Util.Log("tallies for writer 2"); m_writer2.ShowTallies(); // listener 1 Assert.AreEqual(4, m_listener1.AfterCommitEvents, "Should be 4"); Assert.AreEqual(14, m_listener1.AfterCommitKeyEvents, "Should be 14"); Assert.AreEqual(0, m_listener1.AfterFailedCommitEvents, "Should be 0"); Assert.AreEqual(0, m_listener1.AfterFailedCommitKeyEvents, "Should be 0"); Assert.AreEqual(2, m_listener1.AfterRollbackEvents, "Should be 2"); Assert.AreEqual(6, m_listener1.AfterRollbackKeyEvents, "Should be 6"); Assert.AreEqual(1, m_listener1.CloseEvent, "Should be 1"); Assert.AreEqual(false, m_listener1.IncorrectCacheName, "Incorrect cache name in the events"); // listener 2 Assert.AreEqual(2, m_listener2.AfterCommitEvents, "Should be 2"); Assert.AreEqual(6, m_listener2.AfterCommitKeyEvents, "Should be 6"); Assert.AreEqual(0, m_listener2.AfterFailedCommitEvents, "Should be 0"); Assert.AreEqual(0, m_listener2.AfterFailedCommitKeyEvents, "Should be 0"); Assert.AreEqual(2, m_listener2.AfterRollbackEvents, "Should be 2"); Assert.AreEqual(6, m_listener2.AfterRollbackKeyEvents, "Should be 6"); Assert.AreEqual(1, m_listener2.CloseEvent, "Should be 1"); Assert.AreEqual(false, m_listener2.IncorrectCacheName, "Incorrect cache name in the events"); // writer 1 Assert.AreEqual(3, m_writer1.BeforeCommitEvents, "Should be 3"); Assert.AreEqual(10, m_writer1.BeforeCommitKeyEvents, "Should be 10"); Assert.AreEqual(false, m_writer1.IncorrectCacheName, "Incorrect cache name in the events"); // writer 2 Assert.AreEqual(1, m_writer2.BeforeCommitEvents, "Should be 1"); Assert.AreEqual(4, m_writer2.BeforeCommitKeyEvents, "Should be 4"); Assert.AreEqual(false, m_writer2.IncorrectCacheName, "Incorrect cache name in the events"); } */ #endregion public void ValidateListener() { o_region1 = new RegionOperation(cstxRegions[2]); CacheHelper.CSTXManager.Begin(); o_region1.Region.Put("key3", "value1", null); o_region1.Region.Put("key4", "value2", null); o_region1.Region.Remove("key4"); CacheHelper.CSTXManager.Commit(); // server is conflating the events on the same key hence only 1 create Assert.AreEqual(1, m_listener.Creates, "Should be 1 creates"); Assert.AreEqual(1, m_listener.Destroys, "Should be 1 destroys"); CacheHelper.CSTXManager.Begin(); o_region1.Region.Put("key1", "value1", null); o_region1.Region.Put("key2", "value2", null); o_region1.Region.Invalidate("key1"); o_region1.Region.Invalidate("key3"); CacheHelper.CSTXManager.Commit(); // server is conflating the events on the same key hence only 1 invalidate Assert.AreEqual(3, m_listener.Creates, "Should be 3 creates"); Assert.AreEqual(1, m_listener.Invalidates, "Should be 1 invalidates"); } public void SuspendResumeRollback() { o_region1 = new RegionOperation(cstxRegions[0]); o_region2 = new RegionOperation(cstxRegions[1]); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(1, null); o_region2.PutOp(1, null); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(CacheHelper.CSTXManager.TransactionId), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(CacheHelper.CSTXManager.TransactionId), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); TransactionId tid = CacheHelper.CSTXManager.Suspend(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), true, "Transaction should be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(0, o_region1.Region.Keys.Count, "There should be 0 values in the region after suspend"); Assert.AreEqual(0, o_region2.Region.Keys.Count, "There should be 0 values in the region after suspend"); CacheHelper.CSTXManager.Resume(tid); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); o_region2.PutOp(2, null); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be four values in the region before commit"); Assert.AreEqual(4, o_region2.Region.Keys.Count, "There should be four values in the region before commit"); CacheHelper.CSTXManager.Rollback(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), false, "Transaction should NOT exist"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid), false, "Transaction should not be resumed"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid, TimeSpan.FromMilliseconds(3000)), false, "Transaction should not be resumed"); Assert.AreEqual(0, o_region1.Region.Keys.Count, "There should be 0 values in the region after rollback"); Assert.AreEqual(0, o_region2.Region.Keys.Count, "There should be 0 values in the region after rollback"); bool resumeEx = false; try { CacheHelper.CSTXManager.Resume(tid); } catch (IllegalStateException) { resumeEx = true; } Assert.AreEqual(resumeEx, true, "The transaction should not be resumed"); } public void SuspendResumeInThread() { AutoResetEvent txEvent = new AutoResetEvent(false); AutoResetEvent txIdUpdated = new AutoResetEvent(false); SuspendTransactionThread susObj = new SuspendTransactionThread(false, txEvent, txIdUpdated); Thread susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); ResumeTransactionThread resObj = new ResumeTransactionThread(susObj.Tid, false, false, txEvent); Thread resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); susObj = new SuspendTransactionThread(false, txEvent, txIdUpdated); susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); resObj = new ResumeTransactionThread(susObj.Tid, true, false, txEvent); resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); susObj = new SuspendTransactionThread(true, txEvent, txIdUpdated); susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); resObj = new ResumeTransactionThread(susObj.Tid, false, true, txEvent); resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); susObj = new SuspendTransactionThread(true, txEvent, txIdUpdated); susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); resObj = new ResumeTransactionThread(susObj.Tid, true, true, txEvent); resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); } public void SuspendResumeCommit() { o_region1 = new RegionOperation(cstxRegions[0]); o_region2 = new RegionOperation(cstxRegions[1]); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(1, null); o_region2.PutOp(1, null); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(CacheHelper.CSTXManager.TransactionId), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(CacheHelper.CSTXManager.TransactionId), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); TransactionId tid = CacheHelper.CSTXManager.Suspend(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), true, "Transaction should be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(0, o_region1.Region.Keys.Count, "There should be 0 values in the region after suspend"); Assert.AreEqual(0, o_region2.Region.Keys.Count, "There should be 0 values in the region after suspend"); CacheHelper.CSTXManager.Resume(tid); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid), false, "The transaction should not have been resumed again."); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); o_region2.PutOp(2, null); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be four values in the region before commit"); Assert.AreEqual(4, o_region2.Region.Keys.Count, "There should be four values in the region before commit"); CacheHelper.CSTXManager.Commit(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), false, "Transaction should NOT exist"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid), false, "Transaction should not be resumed"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid, TimeSpan.FromMilliseconds(3000)), false, "Transaction should not be resumed"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be four values in the region after commit"); Assert.AreEqual(4, o_region2.Region.Keys.Count, "There should be four values in the region after commit"); o_region1.DestroyOpWithPdxValue(1, null); o_region2.DestroyOpWithPdxValue(2, null); bool resumeEx = false; try { CacheHelper.CSTXManager.Resume(tid); } catch (IllegalStateException) { resumeEx = true; } Assert.AreEqual(resumeEx, true, "The transaction should not be resumed"); // The transaction should not be suspended // Assert.Throws<Exception>( delegate { CacheHelper.CSTXManager.Suspend(); }); } public void CallOp() { #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* m_writer1 = new CSTXWriter<object, object>(CacheHelper.DCache.Name, "cstxWriter1"); m_writer2 = new CSTXWriter<object, object>(CacheHelper.DCache.Name, "cstxWriter2"); m_listener1 = new CSTXListener<object, object>(CacheHelper.DCache.Name); m_listener2 = new CSTXListener<object, object>(CacheHelper.DCache.Name); CacheHelper.CSTXManager.AddListener<object, object>(m_listener1); CacheHelper.CSTXManager.AddListener<object, object>(m_listener2); CacheHelper.CSTXManager.SetWriter<object, object>(m_writer1); // test two listener one writer for commit on two regions Util.Log(" test two listener one writer for commit on two regions"); */ #endregion CacheHelper.CSTXManager.Begin(); o_region1 = new RegionOperation(cstxRegions[0]); o_region1.PutOp(2, null); o_region2 = new RegionOperation(cstxRegions[1]); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Commit(); //two pdx put as well Assert.AreEqual(2 + 2, o_region1.Region.Keys.Count, "Commit didn't put two values in the region"); Assert.AreEqual(2 + 2, o_region2.Region.Keys.Count, "Commit didn't put two values in the region"); #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* Util.Log(" test two listener one writer for commit on two regions - complete"); ////////////////////////////////// // region test two listener one writer for commit on one region Util.Log(" region test two listener one writer for commit on one region"); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); CacheHelper.CSTXManager.Commit(); Util.Log(" region test two listener one writer for commit on one region - complete"); ////////////////////////////////// // test two listener one writer for rollback on two regions Util.Log(" test two listener one writer for rollback on two regions"); */ #endregion CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Rollback(); //two pdx put as well Assert.AreEqual(2 + 2, o_region1.Region.Keys.Count, "Region has incorrect number of objects"); Assert.AreEqual(2 + 2, o_region2.Region.Keys.Count, "Region has incorrect number of objects"); o_region1.DestroyOpWithPdxValue(2, null); o_region2.DestroyOpWithPdxValue(2, null); #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* Util.Log(" test two listener one writer for rollback on two regions - complete"); ////////////////////////////////// // test two listener one writer for rollback on on region Util.Log(" test two listener one writer for rollback on on region"); CacheHelper.CSTXManager.Begin(); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Rollback(); Util.Log(" test two listener one writer for rollback on on region - complete"); ////////////////////////////////// // test remove listener Util.Log(" test remove listener"); CacheHelper.CSTXManager.RemoveListener<object, object>(m_listener2); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Commit(); Util.Log(" test remove listener - complete" ); ////////////////////////////////// // test GetWriter Util.Log("test GetWriter"); CSTXWriter<object, object> writer = (CSTXWriter<object, object>)CacheHelper.CSTXManager.GetWriter<object, object>(); Assert.AreEqual(writer.InstanceName, m_writer1.InstanceName, "GetWriter is not returning the object set by SetWriter"); Util.Log("test GetWriter - complete"); ////////////////////////////////// // set a different writer Util.Log("set a different writer"); CacheHelper.CSTXManager.SetWriter<object, object>(m_writer2); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Commit(); Util.Log("set a different writer - complete"); ////////////////////////////////// */ #endregion } void runThinClientCSTXTest() { CacheHelper.SetupJavaServers(true, "client_server_transactions.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(CacheHelper.InitClient); Util.Log("Creating two regions in client1"); m_client1.Call(CreateRegion, cstxRegions[0], CacheHelper.Locators, false); m_client1.Call(CreateRegion, cstxRegions[1], CacheHelper.Locators, false); m_client1.Call(CreateRegion, cstxRegions[2], CacheHelper.Locators, true); m_client1.Call(CallOp); m_client1.Call(SuspendResumeCommit); m_client1.Call(SuspendResumeRollback); m_client1.Call(SuspendResumeInThread); m_client1.Call(ValidateListener); #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* m_client1.Call(ValidateCSTXListenerWriter); */ #endregion m_client1.Call(CacheHelper.Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); CacheHelper.ClearLocators(); CacheHelper.ClearEndpoints(); } void runThinClientPersistentTXTest() { CacheHelper.SetupJavaServers(true, "client_server_persistent_transactions.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, "--J=-Dgemfire.ALLOW_PERSISTENT_TRANSACTIONS=true"); Util.Log("Cacheserver 1 started."); m_client1.Call(CacheHelper.InitClient); Util.Log("Creating two regions in client1"); m_client1.Call(CreateRegion, cstxRegions[0], CacheHelper.Locators, false); m_client1.Call(initializePdxSerializer); m_client1.Call(doPutGetWithPdxSerializer); m_client1.Call(CacheHelper.Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); CacheHelper.ClearLocators(); CacheHelper.ClearEndpoints(); } [TearDown] public override void EndTest() { base.EndTest(); } //Successful [Test] public void ThinClientCSTXTest() { runThinClientCSTXTest(); } [Test] public void ThinClientPersistentTXTest() { runThinClientPersistentTXTest(); } public class SuspendTransactionThread { public SuspendTransactionThread(bool sleep, AutoResetEvent txevent, AutoResetEvent txIdUpdated) { m_sleep = sleep; m_txevent = txevent; m_txIdUpdated = txIdUpdated; } public void ThreadStart() { RegionOperation o_region1 = new RegionOperation(cstxRegions[0]); RegionOperation o_region2 = new RegionOperation(cstxRegions[1]); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(1, null); o_region2.PutOp(1, null); m_tid = CacheHelper.CSTXManager.TransactionId; m_txIdUpdated.Set(); if (m_sleep) { m_txevent.WaitOne(); Thread.Sleep(5000); } m_tid = CacheHelper.CSTXManager.Suspend(); } public TransactionId Tid { get { return m_tid; } } private TransactionId m_tid = null; private bool m_sleep = false; private AutoResetEvent m_txevent = null; AutoResetEvent m_txIdUpdated = null; } public class ResumeTransactionThread { public ResumeTransactionThread(TransactionId tid, bool isCommit, bool tryResumeWithSleep, AutoResetEvent txevent) { m_tryResumeWithSleep = tryResumeWithSleep; m_txevent = txevent; m_tid = tid; m_isCommit = isCommit; } public void ThreadStart() { RegionOperation o_region1 = new RegionOperation(cstxRegions[0]); RegionOperation o_region2 = new RegionOperation(cstxRegions[1]); if (m_tryResumeWithSleep) { if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; } else { if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == true, "Transaction should be suspended")) return; } if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == true, "Transaction should exist")) return; if (AssertCheckFail(0 == o_region1.Region.Keys.Count, "There should be 0 values in the region after suspend")) return; if (AssertCheckFail(0 == o_region2.Region.Keys.Count, "There should be 0 values in the region after suspend")) return; if (m_tryResumeWithSleep) { m_txevent.Set(); CacheHelper.CSTXManager.TryResume(m_tid, TimeSpan.FromMilliseconds(30000)); } else CacheHelper.CSTXManager.Resume(m_tid); if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == true, "Transaction should exist")) return; if (AssertCheckFail(o_region1.Region.Keys.Count == 2, "There should be two values in the region after suspend")) return; if (AssertCheckFail(o_region2.Region.Keys.Count == 2, "There should be two values in the region after suspend")) return; o_region2.PutOp(2, null); if (m_isCommit) { CacheHelper.CSTXManager.Commit(); if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == false, "Transaction should NOT exist")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid, TimeSpan.FromMilliseconds(3000)) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(2 == o_region1.Region.Keys.Count, "There should be four values in the region after commit")) return; if (AssertCheckFail(4 == o_region2.Region.Keys.Count, "There should be four values in the region after commit")) return; o_region1.DestroyOpWithPdxValue(1, null); o_region2.DestroyOpWithPdxValue(2, null); } else { CacheHelper.CSTXManager.Rollback(); if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == false, "Transaction should NOT exist")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid, TimeSpan.FromMilliseconds(3000)) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(0 == o_region1.Region.Keys.Count, "There should be 0 values in the region after rollback")) return; if (AssertCheckFail(0 == o_region2.Region.Keys.Count, "There should be 0 values in the region after rollback")) return; } } public bool AssertCheckFail(bool cond, String error) { if (!cond) { m_isFailed = true; m_error = error; return true; } return false; } public TransactionId Tid { get { return m_tid; } } public bool IsFailed { get { return m_isFailed; } } public String Error { get { return m_error; } } private TransactionId m_tid = null; private bool m_tryResumeWithSleep = false; private bool m_isFailed = false; private String m_error; private bool m_isCommit = false; private AutoResetEvent m_txevent = null; } public void initializePdxSerializer() { CacheHelper.DCache.TypeRegistry.PdxSerializer = new PdxSerializer(); } public void doPutGetWithPdxSerializer() { CacheHelper.CSTXManager.Begin(); o_region1 = new RegionOperation(cstxRegions[0]); for (int i = 0; i < 10; i++) { o_region1.Region[i] = i + 1; object ret = o_region1.Region[i]; o_region1.Region[i + 10] = i + 10; ret = o_region1.Region[i + 10]; o_region1.Region[i + 20] = i + 20; ret = o_region1.Region[i + 20]; } CacheHelper.CSTXManager.Commit(); Util.Log("Region keys count after commit for non-pdx keys = {0} ", o_region1.Region.Keys.Count); Assert.AreEqual(30, o_region1.Region.Keys.Count, "Commit didn't put two values in the region"); CacheHelper.CSTXManager.Begin(); o_region1 = new RegionOperation(cstxRegions[0]); for (int i = 100; i < 110; i++) { object put = new SerializePdx1(true); o_region1.Region[i] = put; put = new SerializePdx2(true); o_region1.Region[i + 10] = put; put = new SerializePdx3(true, i % 2); o_region1.Region[i + 20] = put; } CacheHelper.CSTXManager.Commit(); for (int i = 100; i < 110; i++) { object put = new SerializePdx1(true); object ret = o_region1.Region[i]; Assert.AreEqual(put, ret); put = new SerializePdx2(true); ret = o_region1.Region[i + 10]; Assert.AreEqual(put, ret); put = new SerializePdx3(true, i % 2); ret = o_region1.Region[i + 20]; Assert.AreEqual(put, ret); } Util.Log("Region keys count after pdx-keys commit = {0} ", o_region1.Region.Keys.Count); Assert.AreEqual(60, o_region1.Region.Keys.Count, "Commit didn't put two values in the region"); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Resources { /// <summary> /// Operations for managing Resource provider operations. /// </summary> internal partial class ResourceProviderOperationDetailsOperations : IServiceOperations<ResourceManagementClient>, IResourceProviderOperationDetailsOperations { /// <summary> /// Initializes a new instance of the /// ResourceProviderOperationDetailsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ResourceProviderOperationDetailsOperations(ResourceManagementClient client) { this._client = client; } private ResourceManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Resources.ResourceManagementClient. /// </summary> public ResourceManagementClient Client { get { return this._client; } } /// <summary> /// Gets a list of resource providers. /// </summary> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of resource provider operations. /// </returns> public async Task<ResourceProviderOperationDetailListResult> ListAsync(ResourceIdentity identity, CancellationToken cancellationToken) { // Validate if (identity == null) { throw new ArgumentNullException("identity"); } if (identity.ResourceName == null) { throw new ArgumentNullException("identity."); } if (identity.ResourceProviderApiVersion == null) { throw new ArgumentNullException("identity."); } if (identity.ResourceProviderNamespace == null) { throw new ArgumentNullException("identity."); } if (identity.ResourceType == null) { throw new ArgumentNullException("identity."); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("identity", identity); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/providers/"; url = url + Uri.EscapeDataString(identity.ResourceProviderNamespace); url = url + "/operations"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(identity.ResourceProviderApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceProviderOperationDetailListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceProviderOperationDetailListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ResourceProviderOperationDefinition resourceProviderOperationDefinitionInstance = new ResourceProviderOperationDefinition(); result.ResourceProviderOperationDetails.Add(resourceProviderOperationDefinitionInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceProviderOperationDefinitionInstance.Name = nameInstance; } JToken displayValue = valueValue["display"]; if (displayValue != null && displayValue.Type != JTokenType.Null) { ResourceProviderOperationDisplayProperties displayInstance = new ResourceProviderOperationDisplayProperties(); resourceProviderOperationDefinitionInstance.ResourceProviderOperationDisplayProperties = displayInstance; JToken publisherValue = displayValue["publisher"]; if (publisherValue != null && publisherValue.Type != JTokenType.Null) { string publisherInstance = ((string)publisherValue); displayInstance.Publisher = publisherInstance; } JToken providerValue = displayValue["provider"]; if (providerValue != null && providerValue.Type != JTokenType.Null) { string providerInstance = ((string)providerValue); displayInstance.Provider = providerInstance; } JToken resourceValue = displayValue["resource"]; if (resourceValue != null && resourceValue.Type != JTokenType.Null) { string resourceInstance = ((string)resourceValue); displayInstance.Resource = resourceInstance; } JToken operationValue = displayValue["operation"]; if (operationValue != null && operationValue.Type != JTokenType.Null) { string operationInstance = ((string)operationValue); displayInstance.Operation = operationInstance; } JToken descriptionValue = displayValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); displayInstance.Description = descriptionInstance; } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.BraceMatching; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.BraceMatching { public class CSharpBraceMatcherTests : AbstractBraceMatcherTests { protected override Task<TestWorkspace> CreateWorkspaceFromCodeAsync(string code, ParseOptions options) { return TestWorkspace.CreateCSharpAsync(code, options); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestEmptyFile() { var code = @"$$"; var expected = @""; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAtFirstPositionInFile() { var code = @"$$public class C { }"; var expected = @"public class C { }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAtLastPositionInFile() { var code = @"public class C { }$$"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace1() { var code = @"public class C $${ }"; var expected = @"public class C { [|}|]"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace2() { var code = @"public class C {$$ }"; var expected = @"public class C { [|}|]"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace3() { var code = @"public class C { $$}"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace4() { var code = @"public class C { }$$"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen1() { var code = @"public class C { void Foo$$() { } }"; var expected = @"public class C { void Foo([|)|] { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen2() { var code = @"public class C { void Foo($$) { } }"; var expected = @"public class C { void Foo([|)|] { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen3() { var code = @"public class C { void Foo($$ ) { } }"; var expected = @"public class C { void Foo( [|)|] { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen4() { var code = @"public class C { void Foo( $$) { } }"; var expected = @"public class C { void Foo[|(|] ) { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen5() { var code = @"public class C { void Foo( )$$ { } }"; var expected = @"public class C { void Foo[|(|] ) { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen6() { var code = @"public class C { void Foo()$$ { } }"; var expected = @"public class C { void Foo[|(|]) { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket1() { var code = @"public class C { int$$[] i; }"; var expected = @"public class C { int[[|]|] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket2() { var code = @"public class C { int[$$] i; }"; var expected = @"public class C { int[[|]|] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket3() { var code = @"public class C { int[$$ ] i; }"; var expected = @"public class C { int[ [|]|] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket4() { var code = @"public class C { int[ $$] i; }"; var expected = @"public class C { int[|[|] ] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket5() { var code = @"public class C { int[ ]$$ i; }"; var expected = @"public class C { int[|[|] ] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket6() { var code = @"public class C { int[]$$ i; }"; var expected = @"public class C { int[|[|]] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket1() { var code = @"public class C { Foo$$<int> f; }"; var expected = @"public class C { Foo<int[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket2() { var code = @"public class C { Foo<$$int> f; }"; var expected = @"public class C { Foo<int[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket3() { var code = @"public class C { Foo<int$$> f; }"; var expected = @"public class C { Foo[|<|]int> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket4() { var code = @"public class C { Foo<int>$$ f; }"; var expected = @"public class C { Foo[|<|]int> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket1() { var code = @"public class C { Func$$<Func<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int>[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket2() { var code = @"public class C { Func<$$Func<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int>[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket3() { var code = @"public class C { Func<Func$$<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int[|>|]> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket4() { var code = @"public class C { Func<Func<$$int,int>> f; }"; var expected = @"public class C { Func<Func<int,int[|>|]> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket5() { var code = @"public class C { Func<Func<int,int$$>> f; }"; var expected = @"public class C { Func<Func[|<|]int,int>> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket6() { var code = @"public class C { Func<Func<int,int>$$> f; }"; var expected = @"public class C { Func<Func[|<|]int,int>> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket7() { var code = @"public class C { Func<Func<int,int> $$> f; }"; var expected = @"public class C { Func[|<|]Func<int,int> > f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket8() { var code = @"public class C { Func<Func<int,int>>$$ f; }"; var expected = @"public class C { Func[|<|]Func<int,int>> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString1() { var code = @"public class C { string s = $$""Foo""; }"; var expected = @"public class C { string s = ""Foo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString2() { var code = @"public class C { string s = ""$$Foo""; }"; var expected = @"public class C { string s = ""Foo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString3() { var code = @"public class C { string s = ""Foo$$""; }"; var expected = @"public class C { string s = [|""|]Foo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString4() { var code = @"public class C { string s = ""Foo""$$; }"; var expected = @"public class C { string s = [|""|]Foo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString5() { var code = @"public class C { string s = ""Foo$$ "; var expected = @"public class C { string s = ""Foo "; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString1() { var code = @"public class C { string s = $$@""Foo""; }"; var expected = @"public class C { string s = @""Foo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString2() { var code = @"public class C { string s = @$$""Foo""; }"; var expected = @"public class C { string s = @""Foo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString3() { var code = @"public class C { string s = @""$$Foo""; }"; var expected = @"public class C { string s = @""Foo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString4() { var code = @"public class C { string s = @""Foo$$""; }"; var expected = @"public class C { string s = [|@""|]Foo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString5() { var code = @"public class C { string s = @""Foo""$$; }"; var expected = @"public class C { string s = [|@""|]Foo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString1() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""$${x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString2() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{$$x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString3() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x$$}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString4() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}$$, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString5() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, $${y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString6() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {$$y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString7() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y$$}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString8() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}$$""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString9() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString10() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString11() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$@""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString12() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$@""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString13() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@$$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithSingleMatchingDirective() { var code = @" public class C { #if$$ CHK #endif }"; var expected = @" public class C { #if$$ CHK [|#endif|] }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithTwoMatchingDirectives() { var code = @" public class C { #if$$ CHK #else #endif }"; var expected = @" public class C { #if$$ CHK [|#else|] #endif }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithAllMatchingDirectives() { var code = @" public class C { #if CHK #elif RET #else #endif$$ }"; var expected = @" public class C { [|#if|] CHK #elif RET #else #endif }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestRegionDirective() { var code = @" public class C { $$#region test #endregion }"; var expected = @" public class C { #region test [|#endregion|] }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterleavedDirectivesInner() { var code = @" #define CHK public class C { void Test() { #if CHK $$#region test var x = 5; #endregion #else var y = 6; #endif } }"; var expected = @" #define CHK public class C { void Test() { #if CHK #region test var x = 5; [|#endregion|] #else var y = 6; #endif } }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterleavedDirectivesOuter() { var code = @" #define CHK public class C { void Test() { #if$$ CHK #region test var x = 5; #endregion #else var y = 6; #endif } }"; var expected = @" #define CHK public class C { void Test() { #if CHK #region test var x = 5; #endregion [|#else|] var y = 6; #endif } }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedDirective1() { var code = @" public class C { $$#region test }"; var expected = @" public class C { #region test }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedDirective2() { var code = @" #d$$efine CHK public class C { }"; var expected = @" #define CHK public class C { }"; await TestAsync(code, expected); } [WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedConditionalDirective() { var code = @" class Program { static void Main(string[] args) {#if$$ } }"; var expected = @" class Program { static void Main(string[] args) {#if } }"; await TestAsync(code, expected); } [WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedConditionalDirective2() { var code = @" class Program { static void Main(string[] args) {#else$$ } }"; var expected = @" class Program { static void Main(string[] args) {#else } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartTupleDeclaration() { var code = @"public class C { $$(int, int, int, int, int, int, int, int) x; }"; var expected = @"public class C { (int, int, int, int, int, int, int, int[|)|] x; }"; await TestAsync(code, expected, TestOptions.Regular.WithTuplesFeature()); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndTupleDeclaration() { var code = @"public class C { (int, int, int, int, int, int, int, int)$$ x; }"; var expected = @"public class C { [|(|]int, int, int, int, int, int, int, int) x; }"; await TestAsync(code, expected, TestOptions.Regular.WithTuplesFeature()); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartTupleLiteral() { var code = @"public class C { var x = $$(1, 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8[|)|]; }"; await TestAsync(code, expected, TestOptions.Regular.WithTuplesFeature()); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndTupleLiteral() { var code = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8)$$; }"; var expected = @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, 8); }"; await TestAsync(code, expected, TestOptions.Regular.WithTuplesFeature()); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartNestedTupleLiteral() { var code = @"public class C { var x = $$((1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = ((1, 1, 1), 2, 3, 4, 5, 6, 7, 8[|)|]; }"; await TestAsync(code, expected, TestOptions.Regular.WithTuplesFeature()); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartInnerNestedTupleLiteral() { var code = @"public class C { var x = ($$(1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = ((1, 1, 1[|)|], 2, 3, 4, 5, 6, 7, 8); }"; await TestAsync(code, expected, TestOptions.Regular.WithTuplesFeature()); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndNestedTupleLiteral() { var code = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, (8, 8, 8))$$; }"; var expected = @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, (8, 8, 8)); }"; await TestAsync(code, expected, TestOptions.Regular.WithTuplesFeature()); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndInnerNestedTupleLiteral() { var code = @"public class C { var x = ((1, 1, 1)$$, 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = ([|(|]1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; await TestAsync(code, expected, TestOptions.Regular.WithTuplesFeature()); } } }
namespace Nancy.Hosting.Wcf.Tests { using Bootstrapper; using FakeItEasy; using Nancy.Helpers; using Nancy.Tests; using Nancy.Tests.xUnitExtensions; using System; using System.IO; using System.Linq; using System.Net; using System.ServiceModel; using System.ServiceModel.Web; using System.Threading; using Bootstrapper; using FakeItEasy; using Nancy.Tests; using Nancy.Tests.xUnitExtensions; using Xunit; /// <remarks> /// These tests attempt to listen on port 56297, and so require either administrative /// privileges or that a command similar to the following has been run with /// administrative privileges: /// <code>netsh http add urlacl url=http://+:56297/base user=DOMAIN\user</code> /// See http://msdn.microsoft.com/en-us/library/ms733768.aspx for more information. /// </remarks> public class NancyWcfGenericServiceFixture { private static readonly Uri BaseUri = new Uri("http://localhost:56297/base/"); [SkippableFact] public void Should_be_able_to_get_any_header_from_selfhost() { // Given using (CreateAndOpenWebServiceHost()) { var request = WebRequest.Create(new Uri(BaseUri, "rel/header/?query=value")); request.Method = "GET"; // When var header = request.GetResponse().Headers["X-Some-Header"]; // Then header.ShouldEqual("Some value"); } } [SkippableFact] public void Should_set_query_string_and_uri_correctly() { // Given Request nancyRequest = null; var fakeEngine = A.Fake<INancyEngine>(); A.CallTo(() => fakeEngine.HandleRequest(A<Request>.Ignored, A<Func<NancyContext, NancyContext>>.Ignored, A<CancellationToken>.Ignored)) .Invokes(f => nancyRequest = (Request)f.Arguments[0]) .Returns(TaskHelpers.GetCompletedTask(new NancyContext())); var fakeBootstrapper = A.Fake<INancyBootstrapper>(); A.CallTo(() => fakeBootstrapper.GetEngine()).Returns(fakeEngine); // When using (CreateAndOpenWebServiceHost(fakeBootstrapper)) { var request = WebRequest.Create(new Uri(BaseUri, "test/stuff?query=value&query2=value2")); request.Method = "GET"; try { request.GetResponse(); } catch (WebException) { // Will throw because it returns 404 - don't care. } } // Then nancyRequest.Path.ShouldEqual("/test/stuff"); Assert.True(nancyRequest.Query.query.HasValue); Assert.True(nancyRequest.Query.query2.HasValue); } [SkippableFact] public void Should_set_path_and_url_correctly_without_trailing_slash() { // Given Request nancyRequest = null; var fakeEngine = A.Fake<INancyEngine>(); A.CallTo(() => fakeEngine.HandleRequest(A<Request>.Ignored, A<Func<NancyContext, NancyContext>>.Ignored, A<CancellationToken>.Ignored)) .Invokes(f => nancyRequest = (Request)f.Arguments[0]) .Returns(TaskHelpers.GetCompletedTask(new NancyContext())); var fakeBootstrapper = A.Fake<INancyBootstrapper>(); A.CallTo(() => fakeBootstrapper.GetEngine()).Returns(fakeEngine); var baseUriWithoutTrailingSlash = new Uri("http://localhost:56297/base"); // When using(CreateAndOpenWebServiceHost(fakeBootstrapper, baseUriWithoutTrailingSlash)) { var request = WebRequest.Create(new Uri(BaseUri, "test/stuff")); request.Method = "GET"; try { request.GetResponse(); } catch(WebException) { // Will throw because it returns 404 - don't care. } } // Then nancyRequest.Path.ShouldEqual("/test/stuff"); nancyRequest.Url.ToString().ShouldEqual("http://localhost:56297/base/test/stuff"); } [SkippableFact] public void Should_be_able_to_get_from_selfhost() { // Given using (CreateAndOpenWebServiceHost()) { var reader = new StreamReader(WebRequest.Create(new Uri(BaseUri, "rel")).GetResponse().GetResponseStream()); // When var response = reader.ReadToEnd(); // Then response.ShouldEqual("This is the site route"); } } [SkippableFact] public void Should_be_able_to_post_body_to_selfhost() { // Given using (CreateAndOpenWebServiceHost()) { const string testBody = "This is the body of the request"; var request = WebRequest.Create(new Uri(BaseUri, "rel")); request.Method = "POST"; var writer = new StreamWriter(request.GetRequestStream()) {AutoFlush = true}; writer.Write(testBody); // When var responseBody = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd(); // Then responseBody.ShouldEqual(testBody); } } [SkippableFact] public void Should_nancyrequest_contain_hostname_port_and_scheme() { // Given Request nancyRequest = null; var fakeEngine = A.Fake<INancyEngine>(); var fakeBootstrapper = A.Fake<INancyBootstrapper>(); A.CallTo(() => fakeEngine.HandleRequest(A<Request>.Ignored, A<Func<NancyContext, NancyContext>>.Ignored, A<CancellationToken>.Ignored)) .Invokes(f => nancyRequest = (Request)f.Arguments[0]) .Returns(TaskHelpers.GetCompletedTask(new NancyContext())); A.CallTo(() => fakeBootstrapper.GetEngine()).Returns(fakeEngine); // When using (CreateAndOpenWebServiceHost(fakeBootstrapper)) { var request = WebRequest.Create(BaseUri); request.Method = "GET"; try { request.GetResponse(); } catch (WebException) { // Will throw because it returns 404 - don't care. } } // Then Assert.Equal(56297, nancyRequest.Url.Port); Assert.Equal("localhost", nancyRequest.Url.HostName); Assert.Equal("http", nancyRequest.Url.Scheme); } [SkippableFact] public void Should_not_have_content_type_header_for_not_modified_responses() { // Given Request nancyRequest = null; var fakeEngine = A.Fake<INancyEngine>(); var fakeBootstrapper = A.Fake<INancyBootstrapper>(); var fakeNotModifiedResponse = A.Fake<Response>(); // Context sends back a 304 Not Modified var context = new NancyContext(); context.Response = new Response() { ContentType = null, StatusCode = Nancy.HttpStatusCode.NotModified }; A.CallTo(() => fakeEngine.HandleRequest(A<Request>.Ignored, A<Func<NancyContext, NancyContext>>.Ignored, A<CancellationToken>.Ignored)) .Invokes(f => nancyRequest = (Request)f.Arguments[0]) .Returns(TaskHelpers.GetCompletedTask(new NancyContext())); A.CallTo(() => fakeBootstrapper.GetEngine()).Returns(fakeEngine); // When a request is made and responded to with a status of 304 Not Modified System.Net.WebResponse response = null; using (CreateAndOpenWebServiceHost(fakeBootstrapper)) { var request = WebRequest.Create(new Uri(BaseUri, "notmodified")); request.Method = "GET"; try { request.GetResponse(); } catch (WebException notModifiedEx) { // Will throw because it returns 304 response = notModifiedEx.Response; } } // Then Assert.NotNull(response); Assert.False(response.Headers.AllKeys.Any(header => header == "Content-Type")); } private static WebServiceHost CreateAndOpenWebServiceHost(INancyBootstrapper nancyBootstrapper = null, Uri baseUri = null) { if (nancyBootstrapper == null) { nancyBootstrapper = new DefaultNancyBootstrapper(); } var host = new WebServiceHost( new NancyWcfGenericService(nancyBootstrapper), baseUri ?? BaseUri); host.AddServiceEndpoint(typeof (NancyWcfGenericService), new WebHttpBinding(), ""); try { host.Open(); } catch (System.ServiceModel.AddressAccessDeniedException) { throw new SkipException("Skipped due to no Administrator access - please see test fixture for more information."); } return host; } } }
#region MIT License /* * Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.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. */ #endregion #if UseDouble using Scalar = System.Double; #else using Scalar = System.Single; #endif using System; using System.Runtime.InteropServices; using AdvanceMath; using AdvanceMath.Geometry2D; using Physics2DDotNet; using Physics2DDotNet.Shapes; using Tao.OpenGl; using SdlDotNet.Graphics; using Color = System.Drawing.Color; namespace Graphics2DDotNet { public class Light { public Vector3D Position; } public class BumpmapSpriteDrawable : BufferedDrawable { public static Surface Createbumpmap(Surface original,Vector2D offset, IShape shape, Scalar depthToCenter) { int width = original.Width; int height = original.Height; //Color[,] colors = new Color[width, height]; Vector3D mid = new Vector3D(128,128,128); Vector3D min = Vector3D.Zero; Vector3D max = new Vector3D(255,255,255); Surface result = new Surface(width, height,32,true); for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { Vector2D point = new Vector2D(x, y) - offset; IntersectionInfo info; Vector3D normal; if (shape.TryGetIntersection(point, out info)) { Scalar va = Math.Abs(info.Distance / depthToCenter); if (va < 1) { Vector3D temp = new Vector3D(info.Normal.X, info.Normal.Y, .1f); temp = Vector3D.Lerp(temp, Vector3D.ZAxis, va); normal = temp.Normalized; } else { normal = Vector3D.ZAxis; } } else { normal = Vector3D.ZAxis; } normal = Vector3D.Clamp(mid + (normal * 128), min, max); result.Draw( new System.Drawing.Point(x, y), Color.FromArgb(255, (int)normal.X, (int)normal.Y, (int)normal.Z)); // colors[x, y] = Color.FromArgb(255,(int)normal.X, (int)normal.Y, (int)normal.Z); } } // result.SetPixels(new System.Drawing.Point(), colors); return result; } bool yInverted; bool xInverted; static Scalar[] GlMatrix = new Scalar[16]; Light light; ARBArrayBuffer<Vector2D> vertexes; ARBArrayBuffer<Vector2D> coordinates; Texture2D bumpmap, sprite; int size; int normalization_cube_map; public BumpmapSpriteDrawable( Surface surface, Surface bumpmap, Vector2D[] vertexes, Vector2D[] coordinates, bool flip, bool xInverted, bool yInverted, Light light) { this.light = light; this.size = Math.Max(surface.Width, surface.Height); this.xInverted = xInverted; if (flip) { this.yInverted = !yInverted; } else { this.yInverted = yInverted; } this.vertexes = new ARBArrayBuffer<Vector2D>(vertexes, Vector2D.Size); this.coordinates = new ARBArrayBuffer<Vector2D>(coordinates, Vector2D.Size); this.bumpmap = new Texture2D(bumpmap, flip, new TextureOptions()); this.sprite = new Texture2D(surface, flip, new TextureOptions()); } ~BumpmapSpriteDrawable() { Dispose(false); } protected override void EnableState() { Gl.glPushAttrib(unchecked((int)0xffffffff)); Gl.glEnableClientState(Gl.GL_VERTEX_ARRAY); Gl.glEnableClientState(Gl.GL_TEXTURE_COORD_ARRAY); Gl.glEnable(Gl.GL_BLEND); Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA); } protected override void DisableState() { Gl.glDisable(Gl.GL_BLEND); Gl.glDisableClientState(Gl.GL_TEXTURE_COORD_ARRAY); Gl.glDisableClientState(Gl.GL_VERTEX_ARRAY); Gl.glPopAttrib(); } protected override void BufferData(int refresh) { normalization_cube_map = TextureHelper.GenNormalizationCubeMap(size); bumpmap.Buffer(refresh); sprite.Buffer(refresh); vertexes.Buffer(refresh); coordinates.Buffer(refresh); } protected override void DrawData(DrawInfo drawInfo, IDrawableState state) { // Set The First Texture Unit To Normalize Our Vector From The Surface To The Light. // Set The Texture Environment Of The First Texture Unit To Replace It With The // Sampled Value Of The Normalization Cube Map. Gl.glEnableClientState(Gl.GL_VERTEX_ARRAY); vertexes.Bind(); //Gl.glBindBufferARB(Gl.GL_ARRAY_BUFFER_ARB, vertexName); Gl.glVertexPointer(Vector2D.Count, GlHelper.GlScalar, 0, IntPtr.Zero); Gl.glActiveTextureARB(Gl.GL_TEXTURE0_ARB); Gl.glClientActiveTexture(Gl.GL_TEXTURE0_ARB); Gl.glEnable(Gl.GL_TEXTURE_CUBE_MAP); Gl.glBindTexture(Gl.GL_TEXTURE_CUBE_MAP, normalization_cube_map); Gl.glTexEnvi(Gl.GL_TEXTURE_ENV, Gl.GL_TEXTURE_ENV_MODE, Gl.GL_COMBINE); Gl.glTexEnvi(Gl.GL_TEXTURE_ENV, Gl.GL_COMBINE_RGB, Gl.GL_REPLACE); Gl.glTexEnvi(Gl.GL_TEXTURE_ENV, Gl.GL_SOURCE0_RGB, Gl.GL_TEXTURE); Gl.glEnableClientState(Gl.GL_TEXTURE_COORD_ARRAY); vertexes.Bind(); //Gl.glBindBufferARB(Gl.GL_ARRAY_BUFFER_ARB, vertexName); Gl.glTexCoordPointer(Vector2D.Count, GlHelper.GlScalar, 0, IntPtr.Zero); //now we change the textures origin to that of the light's position GlHelper.GlGetModelViewMatrix(GlMatrix); Matrix4x4 matrix; Matrix4x4.CopyTranspose(GlMatrix, out matrix); Matrix4x4.Invert(ref matrix, out matrix); Vector3D lightPos; Vector3D.Transform(ref matrix, ref light.Position, out lightPos); Gl.glMatrixMode(Gl.GL_TEXTURE); Gl.glLoadIdentity(); GlHelper.GlScale(-1, -1, -1); GlHelper.GlTranslate( (xInverted) ? (lightPos.X) : (-lightPos.X), (yInverted) ? (lightPos.Y) : (-lightPos.Y), -lightPos.Z); // Set The Second Unit To The Bump Map. // Set The Texture Environment Of The Second Texture Unit To Perform A Dot3 // Operation With The Value Of The Previous Texture Unit (The Normalized // Vector Form The Surface To The Light) And The Sampled Texture Value (The // Normalized Normal Vector Of Our Bump Map). Gl.glActiveTextureARB(Gl.GL_TEXTURE1_ARB); Gl.glClientActiveTexture(Gl.GL_TEXTURE1_ARB); Gl.glEnable(Gl.GL_TEXTURE_2D); bumpmap.Bind(); Gl.glTexEnvi(Gl.GL_TEXTURE_ENV, Gl.GL_TEXTURE_ENV_MODE, Gl.GL_COMBINE); Gl.glTexEnvi(Gl.GL_TEXTURE_ENV, Gl.GL_COMBINE_RGB, Gl.GL_DOT3_RGB); Gl.glTexEnvi(Gl.GL_TEXTURE_ENV, Gl.GL_SOURCE0_RGB, Gl.GL_PREVIOUS); Gl.glTexEnvi(Gl.GL_TEXTURE_ENV, Gl.GL_SOURCE1_RGB, Gl.GL_TEXTURE); Gl.glEnableClientState(Gl.GL_TEXTURE_COORD_ARRAY); coordinates.Bind(); Gl.glTexCoordPointer(Vector2D.Count, GlHelper.GlScalar, 0, IntPtr.Zero); // Set The Third Texture Unit To Our Texture. // Set The Texture Environment Of The Third Texture Unit To Modulate // (Multiply) The Result Of Our Dot3 Operation With The Texture Value. Gl.glActiveTextureARB(Gl.GL_TEXTURE2_ARB); Gl.glClientActiveTexture(Gl.GL_TEXTURE2_ARB); Gl.glEnable(Gl.GL_TEXTURE_2D); sprite.Bind(); Gl.glTexEnvi(Gl.GL_TEXTURE_ENV, Gl.GL_TEXTURE_ENV_MODE, Gl.GL_MODULATE); Gl.glEnableClientState(Gl.GL_TEXTURE_COORD_ARRAY); coordinates.Bind(); Gl.glTexCoordPointer(Vector2D.Count, GlHelper.GlScalar, 0, IntPtr.Zero); //THEN YOU DRAW IT! MUAHHAAHA IT WORKS! it finally works! Gl.glDrawArrays(Gl.GL_QUADS, 0, 4); Gl.glDisable(Gl.GL_TEXTURE_2D); Gl.glDisableClientState(Gl.GL_TEXTURE_COORD_ARRAY); Gl.glActiveTextureARB(Gl.GL_TEXTURE1_ARB); Gl.glClientActiveTexture(Gl.GL_TEXTURE1_ARB); Gl.glDisable(Gl.GL_TEXTURE_2D); Gl.glDisableClientState(Gl.GL_TEXTURE_COORD_ARRAY); Gl.glActiveTextureARB(Gl.GL_TEXTURE0_ARB); Gl.glClientActiveTexture(Gl.GL_TEXTURE0_ARB); Gl.glDisable(Gl.GL_TEXTURE_CUBE_MAP); Gl.glDisableClientState(Gl.GL_TEXTURE_COORD_ARRAY); Gl.glDisableClientState(Gl.GL_VERTEX_ARRAY); Gl.glLoadIdentity(); Gl.glMatrixMode(Gl.GL_MODELVIEW); } public override IDrawableState CreateState() { return null; } protected override void Dispose(bool disposing) { if (disposing) { vertexes.Dispose(); coordinates.Dispose(); sprite.Dispose(); bumpmap.Dispose(); } GlHelper.GlDeleteTextures(LastRefresh, new int[] { normalization_cube_map }); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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 DiscUtils.Streams; namespace DiscUtils.Ext { internal class SuperBlock : IByteArraySerializable { public const ushort Ext2Magic = 0xEF53; /// <summary> /// Old revision, not supported by DiscUtils. /// </summary> public const uint OldRevision = 0; public ushort BlockGroupNumber; public uint BlocksCount; public uint BlocksCountHigh; public uint BlocksPerGroup; public uint CheckInterval; public CompatibleFeatures CompatibleFeatures; public uint CompressionAlgorithmUsageBitmap; public uint CreatorOS; public byte DefaultHashVersion; public uint DefaultMountOptions; public ushort DefaultReservedBlockGid; public ushort DefaultReservedBlockUid; public ushort DescriptorSize; public byte DirPreallocateBlockCount; public uint ReservedGDTBlocks; public ushort Errors; public uint FirstDataBlock; public uint FirstInode; public uint FirstMetablockBlockGroup; public uint Flags; public uint FragsPerGroup; public uint FreeBlocksCount; public uint FreeBlocksCountHigh; public uint FreeInodesCount; public uint[] HashSeed; public IncompatibleFeatures IncompatibleFeatures; public uint InodesCount; public ushort InodeSize; public uint InodesPerGroup; public uint[] JournalBackup; public uint JournalDevice; public uint JournalInode; public Guid JournalSuperBlockUniqueId; public uint LastCheckTime; public string LastMountPoint; public uint LastOrphan; public uint LogBlockSize; public uint LogFragSize; public byte LogGroupsPerFlex; public uint OverheadBlocksCount; public ushort Magic; public ushort MaxMountCount; public ushort MinimumExtraInodeSize; public ushort MinorRevisionLevel; public uint MkfsTime; public ushort MountCount; public uint MountTime; public ulong MultiMountProtectionBlock; public ushort MultiMountProtectionInterval; public byte PreallocateBlockCount; public ushort RaidStride; public uint RaidStripeWidth; public ReadOnlyCompatibleFeatures ReadOnlyCompatibleFeatures; public uint ReservedBlocksCount; public uint ReservedBlocksCountHigh; public uint RevisionLevel; public ushort State; public Guid UniqueId; public string VolumeName; public ushort WantExtraInodeSize; public uint WriteTime; public bool Has64Bit { get { return (IncompatibleFeatures & IncompatibleFeatures.SixtyFourBit) == IncompatibleFeatures.SixtyFourBit && DescriptorSize == 8; } } public uint BlockSize { get { return (uint)(1024 << (int)LogBlockSize); } } public int Size { get { return 1024; } } public int ReadFrom(byte[] buffer, int offset) { InodesCount = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0); BlocksCount = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 4); ReservedBlocksCount = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 8); FreeBlocksCount = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 12); FreeInodesCount = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 16); FirstDataBlock = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 20); LogBlockSize = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 24); LogFragSize = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 28); BlocksPerGroup = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 32); FragsPerGroup = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 36); InodesPerGroup = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 40); MountTime = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 44); WriteTime = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 48); MountCount = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 52); MaxMountCount = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 54); Magic = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 56); State = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 58); Errors = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 60); MinorRevisionLevel = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 62); LastCheckTime = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 64); CheckInterval = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 68); CreatorOS = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 72); RevisionLevel = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 76); DefaultReservedBlockUid = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 80); DefaultReservedBlockGid = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 82); FirstInode = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 84); InodeSize = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 88); BlockGroupNumber = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 90); CompatibleFeatures = (CompatibleFeatures)EndianUtilities.ToUInt32LittleEndian(buffer, offset + 92); IncompatibleFeatures = (IncompatibleFeatures)EndianUtilities.ToUInt32LittleEndian(buffer, offset + 96); ReadOnlyCompatibleFeatures = (ReadOnlyCompatibleFeatures)EndianUtilities.ToUInt32LittleEndian(buffer, offset + 100); UniqueId = EndianUtilities.ToGuidLittleEndian(buffer, offset + 104); VolumeName = EndianUtilities.BytesToZString(buffer, offset + 120, 16); LastMountPoint = EndianUtilities.BytesToZString(buffer, offset + 136, 64); CompressionAlgorithmUsageBitmap = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 200); PreallocateBlockCount = buffer[offset + 204]; DirPreallocateBlockCount = buffer[offset + 205]; ReservedGDTBlocks = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 206); JournalSuperBlockUniqueId = EndianUtilities.ToGuidLittleEndian(buffer, offset + 208); JournalInode = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 224); JournalDevice = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 228); LastOrphan = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 232); HashSeed = new uint[4]; HashSeed[0] = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 236); HashSeed[1] = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 240); HashSeed[2] = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 244); HashSeed[3] = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 248); DefaultHashVersion = buffer[offset + 252]; DescriptorSize = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 254); DefaultMountOptions = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 256); FirstMetablockBlockGroup = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 260); MkfsTime = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 264); JournalBackup = new uint[17]; for (int i = 0; i < 17; ++i) { JournalBackup[i] = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 268 + 4 * i); } BlocksCountHigh = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 336); ReservedBlocksCountHigh = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 340); FreeBlocksCountHigh = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 344); MinimumExtraInodeSize = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 348); WantExtraInodeSize = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 350); Flags = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 352); RaidStride = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 356); MultiMountProtectionInterval = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 358); MultiMountProtectionBlock = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 360); RaidStripeWidth = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 368); LogGroupsPerFlex = buffer[offset + 372]; OverheadBlocksCount = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 584); return 1024; } public void WriteTo(byte[] buffer, int offset) { throw new NotImplementedException(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Automation.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Automation; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Definition of the runbook type. /// </summary> [Rest.Serialization.JsonTransformation] public partial class Runbook : Resource { /// <summary> /// Initializes a new instance of the Runbook class. /// </summary> public Runbook() { CustomInit(); } /// <summary> /// Initializes a new instance of the Runbook class. /// </summary> /// <param name="location">Resource location</param> /// <param name="id">Resource Id</param> /// <param name="name">Resource name</param> /// <param name="type">Resource type</param> /// <param name="tags">Resource tags</param> /// <param name="runbookType">Gets or sets the type of the runbook. /// Possible values include: 'Script', 'Graph', 'PowerShellWorkflow', /// 'PowerShell', 'GraphPowerShellWorkflow', 'GraphPowerShell'</param> /// <param name="publishContentLink">Gets or sets the published runbook /// content link.</param> /// <param name="state">Gets or sets the state of the runbook. Possible /// values include: 'New', 'Edit', 'Published'</param> /// <param name="logVerbose">Gets or sets verbose log option.</param> /// <param name="logProgress">Gets or sets progress log option.</param> /// <param name="logActivityTrace">Gets or sets the option to log /// activity trace of the runbook.</param> /// <param name="jobCount">Gets or sets the job count of the /// runbook.</param> /// <param name="parameters">Gets or sets the runbook /// parameters.</param> /// <param name="outputTypes">Gets or sets the runbook output /// types.</param> /// <param name="draft">Gets or sets the draft runbook /// properties.</param> /// <param name="provisioningState">Gets or sets the provisioning state /// of the runbook. Possible values include: 'Succeeded'</param> /// <param name="lastModifiedBy">Gets or sets the last modified /// by.</param> /// <param name="creationTime">Gets or sets the creation time.</param> /// <param name="lastModifiedTime">Gets or sets the last modified /// time.</param> /// <param name="description">Gets or sets the description.</param> /// <param name="etag">Gets or sets the etag of the resource.</param> public Runbook(string location, string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string runbookType = default(string), ContentLink publishContentLink = default(ContentLink), string state = default(string), bool? logVerbose = default(bool?), bool? logProgress = default(bool?), int? logActivityTrace = default(int?), int? jobCount = default(int?), IDictionary<string, RunbookParameter> parameters = default(IDictionary<string, RunbookParameter>), IList<string> outputTypes = default(IList<string>), RunbookDraft draft = default(RunbookDraft), RunbookProvisioningState? provisioningState = default(RunbookProvisioningState?), string lastModifiedBy = default(string), System.DateTime? creationTime = default(System.DateTime?), System.DateTime? lastModifiedTime = default(System.DateTime?), string description = default(string), string etag = default(string)) : base(location, id, name, type, tags) { RunbookType = runbookType; PublishContentLink = publishContentLink; State = state; LogVerbose = logVerbose; LogProgress = logProgress; LogActivityTrace = logActivityTrace; JobCount = jobCount; Parameters = parameters; OutputTypes = outputTypes; Draft = draft; ProvisioningState = provisioningState; LastModifiedBy = lastModifiedBy; CreationTime = creationTime; LastModifiedTime = lastModifiedTime; Description = description; Etag = etag; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the type of the runbook. Possible values include: /// 'Script', 'Graph', 'PowerShellWorkflow', 'PowerShell', /// 'GraphPowerShellWorkflow', 'GraphPowerShell' /// </summary> [JsonProperty(PropertyName = "properties.runbookType")] public string RunbookType { get; set; } /// <summary> /// Gets or sets the published runbook content link. /// </summary> [JsonProperty(PropertyName = "properties.publishContentLink")] public ContentLink PublishContentLink { get; set; } /// <summary> /// Gets or sets the state of the runbook. Possible values include: /// 'New', 'Edit', 'Published' /// </summary> [JsonProperty(PropertyName = "properties.state")] public string State { get; set; } /// <summary> /// Gets or sets verbose log option. /// </summary> [JsonProperty(PropertyName = "properties.logVerbose")] public bool? LogVerbose { get; set; } /// <summary> /// Gets or sets progress log option. /// </summary> [JsonProperty(PropertyName = "properties.logProgress")] public bool? LogProgress { get; set; } /// <summary> /// Gets or sets the option to log activity trace of the runbook. /// </summary> [JsonProperty(PropertyName = "properties.logActivityTrace")] public int? LogActivityTrace { get; set; } /// <summary> /// Gets or sets the job count of the runbook. /// </summary> [JsonProperty(PropertyName = "properties.jobCount")] public int? JobCount { get; set; } /// <summary> /// Gets or sets the runbook parameters. /// </summary> [JsonProperty(PropertyName = "properties.parameters")] public IDictionary<string, RunbookParameter> Parameters { get; set; } /// <summary> /// Gets or sets the runbook output types. /// </summary> [JsonProperty(PropertyName = "properties.outputTypes")] public IList<string> OutputTypes { get; set; } /// <summary> /// Gets or sets the draft runbook properties. /// </summary> [JsonProperty(PropertyName = "properties.draft")] public RunbookDraft Draft { get; set; } /// <summary> /// Gets or sets the provisioning state of the runbook. Possible values /// include: 'Succeeded' /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public RunbookProvisioningState? ProvisioningState { get; set; } /// <summary> /// Gets or sets the last modified by. /// </summary> [JsonProperty(PropertyName = "properties.lastModifiedBy")] public string LastModifiedBy { get; set; } /// <summary> /// Gets or sets the creation time. /// </summary> [JsonProperty(PropertyName = "properties.creationTime")] public System.DateTime? CreationTime { get; set; } /// <summary> /// Gets or sets the last modified time. /// </summary> [JsonProperty(PropertyName = "properties.lastModifiedTime")] public System.DateTime? LastModifiedTime { get; set; } /// <summary> /// Gets or sets the description. /// </summary> [JsonProperty(PropertyName = "properties.description")] public string Description { get; set; } /// <summary> /// Gets or sets the etag of the resource. /// </summary> [JsonProperty(PropertyName = "etag")] public string Etag { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public override void Validate() { base.Validate(); if (PublishContentLink != null) { PublishContentLink.Validate(); } if (Draft != null) { Draft.Validate(); } } } }
namespace Nancy.ViewEngines.SuperSimpleViewEngine { using Microsoft.CSharp.RuntimeBinder; using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Text; /// <summary> /// A super-simple view engine /// </summary> public class SuperSimpleViewEngine { /// <summary> /// Compiled Regex for viewbag substitutions /// </summary> private static readonly Regex ViewBagSubstitutionsRegEx = new Regex(@"@(?<Encode>!)?ViewBag(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?", RegexOptions.Compiled); /// <summary> /// Compiled Regex for single substitutions /// </summary> private static readonly Regex SingleSubstitutionsRegEx = new Regex(@"@(?<Encode>!)?Model(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?", RegexOptions.Compiled); /// <summary> /// Compiled Regex for context subsituations /// </summary> private static readonly Regex ContextSubstitutionsRegEx = new Regex(@"@(?<Encode>!)?Context(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?", RegexOptions.Compiled); /// <summary> /// Compiled Regex for each blocks /// </summary> private static readonly Regex EachSubstitutionRegEx = new Regex(@"@Each(?:\.(?<ModelSource>(Model|Context)+))?(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?(?<Contents>.*?)@EndEach;?", RegexOptions.Compiled | RegexOptions.Singleline); /// <summary> /// Compiled Regex for each block current substitutions /// </summary> private static readonly Regex EachItemSubstitutionRegEx = new Regex(@"@(?<Encode>!)?Current(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?", RegexOptions.Compiled); /// <summary> /// Compiled Regex for if blocks /// </summary> private static readonly Regex ConditionalSubstitutionRegEx = new Regex(@"@If(?<Not>Not)?(?<Null>Null)?(?:\.(?<ModelSource>(Model|Context)+))?(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))+;?(?<Contents>.*?)@EndIf;?", RegexOptions.Compiled | RegexOptions.Singleline); /// <summary> /// Compiled regex for partial blocks /// </summary> private static readonly Regex PartialSubstitutionRegEx = new Regex(@"@Partial\['(?<ViewName>[^\]]+)'(?:.[ ]?@?(?<Model>(Model|Current)(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*))?\];?", RegexOptions.Compiled); /// <summary> /// Compiled RegEx for section block declarations /// </summary> private static readonly Regex SectionDeclarationRegEx = new Regex(@"@Section\[\'(?<SectionName>.+?)\'\];?", RegexOptions.Compiled); /// <summary> /// Compiled RegEx for section block contents /// </summary> private static readonly Regex SectionContentsRegEx = new Regex(@"(?:@Section\[\'(?<SectionName>.+?)\'\];?(?<SectionContents>.*?)@EndSection;?)", RegexOptions.Compiled | RegexOptions.Singleline); /// <summary> /// Compiled RegEx for master page declaration /// </summary> private static readonly Regex MasterPageHeaderRegEx = new Regex(@"^(?:@Master\[\'(?<MasterPage>.+?)\'\]);?", RegexOptions.Compiled); /// <summary> /// Compiled RegEx for path expansion /// </summary> private static readonly Regex PathExpansionRegEx = new Regex(@"(?:@Path\[\'(?<Path>.+?)\'\]);?", RegexOptions.Compiled); /// <summary> /// Compiled RegEx for path expansion in attribute values /// </summary> private static readonly Regex AttributeValuePathExpansionRegEx = new Regex(@"(?<Attribute>[a-zA-Z]+)=(?<Quote>[""'])(?<Path>~.+?)\k<Quote>", RegexOptions.Compiled); /// <summary> /// Compiled RegEx for the CSRF anti forgery token /// </summary> private static readonly Regex AntiForgeryTokenRegEx = new Regex(@"@AntiForgeryToken;?", RegexOptions.Compiled); /// <summary> /// View engine transform processors /// </summary> private readonly List<Func<string, object, IViewEngineHost, string>> processors; /// <summary> /// View engine extensions /// </summary> private readonly IEnumerable<ISuperSimpleViewEngineMatcher> matchers; /// <summary> /// Initializes a new instance of the <see cref="SuperSimpleViewEngine"/> class. /// </summary> public SuperSimpleViewEngine() : this(Enumerable.Empty<ISuperSimpleViewEngineMatcher>()) { } /// <summary> /// Initializes a new instance of the <see cref="SuperSimpleViewEngine"/> class, using /// the provided <see cref="ISuperSimpleViewEngineMatcher"/> extensions. /// </summary> /// <param name="matchers">The matchers to use with the engine.</param> public SuperSimpleViewEngine(IEnumerable<ISuperSimpleViewEngineMatcher> matchers) { this.matchers = matchers ?? Enumerable.Empty<ISuperSimpleViewEngineMatcher>(); this.processors = new List<Func<string, object, IViewEngineHost, string>> { PerformViewBagSubstitutions, PerformSingleSubstitutions, PerformContextSubstitutions, PerformEachSubstitutions, PerformConditionalSubstitutions, PerformPathSubstitutions, PerformAntiForgeryTokenSubstitutions, this.PerformPartialSubstitutions, this.PerformMasterPageSubstitutions, }; } /// <summary> /// Renders a template /// </summary> /// <param name="template">The template to render.</param> /// <param name="model">The model to user for rendering.</param> /// <param name="host">The view engine host</param> /// <returns>A string containing the expanded template.</returns> public string Render(string template, dynamic model, IViewEngineHost host) { var output = this.processors.Aggregate(template, (current, processor) => processor(current, model ?? new object(), host)); return this.matchers.Aggregate(output, (current, extension) => extension.Invoke(current, model, host)); } /// <summary> /// <para> /// Gets a property value from the given model. /// </para> /// <para> /// Anonymous types, standard types and ExpandoObject are supported. /// Arbitrary dynamics (implementing IDynamicMetaObjectProvider) are not, unless /// they also implement IDictionary string, object for accessing properties. /// </para> /// </summary> /// <param name="model">The model.</param> /// <param name="propertyName">The property name to evaluate.</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns> /// <exception cref="ArgumentException">Model type is not supported.</exception> private static Tuple<bool, object> GetPropertyValue(object model, string propertyName) { if (model == null || string.IsNullOrEmpty(propertyName)) { return new Tuple<bool, object>(false, null); } if (model is IDictionary<string, object>) { return DynamicDictionaryPropertyEvaluator(model, propertyName); } if (!(model is IDynamicMetaObjectProvider)) { return StandardTypePropertyEvaluator(model, propertyName); } if (model is DynamicDictionaryValue) { var dynamicModel = model as DynamicDictionaryValue; return GetPropertyValue(dynamicModel.Value, propertyName); } if (model is DynamicObject) { return GetDynamicMember(model, propertyName); } throw new ArgumentException("model must be a standard type or implement IDictionary<string, object>", "model"); } private static Tuple<bool, object> GetDynamicMember(object obj, string memberName) { var binder = Microsoft.CSharp.RuntimeBinder.Binder.GetMember(CSharpBinderFlags.None, memberName, obj.GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); var callsite = CallSite<Func<CallSite, object, object>>.Create(binder); var result = callsite.Target(callsite, obj); return result == null ? new Tuple<bool, object>(false, null) : new Tuple<bool, object>(true, result); } /// <summary> /// A property extractor for standard types. /// </summary> /// <param name="model">The model.</param> /// <param name="propertyName">The property name.</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns> private static Tuple<bool, object> StandardTypePropertyEvaluator(object model, string propertyName) { var type = model.GetType(); var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); var property = properties.Where(p => string.Equals(p.Name, propertyName, StringComparison.InvariantCulture)). FirstOrDefault(); if (property != null) { return new Tuple<bool, object>(true, property.GetValue(model, null)); } var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); var field = fields.Where(p => string.Equals(p.Name, propertyName, StringComparison.InvariantCulture)). FirstOrDefault(); return field == null ? new Tuple<bool, object>(false, null) : new Tuple<bool, object>(true, field.GetValue(model)); } /// <summary> /// A property extractor designed for ExpandoObject, but also for any /// type that implements IDictionary string object for accessing its /// properties. /// </summary> /// <param name="model">The model.</param> /// <param name="propertyName">The property name.</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns> private static Tuple<bool, object> DynamicDictionaryPropertyEvaluator(object model, string propertyName) { var dictionaryModel = (IDictionary<string, object>)model; object output; return !dictionaryModel.TryGetValue(propertyName, out output) ? new Tuple<bool, object>(false, null) : new Tuple<bool, object>(true, output); } /// <summary> /// Gets an IEnumerable of capture group values /// </summary> /// <param name="m">The match to use.</param> /// <param name="groupName">Group name containing the capture group.</param> /// <returns>IEnumerable of capture group values as strings.</returns> private static IEnumerable<string> GetCaptureGroupValues(Match m, string groupName) { return m.Groups[groupName].Captures.Cast<Capture>().Select(c => c.Value); } /// <summary> /// Gets a property value from a collection of nested parameter names /// </summary> /// <param name="model">The model containing properties.</param> /// <param name="parameters">A collection of nested parameters (e.g. User, Name</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns> private static Tuple<bool, object> GetPropertyValueFromParameterCollection(object model, IEnumerable<string> parameters) { if (parameters == null) { return new Tuple<bool, object>(true, model); } var currentObject = model; foreach (var parameter in parameters) { var currentResult = GetPropertyValue(currentObject, parameter); if (currentResult.Item1 == false) { return new Tuple<bool, object>(false, null); } currentObject = currentResult.Item2; } return new Tuple<bool, object>(true, currentObject); } /// <summary> /// Gets the predicate result for an If or IfNot block /// </summary> /// <param name="item">The item to evaluate</param> /// <param name="properties">Property list to evaluate</param> /// <param name="nullCheck">Whether to check for null, rather than straight boolean</param> /// <returns>Bool representing the predicate result</returns> private static bool GetPredicateResult(object item, IEnumerable<string> properties, bool nullCheck) { var substitutionObject = GetPropertyValueFromParameterCollection(item, properties); if (substitutionObject.Item1 == false && properties.Last().StartsWith("Has")) { var newProperties = properties.Take(properties.Count() - 1).Concat(new[] { properties.Last().Substring(3) }); substitutionObject = GetPropertyValueFromParameterCollection(item, newProperties); return GetHasPredicateResultFromSubstitutionObject(substitutionObject.Item2); } return GetPredicateResultFromSubstitutionObject(substitutionObject.Item2, nullCheck); } /// <summary> /// Returns the predicate result if the substitionObject is a valid bool /// </summary> /// <param name="substitutionObject">The substitution object.</param> /// <param name="nullCheck"></param> /// <returns>Bool value of the substitutionObject, or false if unable to cast.</returns> private static bool GetPredicateResultFromSubstitutionObject(object substitutionObject, bool nullCheck) { if (nullCheck) { return substitutionObject == null; } if (substitutionObject != null && substitutionObject.GetType().GetProperty("Value") != null) { object value = ((dynamic)substitutionObject).Value; if (value is bool?) { substitutionObject = value; } } var predicateResult = false; var substitutionBool = substitutionObject as bool?; if (substitutionBool != null) { predicateResult = substitutionBool.Value; } return predicateResult; } /// <summary> /// Returns the predicate result if the substitionObject is a valid ICollection /// </summary> /// <param name="substitutionObject">The substitution object.</param> /// <returns>Bool value of the whether the ICollection has items, or false if unable to cast.</returns> private static bool GetHasPredicateResultFromSubstitutionObject(object substitutionObject) { var predicateResult = false; var substitutionCollection = substitutionObject as ICollection; if (substitutionCollection != null) { predicateResult = substitutionCollection.Count != 0; } return predicateResult; } /// <summary> /// Performs single @ViewBag.PropertyName substitutions. /// </summary> /// <param name="template">The template.</param> /// <param name="model">This parameter is not used, the model is based on the "host.Context.ViewBag".</param> /// <param name="host">View engine host</param> /// <returns>Template with @ViewBag.PropertyName blocks expanded.</returns> private static string PerformViewBagSubstitutions(string template, object model, IViewEngineHost host) { return ViewBagSubstitutionsRegEx.Replace( template, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var substitution = GetPropertyValueFromParameterCollection(((dynamic)host.Context).ViewBag, properties); if (!substitution.Item1) { return "[ERR!]"; } if (substitution.Item2 == null) { return string.Empty; } return m.Groups["Encode"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString(); }); } /// <summary> /// Performs single @Model.PropertyName substitutions. /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with @Model.PropertyName blocks expanded.</returns> private static string PerformSingleSubstitutions(string template, object model, IViewEngineHost host) { return SingleSubstitutionsRegEx.Replace( template, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var substitution = GetPropertyValueFromParameterCollection(model, properties); if (!substitution.Item1) { return "[ERR!]"; } if (substitution.Item2 == null) { return string.Empty; } return m.Groups["Encode"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString(); }); } /// <summary> /// Performs single @Context.PropertyName substitutions. /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with @Context.PropertyName blocks expanded.</returns> private static string PerformContextSubstitutions(string template, object model, IViewEngineHost host) { return ContextSubstitutionsRegEx.Replace( template, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var substitution = GetPropertyValueFromParameterCollection(host.Context, properties); if (!substitution.Item1) { return "[ERR!]"; } if (substitution.Item2 == null) { return string.Empty; } return m.Groups["Encode"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString(); }); } /// <summary> /// Performs @Each.PropertyName substitutions /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with @Each.PropertyName blocks expanded.</returns> private string PerformEachSubstitutions(string template, object model, IViewEngineHost host) { return EachSubstitutionRegEx.Replace( template, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var modelSource = GetCaptureGroupValues(m, "ModelSource").SingleOrDefault(); if (modelSource != null && modelSource.Equals("Context", StringComparison.OrdinalIgnoreCase)) { model = host.Context; } var substitutionObject = GetPropertyValueFromParameterCollection(model, properties); if (substitutionObject.Item1 == false) { return "[ERR!]"; } if (substitutionObject.Item2 == null) { return string.Empty; } var substitutionEnumerable = substitutionObject.Item2 as IEnumerable; if (substitutionEnumerable == null) { return "[ERR!]"; } var contents = m.Groups["Contents"].Value; var result = new StringBuilder(); foreach (var item in substitutionEnumerable) { var modifiedContent = PerformPartialSubstitutions(contents, item, host); modifiedContent = PerformConditionalSubstitutions(modifiedContent, item, host); result.Append(ReplaceCurrentMatch(modifiedContent, item, host)); } return result.ToString(); }); } /// <summary> /// Expand a @Current match inside an @Each iterator /// </summary> /// <param name="contents">Contents of the @Each block</param> /// <param name="item">Current item from the @Each enumerable</param> /// <param name="host">View engine host</param> /// <returns>String result of the expansion of the @Each.</returns> private static string ReplaceCurrentMatch(string contents, object item, IViewEngineHost host) { return EachItemSubstitutionRegEx.Replace( contents, eachMatch => { if (string.IsNullOrEmpty(eachMatch.Groups["ParameterName"].Value)) { return eachMatch.Groups["Encode"].Success ? host.HtmlEncode(item.ToString()) : item.ToString(); } var properties = GetCaptureGroupValues(eachMatch, "ParameterName"); var substitution = GetPropertyValueFromParameterCollection(item, properties); if (!substitution.Item1) { return "[ERR!]"; } if (substitution.Item2 == null) { return string.Empty; } return eachMatch.Groups["Encode"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString(); }); } /// <summary> /// Performs @If.PropertyName and @IfNot.PropertyName substitutions /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with @If.PropertyName @IfNot.PropertyName blocks removed/expanded.</returns> private static string PerformConditionalSubstitutions(string template, object model, IViewEngineHost host) { var result = template; result = ConditionalSubstitutionRegEx.Replace( result, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var modelSource = GetCaptureGroupValues(m, "ModelSource").SingleOrDefault(); if (modelSource != null && modelSource.Equals("Context", StringComparison.OrdinalIgnoreCase)) { model = host.Context; } var predicateResult = GetPredicateResult(model, properties, m.Groups["Null"].Value == "Null"); if (m.Groups["Not"].Value == "Not") { predicateResult = !predicateResult; } return predicateResult ? m.Groups["Contents"].Value : string.Empty; }); return result; } /// <summary> /// Perform path expansion substitutions /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with paths expanded</returns> private static string PerformPathSubstitutions(string template, object model, IViewEngineHost host) { var result = template; result = PathExpansionRegEx.Replace( result, m => { var path = m.Groups["Path"].Value; return host.ExpandPath(path); }); result = AttributeValuePathExpansionRegEx.Replace( result, m => { var attribute = m.Groups["Attribute"]; var quote = m.Groups["Quote"].Value; var path = m.Groups["Path"].Value; var expandedPath = host.ExpandPath(path); return string.Format("{0}={1}{2}{1}", attribute, quote, expandedPath); }); return result; } /// <summary> /// Perform CSRF anti forgery token expansions /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with anti forgery tokens expanded</returns> private static string PerformAntiForgeryTokenSubstitutions(string template, object model, IViewEngineHost host) { return AntiForgeryTokenRegEx.Replace(template, x => host.AntiForgeryToken()); } /// <summary> /// Perform @Partial partial view expansion /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with partials expanded</returns> private string PerformPartialSubstitutions(string template, dynamic model, IViewEngineHost host) { var result = template; result = PartialSubstitutionRegEx.Replace( result, m => { var partialViewName = m.Groups["ViewName"].Value; var partialModel = model; var properties = GetCaptureGroupValues(m, "ParameterName"); if (m.Groups["Model"].Length > 0) { var modelValue = GetPropertyValueFromParameterCollection(partialModel, properties); if (modelValue.Item1 != true) { return "[ERR!]"; } partialModel = modelValue.Item2; } var partialTemplate = host.GetTemplate(partialViewName, partialModel); return this.Render(partialTemplate, partialModel, host); }); return result; } /// <summary> /// Invokes the master page rendering with current sections if necessary /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with master page applied and sections substituted</returns> private string PerformMasterPageSubstitutions(string template, object model, IViewEngineHost host) { var masterPageName = GetMasterPageName(template); if (string.IsNullOrWhiteSpace(masterPageName)) { return template; } var masterTemplate = host.GetTemplate(masterPageName, model); var sectionMatches = SectionContentsRegEx.Matches(template); var sections = sectionMatches.Cast<Match>().ToDictionary(sectionMatch => sectionMatch.Groups["SectionName"].Value, sectionMatch => sectionMatch.Groups["SectionContents"].Value); return this.RenderMasterPage(masterTemplate, sections, model, host); } /// <summary> /// Renders a master page - does a normal render then replaces any section tags with sections passed in /// </summary> /// <param name="masterTemplate">The master page template</param> /// <param name="sections">Dictionary of section contents</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with the master page applied and sections substituted</returns> private string RenderMasterPage(string masterTemplate, IDictionary<string, string> sections, object model, IViewEngineHost host) { var result = this.Render(masterTemplate, model, host); result = SectionDeclarationRegEx.Replace( result, m => { var sectionName = m.Groups["SectionName"].Value; return sections.ContainsKey(sectionName) ? sections[sectionName] : string.Empty; }); return result; } /// <summary> /// Gets the master page name, if one is specified /// </summary> /// <param name="template">The template</param> /// <returns>Master page name or String.Empty</returns> private static string GetMasterPageName(string template) { using (var stringReader = new StringReader(template)) { var firstLine = stringReader.ReadLine(); if (firstLine == null) { return string.Empty; } var masterPageMatch = MasterPageHeaderRegEx.Match(firstLine); return masterPageMatch.Success ? masterPageMatch.Groups["MasterPage"].Value : string.Empty; } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Converter ** ** ** Purpose: Hexify and bin.base64 conversions ** ** ===========================================================*/ namespace System.Runtime.Serialization.Formatters.Binary { using System.Threading; using System.Runtime.Remoting; using System.Runtime.Serialization; using System; using System.Reflection; using System.Globalization; using System.Text; using System.Security.Permissions; using System.Diagnostics.Contracts; sealed internal class Converter { private Converter() { } private static int primitiveTypeEnumLength = 17; //Number of PrimitiveTypeEnums // The following section are utilities to read and write XML types internal static InternalPrimitiveTypeE ToCode(Type type) { SerTrace.Log("Converter", "ToCode Type Entry ",type); InternalPrimitiveTypeE code; if ((object)type != null && !type.IsPrimitive) { if (Object.ReferenceEquals(type, typeofDateTime)) code = InternalPrimitiveTypeE.DateTime; else if (Object.ReferenceEquals(type, typeofTimeSpan)) code = InternalPrimitiveTypeE.TimeSpan; else if (Object.ReferenceEquals(type, typeofDecimal)) code = InternalPrimitiveTypeE.Decimal; else code = InternalPrimitiveTypeE.Invalid; } else code = ToPrimitiveTypeEnum(Type.GetTypeCode(type)); SerTrace.Log("Converter", "ToCode Exit " , ((Enum)code).ToString()); return code; } internal static bool IsWriteAsByteArray(InternalPrimitiveTypeE code) { bool isWrite = false; switch (code) { case InternalPrimitiveTypeE.Boolean: case InternalPrimitiveTypeE.Char: case InternalPrimitiveTypeE.Byte: case InternalPrimitiveTypeE.Double: case InternalPrimitiveTypeE.Int16: case InternalPrimitiveTypeE.Int32: case InternalPrimitiveTypeE.Int64: case InternalPrimitiveTypeE.SByte: case InternalPrimitiveTypeE.Single: case InternalPrimitiveTypeE.UInt16: case InternalPrimitiveTypeE.UInt32: case InternalPrimitiveTypeE.UInt64: isWrite = true; break; } return isWrite; } internal static int TypeLength(InternalPrimitiveTypeE code) { int length = 0; switch (code) { case InternalPrimitiveTypeE.Boolean: length = 1; break; case InternalPrimitiveTypeE.Char: length = 2; break; case InternalPrimitiveTypeE.Byte: length = 1; break; case InternalPrimitiveTypeE.Double: length = 8; break; case InternalPrimitiveTypeE.Int16: length = 2; break; case InternalPrimitiveTypeE.Int32: length = 4; break; case InternalPrimitiveTypeE.Int64: length = 8; break; case InternalPrimitiveTypeE.SByte: length = 1; break; case InternalPrimitiveTypeE.Single: length = 4; break; case InternalPrimitiveTypeE.UInt16: length = 2; break; case InternalPrimitiveTypeE.UInt32: length = 4; break; case InternalPrimitiveTypeE.UInt64: length = 8; break; } return length; } internal static InternalNameSpaceE GetNameSpaceEnum(InternalPrimitiveTypeE code, Type type, WriteObjectInfo objectInfo, out String typeName) { SerTrace.Log("Converter", "GetNameSpaceEnum Entry ",((Enum)code).ToString()," type ",type); InternalNameSpaceE nameSpaceEnum = InternalNameSpaceE.None; typeName = null; if (code != InternalPrimitiveTypeE.Invalid) { switch (code) { case InternalPrimitiveTypeE.Boolean: case InternalPrimitiveTypeE.Char: case InternalPrimitiveTypeE.Byte: case InternalPrimitiveTypeE.Double: case InternalPrimitiveTypeE.Int16: case InternalPrimitiveTypeE.Int32: case InternalPrimitiveTypeE.Int64: case InternalPrimitiveTypeE.SByte: case InternalPrimitiveTypeE.Single: case InternalPrimitiveTypeE.UInt16: case InternalPrimitiveTypeE.UInt32: case InternalPrimitiveTypeE.UInt64: case InternalPrimitiveTypeE.DateTime: case InternalPrimitiveTypeE.TimeSpan: nameSpaceEnum = InternalNameSpaceE.XdrPrimitive; typeName = "System."+ToComType(code); break; case InternalPrimitiveTypeE.Decimal: nameSpaceEnum = InternalNameSpaceE.UrtSystem; typeName = "System."+ToComType(code); break; } } if ((nameSpaceEnum == InternalNameSpaceE.None) && ((object)type != null)) { if (Object.ReferenceEquals(type, typeofString)) nameSpaceEnum = InternalNameSpaceE.XdrString; else { if (objectInfo == null) { typeName = type.FullName; if (type.Assembly == urtAssembly) nameSpaceEnum = InternalNameSpaceE.UrtSystem; else nameSpaceEnum = InternalNameSpaceE.UrtUser; } else { typeName = objectInfo.GetTypeFullName(); if (objectInfo.GetAssemblyString().Equals(urtAssemblyString)) nameSpaceEnum = InternalNameSpaceE.UrtSystem; else nameSpaceEnum = InternalNameSpaceE.UrtUser; } } } SerTrace.Log("Converter", "GetNameSpaceEnum Exit ", ((Enum)nameSpaceEnum).ToString()," typeName ",typeName); return nameSpaceEnum; } // Returns a COM runtime type associated with the type code internal static Type ToArrayType(InternalPrimitiveTypeE code) { SerTrace.Log("Converter", "ToType Entry ", ((Enum)code).ToString()); if (arrayTypeA == null) InitArrayTypeA(); SerTrace.Log("Converter", "ToType Exit ", (((object)arrayTypeA[(int)code] == null)?"null ":arrayTypeA[(int)code].Name)); return arrayTypeA[(int)code]; } private static volatile Type[] typeA; private static void InitTypeA() { Type[] typeATemp = new Type[primitiveTypeEnumLength]; typeATemp[(int)InternalPrimitiveTypeE.Invalid] = null; typeATemp[(int)InternalPrimitiveTypeE.Boolean] = typeofBoolean; typeATemp[(int)InternalPrimitiveTypeE.Byte] = typeofByte; typeATemp[(int)InternalPrimitiveTypeE.Char] = typeofChar; typeATemp[(int)InternalPrimitiveTypeE.Decimal] = typeofDecimal; typeATemp[(int)InternalPrimitiveTypeE.Double] = typeofDouble; typeATemp[(int)InternalPrimitiveTypeE.Int16] = typeofInt16; typeATemp[(int)InternalPrimitiveTypeE.Int32] = typeofInt32; typeATemp[(int)InternalPrimitiveTypeE.Int64] = typeofInt64; typeATemp[(int)InternalPrimitiveTypeE.SByte] = typeofSByte; typeATemp[(int)InternalPrimitiveTypeE.Single] = typeofSingle; typeATemp[(int)InternalPrimitiveTypeE.TimeSpan] = typeofTimeSpan; typeATemp[(int)InternalPrimitiveTypeE.DateTime] = typeofDateTime; typeATemp[(int)InternalPrimitiveTypeE.UInt16] = typeofUInt16; typeATemp[(int)InternalPrimitiveTypeE.UInt32] = typeofUInt32; typeATemp[(int)InternalPrimitiveTypeE.UInt64] = typeofUInt64; typeA = typeATemp; } private static volatile Type[] arrayTypeA; private static void InitArrayTypeA() { Type[] arrayTypeATemp = new Type[primitiveTypeEnumLength]; arrayTypeATemp[(int)InternalPrimitiveTypeE.Invalid] = null; arrayTypeATemp[(int)InternalPrimitiveTypeE.Boolean] = typeofBooleanArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Byte] = typeofByteArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Char] = typeofCharArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Decimal] = typeofDecimalArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Double] = typeofDoubleArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Int16] = typeofInt16Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.Int32] = typeofInt32Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.Int64] = typeofInt64Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.SByte] = typeofSByteArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Single] = typeofSingleArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.TimeSpan] = typeofTimeSpanArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.DateTime] = typeofDateTimeArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.UInt16] = typeofUInt16Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.UInt32] = typeofUInt32Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.UInt64] = typeofUInt64Array; arrayTypeA = arrayTypeATemp; } // Returns a COM runtime type associated with the type code internal static Type ToType(InternalPrimitiveTypeE code) { SerTrace.Log("Converter", "ToType Entry ", ((Enum)code).ToString()); if (typeA == null) InitTypeA(); SerTrace.Log("Converter", "ToType Exit ", (((object)typeA[(int)code] == null)?"null ":typeA[(int)code].Name)); return typeA[(int)code]; } internal static Array CreatePrimitiveArray(InternalPrimitiveTypeE code, int length) { Array array = null; switch (code) { case InternalPrimitiveTypeE.Boolean: array = new Boolean[length]; break; case InternalPrimitiveTypeE.Byte: array = new Byte[length]; break; case InternalPrimitiveTypeE.Char: array = new Char[length]; break; case InternalPrimitiveTypeE.Decimal: array = new Decimal[length]; break; case InternalPrimitiveTypeE.Double: array = new Double[length]; break; case InternalPrimitiveTypeE.Int16: array = new Int16[length]; break; case InternalPrimitiveTypeE.Int32: array = new Int32[length]; break; case InternalPrimitiveTypeE.Int64: array = new Int64[length]; break; case InternalPrimitiveTypeE.SByte: array = new SByte[length]; break; case InternalPrimitiveTypeE.Single: array = new Single[length]; break; case InternalPrimitiveTypeE.TimeSpan: array = new TimeSpan[length]; break; case InternalPrimitiveTypeE.DateTime: array = new DateTime[length]; break; case InternalPrimitiveTypeE.UInt16: array = new UInt16[length]; break; case InternalPrimitiveTypeE.UInt32: array = new UInt32[length]; break; case InternalPrimitiveTypeE.UInt64: array = new UInt64[length]; break; } return array; } internal static bool IsPrimitiveArray(Type type, out Object typeInformation) { typeInformation = null; bool bIsPrimitive = true; if (Object.ReferenceEquals(type, typeofBooleanArray)) typeInformation = InternalPrimitiveTypeE.Boolean; else if (Object.ReferenceEquals(type, typeofByteArray)) typeInformation = InternalPrimitiveTypeE.Byte; else if (Object.ReferenceEquals(type, typeofCharArray)) typeInformation = InternalPrimitiveTypeE.Char; else if (Object.ReferenceEquals(type, typeofDoubleArray)) typeInformation = InternalPrimitiveTypeE.Double; else if (Object.ReferenceEquals(type, typeofInt16Array)) typeInformation = InternalPrimitiveTypeE.Int16; else if (Object.ReferenceEquals(type, typeofInt32Array)) typeInformation = InternalPrimitiveTypeE.Int32; else if (Object.ReferenceEquals(type, typeofInt64Array)) typeInformation = InternalPrimitiveTypeE.Int64; else if (Object.ReferenceEquals(type, typeofSByteArray)) typeInformation = InternalPrimitiveTypeE.SByte; else if (Object.ReferenceEquals(type, typeofSingleArray)) typeInformation = InternalPrimitiveTypeE.Single; else if (Object.ReferenceEquals(type, typeofUInt16Array)) typeInformation = InternalPrimitiveTypeE.UInt16; else if (Object.ReferenceEquals(type, typeofUInt32Array)) typeInformation = InternalPrimitiveTypeE.UInt32; else if (Object.ReferenceEquals(type, typeofUInt64Array)) typeInformation = InternalPrimitiveTypeE.UInt64; else bIsPrimitive = false; return bIsPrimitive; } private static volatile String[] valueA; private static void InitValueA() { String[] valueATemp = new String[primitiveTypeEnumLength]; valueATemp[(int)InternalPrimitiveTypeE.Invalid] = null; valueATemp[(int)InternalPrimitiveTypeE.Boolean] = "Boolean"; valueATemp[(int)InternalPrimitiveTypeE.Byte] = "Byte"; valueATemp[(int)InternalPrimitiveTypeE.Char] = "Char"; valueATemp[(int)InternalPrimitiveTypeE.Decimal] = "Decimal"; valueATemp[(int)InternalPrimitiveTypeE.Double] = "Double"; valueATemp[(int)InternalPrimitiveTypeE.Int16] = "Int16"; valueATemp[(int)InternalPrimitiveTypeE.Int32] = "Int32"; valueATemp[(int)InternalPrimitiveTypeE.Int64] = "Int64"; valueATemp[(int)InternalPrimitiveTypeE.SByte] = "SByte"; valueATemp[(int)InternalPrimitiveTypeE.Single] = "Single"; valueATemp[(int)InternalPrimitiveTypeE.TimeSpan] = "TimeSpan"; valueATemp[(int)InternalPrimitiveTypeE.DateTime] = "DateTime"; valueATemp[(int)InternalPrimitiveTypeE.UInt16] = "UInt16"; valueATemp[(int)InternalPrimitiveTypeE.UInt32] = "UInt32"; valueATemp[(int)InternalPrimitiveTypeE.UInt64] = "UInt64"; valueA = valueATemp; } // Returns a String containg a COM+ runtime type associated with the type code internal static String ToComType(InternalPrimitiveTypeE code) { SerTrace.Log("Converter", "ToComType Entry ", ((Enum)code).ToString()); if (valueA == null) InitValueA(); SerTrace.Log("Converter", "ToComType Exit ",((valueA[(int)code] == null)?"null":valueA[(int)code])); return valueA[(int)code]; } private static volatile TypeCode[] typeCodeA; private static void InitTypeCodeA() { TypeCode[] typeCodeATemp = new TypeCode[primitiveTypeEnumLength]; typeCodeATemp[(int)InternalPrimitiveTypeE.Invalid] = TypeCode.Object; typeCodeATemp[(int)InternalPrimitiveTypeE.Boolean] = TypeCode.Boolean; typeCodeATemp[(int)InternalPrimitiveTypeE.Byte] = TypeCode.Byte; typeCodeATemp[(int)InternalPrimitiveTypeE.Char] = TypeCode.Char; typeCodeATemp[(int)InternalPrimitiveTypeE.Decimal] = TypeCode.Decimal; typeCodeATemp[(int)InternalPrimitiveTypeE.Double] = TypeCode.Double; typeCodeATemp[(int)InternalPrimitiveTypeE.Int16] = TypeCode.Int16; typeCodeATemp[(int)InternalPrimitiveTypeE.Int32] = TypeCode.Int32; typeCodeATemp[(int)InternalPrimitiveTypeE.Int64] = TypeCode.Int64; typeCodeATemp[(int)InternalPrimitiveTypeE.SByte] = TypeCode.SByte; typeCodeATemp[(int)InternalPrimitiveTypeE.Single] = TypeCode.Single; typeCodeATemp[(int)InternalPrimitiveTypeE.TimeSpan] = TypeCode.Object; typeCodeATemp[(int)InternalPrimitiveTypeE.DateTime] = TypeCode.DateTime; typeCodeATemp[(int)InternalPrimitiveTypeE.UInt16] = TypeCode.UInt16; typeCodeATemp[(int)InternalPrimitiveTypeE.UInt32] = TypeCode.UInt32; typeCodeATemp[(int)InternalPrimitiveTypeE.UInt64] = TypeCode.UInt64; typeCodeA = typeCodeATemp; } // Returns a System.TypeCode from a InternalPrimitiveTypeE internal static TypeCode ToTypeCode(InternalPrimitiveTypeE code) { if (typeCodeA == null) InitTypeCodeA(); return typeCodeA[(int)code]; } private static volatile InternalPrimitiveTypeE[] codeA; private static void InitCodeA() { InternalPrimitiveTypeE[] codeATemp = new InternalPrimitiveTypeE[19]; codeATemp[(int)TypeCode.Empty] = InternalPrimitiveTypeE.Invalid; codeATemp[(int)TypeCode.Object] = InternalPrimitiveTypeE.Invalid; #if !FEATURE_CORECLR codeATemp[(int)TypeCode.DBNull] = InternalPrimitiveTypeE.Invalid; #endif codeATemp[(int)TypeCode.Boolean] = InternalPrimitiveTypeE.Boolean; codeATemp[(int)TypeCode.Char] = InternalPrimitiveTypeE.Char; codeATemp[(int)TypeCode.SByte] = InternalPrimitiveTypeE.SByte; codeATemp[(int)TypeCode.Byte] = InternalPrimitiveTypeE.Byte; codeATemp[(int)TypeCode.Int16] = InternalPrimitiveTypeE.Int16; codeATemp[(int)TypeCode.UInt16] = InternalPrimitiveTypeE.UInt16; codeATemp[(int)TypeCode.Int32] = InternalPrimitiveTypeE.Int32; codeATemp[(int)TypeCode.UInt32] = InternalPrimitiveTypeE.UInt32; codeATemp[(int)TypeCode.Int64] = InternalPrimitiveTypeE.Int64; codeATemp[(int)TypeCode.UInt64] = InternalPrimitiveTypeE.UInt64; codeATemp[(int)TypeCode.Single] = InternalPrimitiveTypeE.Single; codeATemp[(int)TypeCode.Double] = InternalPrimitiveTypeE.Double; codeATemp[(int)TypeCode.Decimal] = InternalPrimitiveTypeE.Decimal; codeATemp[(int)TypeCode.DateTime] = InternalPrimitiveTypeE.DateTime; codeATemp[17] = InternalPrimitiveTypeE.Invalid; codeATemp[(int)TypeCode.String] = InternalPrimitiveTypeE.Invalid; codeA = codeATemp; } // Returns a InternalPrimitiveTypeE from a System.TypeCode internal static InternalPrimitiveTypeE ToPrimitiveTypeEnum(TypeCode typeCode) { if (codeA == null) InitCodeA(); return codeA[(int)typeCode]; } // Translates a string into an Object internal static Object FromString(String value, InternalPrimitiveTypeE code) { Object var; SerTrace.Log( "Converter", "FromString Entry ",value," " , ((Enum)code).ToString()); // InternalPrimitiveTypeE needs to be a primitive type Contract.Assert((code != InternalPrimitiveTypeE.Invalid), "[Converter.FromString]!InternalPrimitiveTypeE.Invalid "); if (code != InternalPrimitiveTypeE.Invalid) var = Convert.ChangeType(value, ToTypeCode(code), CultureInfo.InvariantCulture); else var = value; SerTrace.Log( "Converter", "FromString Exit "+((var == null)?"null":var+" var type "+((var==null)?"<null>":var.GetType().ToString()))); return var; } internal static Type typeofISerializable = typeof(ISerializable); internal static Type typeofString = typeof(String); internal static Type typeofConverter = typeof(Converter); internal static Type typeofBoolean = typeof(Boolean); internal static Type typeofByte = typeof(Byte); internal static Type typeofChar = typeof(Char); internal static Type typeofDecimal = typeof(Decimal); internal static Type typeofDouble = typeof(Double); internal static Type typeofInt16 = typeof(Int16); internal static Type typeofInt32 = typeof(Int32); internal static Type typeofInt64 = typeof(Int64); internal static Type typeofSByte = typeof(SByte); internal static Type typeofSingle = typeof(Single); internal static Type typeofTimeSpan = typeof(TimeSpan); internal static Type typeofDateTime = typeof(DateTime); internal static Type typeofUInt16 = typeof(UInt16); internal static Type typeofUInt32 = typeof(UInt32); internal static Type typeofUInt64 = typeof(UInt64); internal static Type typeofObject = typeof(Object); internal static Type typeofSystemVoid = typeof(void); internal static Assembly urtAssembly = Assembly.GetAssembly(typeofString); internal static String urtAssemblyString = urtAssembly.FullName; // Arrays internal static Type typeofTypeArray = typeof(System.Type[]); internal static Type typeofObjectArray = typeof(System.Object[]); internal static Type typeofStringArray = typeof(System.String[]); internal static Type typeofBooleanArray = typeof(Boolean[]); internal static Type typeofByteArray = typeof(Byte[]); internal static Type typeofCharArray = typeof(Char[]); internal static Type typeofDecimalArray = typeof(Decimal[]); internal static Type typeofDoubleArray = typeof(Double[]); internal static Type typeofInt16Array = typeof(Int16[]); internal static Type typeofInt32Array = typeof(Int32[]); internal static Type typeofInt64Array = typeof(Int64[]); internal static Type typeofSByteArray = typeof(SByte[]); internal static Type typeofSingleArray = typeof(Single[]); internal static Type typeofTimeSpanArray = typeof(TimeSpan[]); internal static Type typeofDateTimeArray = typeof(DateTime[]); internal static Type typeofUInt16Array = typeof(UInt16[]); internal static Type typeofUInt32Array = typeof(UInt32[]); internal static Type typeofUInt64Array = typeof(UInt64[]); internal static Type typeofMarshalByRefObject = typeof(System.MarshalByRefObject); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Build.Framework; using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; using Xunit; namespace Microsoft.Build.UnitTests { /* * Class: AlTests * * Test the AL task in various ways. * */ sealed public class AlTests { /// <summary> /// Tests the AlgorithmId parameter /// </summary> [Fact] public void AlgorithmId() { AL t = new AL(); Assert.Null(t.AlgorithmId); // "Default value" t.AlgorithmId = "whatisthis"; Assert.Equal("whatisthis", t.AlgorithmId); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/algid:whatisthis"); } /// <summary> /// Tests the BaseAddress parameter /// </summary> [Fact] public void BaseAddress() { AL t = new AL(); Assert.Null(t.BaseAddress); // "Default value" t.BaseAddress = "12345678"; Assert.Equal("12345678", t.BaseAddress); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/baseaddress:12345678"); } /// <summary> /// Tests the CompanyName parameter /// </summary> [Fact] public void CompanyName() { AL t = new AL(); Assert.Null(t.CompanyName); // "Default value" t.CompanyName = "Google"; Assert.Equal("Google", t.CompanyName); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/company:Google"); } /// <summary> /// Tests the Configuration parameter /// </summary> [Fact] public void Configuration() { AL t = new AL(); Assert.Null(t.Configuration); // "Default value" t.Configuration = "debug"; Assert.Equal("debug", t.Configuration); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/configuration:debug"); } /// <summary> /// Tests the Copyright parameter /// </summary> [Fact] public void Copyright() { AL t = new AL(); Assert.Null(t.Copyright); // "Default value" t.Copyright = "(C) 2005"; Assert.Equal("(C) 2005", t.Copyright); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/copyright:(C) 2005"); } /// <summary> /// Tests the Culture parameter /// </summary> [Fact] public void Culture() { AL t = new AL(); Assert.Null(t.Culture); // "Default value" t.Culture = "aussie"; Assert.Equal("aussie", t.Culture); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/culture:aussie"); } /// <summary> /// Tests the DelaySign parameter. /// </summary> [Fact] public void DelaySign() { AL t = new AL(); Assert.False(t.DelaySign); // "Default value" t.DelaySign = true; Assert.True(t.DelaySign); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, "/delaysign+"); } /// <summary> /// Tests the Description parameter /// </summary> [Fact] public void Description() { AL t = new AL(); Assert.Null(t.Description); // "Default value" t.Description = "whatever"; Assert.Equal("whatever", t.Description); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/description:whatever"); } /// <summary> /// Tests the EmbedResources parameter with an item that has metadata LogicalName and Access=private /// </summary> [Fact] public void EmbedResourcesWithPrivateAccess() { AL t = new AL(); Assert.Null(t.EmbedResources); // "Default value" // Construct the task item. TaskItem i = new TaskItem(); i.ItemSpec = "MyResource.bmp"; i.SetMetadata("LogicalName", "Kenny"); i.SetMetadata("Access", "Private"); t.EmbedResources = new ITaskItem[] { i }; Assert.Single(t.EmbedResources); // "New value" // Check the parameters. CommandLine.ValidateHasParameter( t, "/embed:MyResource.bmp,Kenny,Private"); } /// <summary> /// Tests the EvidenceFile parameter /// </summary> [Fact] public void EvidenceFile() { AL t = new AL(); Assert.Null(t.EvidenceFile); // "Default value" t.EvidenceFile = "MyEvidenceFile"; Assert.Equal("MyEvidenceFile", t.EvidenceFile); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/evidence:MyEvidenceFile"); } /// <summary> /// Tests the FileVersion parameter /// </summary> [Fact] public void FileVersion() { AL t = new AL(); Assert.Null(t.FileVersion); // "Default value" t.FileVersion = "1.2.3.4"; Assert.Equal("1.2.3.4", t.FileVersion); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/fileversion:1.2.3.4"); } /// <summary> /// Tests the Flags parameter /// </summary> [Fact] public void Flags() { AL t = new AL(); Assert.Null(t.Flags); // "Default value" t.Flags = "0x8421"; Assert.Equal("0x8421", t.Flags); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/flags:0x8421"); } /// <summary> /// Tests the GenerateFullPaths parameter. /// </summary> [Fact] public void GenerateFullPaths() { AL t = new AL(); Assert.False(t.GenerateFullPaths); // "Default value" t.GenerateFullPaths = true; Assert.True(t.GenerateFullPaths); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, "/fullpaths"); } /// <summary> /// Tests the KeyFile parameter /// </summary> [Fact] public void KeyFile() { AL t = new AL(); Assert.Null(t.KeyFile); // "Default value" t.KeyFile = "mykey.snk"; Assert.Equal("mykey.snk", t.KeyFile); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/keyfile:mykey.snk"); } /// <summary> /// Tests the KeyContainer parameter /// </summary> [Fact] public void KeyContainer() { AL t = new AL(); Assert.Null(t.KeyContainer); // "Default value" t.KeyContainer = "MyKeyContainer"; Assert.Equal("MyKeyContainer", t.KeyContainer); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/keyname:MyKeyContainer"); } /// <summary> /// Tests the LinkResources parameter with an item that has metadata LogicalName, Target, and Access=private /// </summary> [Fact] public void LinkResourcesWithPrivateAccessAndTargetFile() { AL t = new AL(); Assert.Null(t.LinkResources); // "Default value" // Construct the task item. TaskItem i = new TaskItem(); i.ItemSpec = "MyResource.bmp"; i.SetMetadata("LogicalName", "Kenny"); i.SetMetadata("TargetFile", @"working\MyResource.bmp"); i.SetMetadata("Access", "Private"); t.LinkResources = new ITaskItem[] { i }; Assert.Single(t.LinkResources); // "New value" // Check the parameters. CommandLine.ValidateHasParameter( t, @"/link:MyResource.bmp,Kenny,working\MyResource.bmp,Private"); } /// <summary> /// Tests the LinkResources parameter with two items with differing metadata. /// </summary> [Fact] public void LinkResourcesWithTwoItems() { AL t = new AL(); Assert.Null(t.LinkResources); // "Default value" // Construct the task item. TaskItem i1 = new TaskItem(); i1.ItemSpec = "MyResource.bmp"; i1.SetMetadata("LogicalName", "Kenny"); i1.SetMetadata("TargetFile", @"working\MyResource.bmp"); i1.SetMetadata("Access", "Private"); TaskItem i2 = new TaskItem(); i2.ItemSpec = "MyResource2.bmp"; i2.SetMetadata("LogicalName", "Chef"); i2.SetMetadata("TargetFile", @"working\MyResource2.bmp"); t.LinkResources = new ITaskItem[] { i1, i2 }; Assert.Equal(2, t.LinkResources.Length); // "New value" // Check the parameters. CommandLine.ValidateHasParameter( t, @"/link:MyResource.bmp,Kenny,working\MyResource.bmp,Private"); CommandLine.ValidateHasParameter( t, @"/link:MyResource2.bmp,Chef,working\MyResource2.bmp"); } /// <summary> /// Tests the MainEntryPoint parameter /// </summary> [Fact] public void MainEntryPoint() { AL t = new AL(); Assert.Null(t.MainEntryPoint); // "Default value" t.MainEntryPoint = "Class1.Main"; Assert.Equal("Class1.Main", t.MainEntryPoint); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/main:Class1.Main"); } /// <summary> /// Tests the OutputAssembly parameter /// </summary> [Fact] public void OutputAssembly() { AL t = new AL(); Assert.Null(t.OutputAssembly); // "Default value" t.OutputAssembly = new TaskItem("foo.dll"); Assert.Equal("foo.dll", t.OutputAssembly.ItemSpec); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/out:foo.dll"); } /// <summary> /// Tests the Platform parameter /// </summary> [Fact] public void Platform() { AL t = new AL(); Assert.Null(t.Platform); // "Default value" t.Platform = "x86"; Assert.Equal("x86", t.Platform); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/platform:x86"); } // Tests the "Platform" and "Prefer32Bit" parameter combinations on the AL task, // and confirms that it sets the /platform switch on the command-line correctly. [Fact] public void PlatformAndPrefer32Bit() { // Implicit "anycpu" AL t = new AL(); CommandLine.ValidateNoParameterStartsWith(t, @"/platform:"); t = new AL(); t.Prefer32Bit = false; CommandLine.ValidateNoParameterStartsWith(t, @"/platform:"); t = new AL(); t.Prefer32Bit = true; CommandLine.ValidateHasParameter( t, @"/platform:anycpu32bitpreferred"); // Explicit "anycpu" t = new AL(); t.Platform = "anycpu"; CommandLine.ValidateHasParameter(t, @"/platform:anycpu"); t = new AL(); t.Platform = "anycpu"; t.Prefer32Bit = false; CommandLine.ValidateHasParameter(t, @"/platform:anycpu"); t = new AL(); t.Platform = "anycpu"; t.Prefer32Bit = true; CommandLine.ValidateHasParameter( t, @"/platform:anycpu32bitpreferred"); // Explicit "x86" t = new AL(); t.Platform = "x86"; CommandLine.ValidateHasParameter(t, @"/platform:x86"); t = new AL(); t.Platform = "x86"; t.Prefer32Bit = false; CommandLine.ValidateHasParameter(t, @"/platform:x86"); t = new AL(); t.Platform = "x86"; t.Prefer32Bit = true; CommandLine.ValidateHasParameter(t, @"/platform:x86"); } /// <summary> /// Tests the ProductName parameter /// </summary> [Fact] public void ProductName() { AL t = new AL(); Assert.Null(t.ProductName); // "Default value" t.ProductName = "VisualStudio"; Assert.Equal("VisualStudio", t.ProductName); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/product:VisualStudio"); } /// <summary> /// Tests the ProductVersion parameter /// </summary> [Fact] public void ProductVersion() { AL t = new AL(); Assert.Null(t.ProductVersion); // "Default value" t.ProductVersion = "8.0"; Assert.Equal("8.0", t.ProductVersion); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/productversion:8.0"); } /// <summary> /// Tests the ResponseFiles parameter /// </summary> [Fact] public void ResponseFiles() { AL t = new AL(); Assert.Null(t.ResponseFiles); // "Default value" t.ResponseFiles = new string[2] { "one.rsp", "two.rsp" }; Assert.Equal(2, t.ResponseFiles.Length); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"@one.rsp"); CommandLine.ValidateHasParameter(t, @"@two.rsp"); } /// <summary> /// Tests the SourceModules parameter /// </summary> [Fact] public void SourceModules() { AL t = new AL(); Assert.Null(t.SourceModules); // "Default value" // Construct the task items. TaskItem i1 = new TaskItem(); i1.ItemSpec = "Strings.resources"; i1.SetMetadata("TargetFile", @"working\MyResource.bmp"); TaskItem i2 = new TaskItem(); i2.ItemSpec = "Dialogs.resources"; t.SourceModules = new ITaskItem[] { i1, i2 }; Assert.Equal(2, t.SourceModules.Length); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"Strings.resources,working\MyResource.bmp"); CommandLine.ValidateHasParameter(t, @"Dialogs.resources"); } /// <summary> /// Tests the TargetType parameter /// </summary> [Fact] public void TargetType() { AL t = new AL(); Assert.Null(t.TargetType); // "Default value" t.TargetType = "winexe"; Assert.Equal("winexe", t.TargetType); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/target:winexe"); } /// <summary> /// Tests the TemplateFile parameter /// </summary> [Fact] public void TemplateFile() { AL t = new AL(); Assert.Null(t.TemplateFile); // "Default value" t.TemplateFile = "mymainassembly.dll"; Assert.Equal("mymainassembly.dll", t.TemplateFile); // "New value" // Check the parameters. CommandLine.ValidateHasParameter( t, @"/template:mymainassembly.dll"); } /// <summary> /// Tests the Title parameter /// </summary> [Fact] public void Title() { AL t = new AL(); Assert.Null(t.Title); // "Default value" t.Title = "WarAndPeace"; Assert.Equal("WarAndPeace", t.Title); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/title:WarAndPeace"); } /// <summary> /// Tests the Trademark parameter /// </summary> [Fact] public void Trademark() { AL t = new AL(); Assert.Null(t.Trademark); // "Default value" t.Trademark = "MyTrademark"; Assert.Equal("MyTrademark", t.Trademark); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/trademark:MyTrademark"); } /// <summary> /// Tests the Version parameter /// </summary> [Fact] public void Version() { AL t = new AL(); Assert.Null(t.Version); // "Default value" t.Version = "WowHowManyKindsOfVersionsAreThere"; Assert.Equal("WowHowManyKindsOfVersionsAreThere", t.Version); // "New value" // Check the parameters. CommandLine.ValidateHasParameter( t, @"/version:WowHowManyKindsOfVersionsAreThere"); } /// <summary> /// Tests the Win32Icon parameter /// </summary> [Fact] public void Win32Icon() { AL t = new AL(); Assert.Null(t.Win32Icon); // "Default value" t.Win32Icon = "foo.ico"; Assert.Equal("foo.ico", t.Win32Icon); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/win32icon:foo.ico"); } /// <summary> /// Tests the Win32Resource parameter /// </summary> [Fact] public void Win32Resource() { AL t = new AL(); Assert.Null(t.Win32Resource); // "Default value" t.Win32Resource = "foo.res"; Assert.Equal("foo.res", t.Win32Resource); // "New value" // Check the parameters. CommandLine.ValidateHasParameter(t, @"/win32res:foo.res"); } } }
// 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 ShiftLeftLogicalInt1616() { var test = new ImmUnaryOpTest__ShiftLeftLogicalInt1616(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogicalInt1616 { private struct TestStruct { public Vector256<Int16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalInt1616 testClass) { var result = Avx2.ShiftLeftLogical(_fld, 16); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private static Vector256<Int16> _clsVar; private Vector256<Int16> _fld; private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable; static ImmUnaryOpTest__ShiftLeftLogicalInt1616() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public ImmUnaryOpTest__ShiftLeftLogicalInt1616() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftLeftLogical( Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftLeftLogical( Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftLeftLogical( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftLeftLogical( _clsVar, 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr); var result = Avx2.ShiftLeftLogical(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogicalInt1616(); var result = Avx2.ShiftLeftLogical(test._fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftLeftLogical(_fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftLeftLogical(test._fld, 16); 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(Vector256<Int16> firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (0 != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0 != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical)}<Int16>(Vector256<Int16><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Data.Common; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using TddBuddy.SpeedyLocalDb.DotNetCore.Attribute; using TddBuddy.SpeedyLocalDb.DotNetCore.Construction; using TddBuddy.SpeedyLocalDb.EF.Example.Attachment.DotNetCore.Builders; using TddBuddy.SpeedyLocalDb.EF.Example.Attachment.DotNetCore.Context; using TddBuddy.SpeedyLocalDb.EF.Example.Attachment.DotNetCore.Entities; using TddBuddy.SpeedyLocalDb.EF.Example.Attachment.DotNetCore.Repositories; namespace TddBuddy.SpeedySqlLocalDb.DotNetCore.Tests { [TestFixture, SharedSpeedyLocalDb(typeof(AttachmentDbContext))] public class AttachmentRepositoryTests { [Test] public void Create_GivenOneAttachment_ShouldStoreInDatabase() { //---------------Set up test pack------------------- var attachment = new AttachmentBuilder() .WithFileName("A.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); using (var wrapper = SpeedySqlFactory.CreateWrapper()) { var dbContext = CreateDbContext(wrapper.Connection); var attachmentsRepository = CreateRepository(dbContext); //---------------Execute Test ---------------------- attachmentsRepository.Create(attachment); attachmentsRepository.Save(); //---------------Test Result ----------------------- Assert.AreEqual(1, dbContext.Attachments.Count()); var actualAttachment = dbContext.Attachments.First(); AssertIsEqual(attachment, actualAttachment); } } [Test] public void Create_GivenExistingAttachment_ShouldThrowExceptionWhenSaving() { //---------------Set up test pack------------------- var attachment = new AttachmentBuilder() .WithFileName("A.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); using (var wrapper = SpeedySqlFactory.CreateWrapper()) { var dbContext = CreateDbContext(wrapper.Connection); var attachmentsRepository = CreateRepository(dbContext); dbContext.Attachments.Add(attachment); dbContext.SaveChanges(); //---------------Execute Test ---------------------- attachmentsRepository.Create(attachment); var exception = Assert.Throws<DbUpdateException>(() => attachmentsRepository.Save()); //---------------Test Result ----------------------- StringAssert.Contains("An error occurred while updating the entries", exception.Message); } } [Test] public void Create_GivenManyAttachments_ShouldStoreAllInDatabase() { //---------------Set up test pack------------------- var attachment1 = new AttachmentBuilder() .WithFileName("A.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); var attachment2 = new AttachmentBuilder() .WithId(new Guid()) .WithFileName("B.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); var attachment3 = new AttachmentBuilder() .WithFileName("C.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); using (var wrapper = SpeedySqlFactory.CreateWrapper()) { var dbContext = CreateDbContext(wrapper.Connection); var attachmentsRepository = CreateRepository(dbContext); //---------------Execute Test ---------------------- attachmentsRepository.Create(attachment1); attachmentsRepository.Create(attachment2); attachmentsRepository.Create(attachment3); attachmentsRepository.Save(); //---------------Test Result ----------------------- Assert.AreEqual(3, dbContext.Attachments.Count()); var actualAttachment1 = dbContext.Attachments.First(r => r.Id == attachment1.Id); var actualAttachment2 = dbContext.Attachments.First(r => r.Id == attachment2.Id); var actualAttachment3 = dbContext.Attachments.First(r => r.Id == attachment3.Id); AssertIsEqual(attachment1, actualAttachment1); AssertIsEqual(attachment2, actualAttachment2); AssertIsEqual(attachment3, actualAttachment3); } } [Test] public void Find_GivenExistingAttachment_ShouldReturnAttachment() { //---------------Set up test pack------------------- var id = Guid.NewGuid(); var attachment = new AttachmentBuilder() .WithId(id) .WithFileName("A.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); using (var wrapper = SpeedySqlFactory.CreateWrapper()) { var dbContext = CreateDbContext(wrapper.Connection); var attachmentsRepository = CreateRepository(dbContext); dbContext.Attachments.Add(attachment); dbContext.SaveChanges(); //---------------Execute Test ---------------------- var actualAttachment = attachmentsRepository.Find(id); //---------------Test Result ----------------------- Assert.IsNotNull(actualAttachment); AssertIsEqual(attachment, actualAttachment); } } [Test] public void Find_GivenAttachmentDoesNotExist_ShouldReturnNull() { //---------------Set up test pack------------------- var nonExistantId = Guid.NewGuid(); var attachment = new AttachmentBuilder() .WithId(Guid.NewGuid()) .Build(); using (var wrapper = SpeedySqlFactory.CreateWrapper()) { var dbContext = CreateDbContext(wrapper.Connection); var attachmentsRepository = CreateRepository(dbContext); dbContext.Attachments.Add(attachment); dbContext.SaveChanges(); //---------------Execute Test ---------------------- var actualAttachment = attachmentsRepository.Find(nonExistantId); //---------------Test Result ----------------------- Assert.Null(actualAttachment); } } [Test] public void Update_GivenExistingAttachment_ShouldUpdateInDatabase() { //---------------Set up test pack------------------- var attachment = new AttachmentBuilder() .WithFileName("A.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); using (var wrapper = SpeedySqlFactory.CreateWrapper()) { var dbContext = CreateDbContext(wrapper.Connection); var attachmentsRepository = CreateRepository(dbContext); dbContext.Attachments.Add(attachment); dbContext.SaveChanges(); var updatedAttachment = dbContext.Attachments.First(r => r.Id == attachment.Id); updatedAttachment.FileName = "Update-A.jpg"; //---------------Execute Test ---------------------- attachmentsRepository.Update(updatedAttachment); attachmentsRepository.Save(); //---------------Test Result ----------------------- var actualAttachment = dbContext.Attachments.First(); AssertIsEqual(updatedAttachment, actualAttachment); } } [Test] public void Update_GivenExistingAttachments_ShouldOnlyUpdateAttachmentWithGivenId() { //---------------Set up test pack------------------- var attachmentBeingUpdated = new AttachmentBuilder() .WithFileName("A.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); var attachmentNotBeingUpdated = new AttachmentBuilder() .WithFileName("B.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); using (var wrapper = SpeedySqlFactory.CreateWrapper()) { var dbContext = CreateDbContext(wrapper.Connection); var attachmentsRepository = CreateRepository(dbContext); dbContext.Attachments.Add(attachmentBeingUpdated); dbContext.Attachments.Add(attachmentNotBeingUpdated); dbContext.SaveChanges(); var updatedAttachment = dbContext.Attachments.First(r => r.Id == attachmentBeingUpdated.Id); updatedAttachment.FileName = "Update-A.jpg"; //---------------Execute Test ---------------------- attachmentsRepository.Update(updatedAttachment); attachmentsRepository.Save(); //---------------Test Result ----------------------- var actualAttachmentBeingUpdated = dbContext.Attachments.First(r => r.Id == attachmentBeingUpdated.Id); var actualAttachmentNotBeingUpdated = dbContext.Attachments.First(r => r.Id == attachmentNotBeingUpdated.Id); AssertIsEqual(updatedAttachment, actualAttachmentBeingUpdated); AssertIsEqual(attachmentNotBeingUpdated, actualAttachmentNotBeingUpdated); } } [Test] public void Update_GivenManyExistingAttachments_ShouldUpdateInDatabase() { //---------------Set up test pack------------------- var attachment1 = new AttachmentBuilder() .WithFileName("A.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); var attachment2 = new AttachmentBuilder() .WithFileName("B.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); var attachment3 = new AttachmentBuilder() .WithFileName("C.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); using (var wrapper = SpeedySqlFactory.CreateWrapper()) { var dbContext = CreateDbContext(wrapper.Connection); var attachmentsRepository = CreateRepository(dbContext); dbContext.Attachments.Add(attachment1); dbContext.Attachments.Add(attachment2); dbContext.Attachments.Add(attachment3); dbContext.SaveChanges(); var updatedAttachment1 = dbContext.Attachments.First(r => r.Id == attachment1.Id); updatedAttachment1.FileName = "Update-A.jpg"; var updatedAttachment2 = dbContext.Attachments.First(r => r.Id == attachment2.Id); updatedAttachment2.FileName = "Update-B.jpg"; var updatedAttachment3 = dbContext.Attachments.First(r => r.Id == attachment3.Id); updatedAttachment3.FileName = "Update-C.jpg"; //---------------Execute Test ---------------------- attachmentsRepository.Update(updatedAttachment1); attachmentsRepository.Update(updatedAttachment2); attachmentsRepository.Update(updatedAttachment3); attachmentsRepository.Save(); //---------------Test Result ----------------------- var actualAttachment1 = dbContext.Attachments.First(r => r.Id == attachment1.Id); var actualAttachment2 = dbContext.Attachments.First(r => r.Id == attachment2.Id); var actualAttachment3 = dbContext.Attachments.First(r => r.Id == attachment3.Id); AssertIsEqual(updatedAttachment1, actualAttachment1); AssertIsEqual(updatedAttachment2, actualAttachment2); AssertIsEqual(updatedAttachment3, actualAttachment3); } } [Test] public void Update_GivenAttachmentDoesNotExist_ShouldThrowExceptionWhenSaving() { //---------------Set up test pack------------------- var attachment = new AttachmentBuilder() .WithFileName("A.JPG") .WithContent(CreateRandomByteArray(100)) .Build(); using (var wrapper = SpeedySqlFactory.CreateWrapper()) { var dbContext = CreateDbContext(wrapper.Connection); var attachmentsRepository = CreateRepository(dbContext); //---------------Execute Test ---------------------- attachmentsRepository.Update(attachment); var exception = Assert.Throws<DbUpdateConcurrencyException>(() => attachmentsRepository.Save()); //---------------Test Result ----------------------- StringAssert.Contains("Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.", exception.Message); } } private void AssertIsEqual(Attachment expectedAttachment, Attachment actualAttachment) { Assert.AreEqual(expectedAttachment.Id, actualAttachment.Id); Assert.AreEqual(expectedAttachment.FileName, actualAttachment.FileName); } private AttachmentRepository CreateRepository(AttachmentDbContext writeDbContext) { return new AttachmentRepository(writeDbContext); } private AttachmentDbContext CreateDbContext(DbConnection connection) { var connectionString = connection.ConnectionString; var builder = new DbContextOptionsBuilder<AttachmentDbContext>(); builder .UseSqlServer(connectionString) .EnableSensitiveDataLogging(true); return new AttachmentDbContext(builder.Options); } private static byte[] CreateRandomByteArray(int size) { var bytes = new byte[size]; new Random().NextBytes(bytes); return bytes; } } }
using VkApi.Wrapper.Objects; using VkApi.Wrapper.Responses; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace VkApi.Wrapper.Methods { public class Photos { private readonly Vkontakte _vkontakte; internal Photos(Vkontakte vkontakte) => _vkontakte = vkontakte; ///<summary> /// Confirms a tag on a photo. ///</summary> public Task<BaseOkResponse> ConfirmTag(int? ownerId = null, String photoId = null, int? tagId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); if (tagId != null) parameters.Add("tag_id", tagId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.confirmTag", parameters); } ///<summary> /// Allows to copy a photo to the "Saved photos" album ///</summary> public Task<int> Copy(int? ownerId = null, int? photoId = null, String accessKey = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); if (accessKey != null) parameters.Add("access_key", accessKey.ToApiString()); return _vkontakte.RequestAsync<int>("photos.copy", parameters); } ///<summary> /// Creates an empty photo album. ///</summary> public Task<PhotosPhotoAlbumFull> CreateAlbum(String title = null, int? groupId = null, String description = null, String[] privacyView = null, String[] privacyComment = null, Boolean? uploadByAdminsOnly = null, Boolean? commentsDisabled = null) { var parameters = new Dictionary<string, string>(); if (title != null) parameters.Add("title", title.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (description != null) parameters.Add("description", description.ToApiString()); if (privacyView != null) parameters.Add("privacy_view", privacyView.ToApiString()); if (privacyComment != null) parameters.Add("privacy_comment", privacyComment.ToApiString()); if (uploadByAdminsOnly != null) parameters.Add("upload_by_admins_only", uploadByAdminsOnly.ToApiString()); if (commentsDisabled != null) parameters.Add("comments_disabled", commentsDisabled.ToApiString()); return _vkontakte.RequestAsync<PhotosPhotoAlbumFull>("photos.createAlbum", parameters); } ///<summary> /// Adds a new comment on the photo. ///</summary> public Task<int> CreateComment(int? ownerId = null, int? photoId = null, String message = null, String[] attachments = null, Boolean? fromGroup = null, int? replyToComment = null, int? stickerId = null, String accessKey = null, String guid = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); if (message != null) parameters.Add("message", message.ToApiString()); if (attachments != null) parameters.Add("attachments", attachments.ToApiString()); if (fromGroup != null) parameters.Add("from_group", fromGroup.ToApiString()); if (replyToComment != null) parameters.Add("reply_to_comment", replyToComment.ToApiString()); if (stickerId != null) parameters.Add("sticker_id", stickerId.ToApiString()); if (accessKey != null) parameters.Add("access_key", accessKey.ToApiString()); if (guid != null) parameters.Add("guid", guid.ToApiString()); return _vkontakte.RequestAsync<int>("photos.createComment", parameters); } ///<summary> /// Deletes a photo. ///</summary> public Task<BaseOkResponse> Delete(int? ownerId = null, int? photoId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.delete", parameters); } ///<summary> /// Deletes a photo album belonging to the current user. ///</summary> public Task<BaseOkResponse> DeleteAlbum(int? albumId = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.deleteAlbum", parameters); } ///<summary> /// Deletes a comment on the photo. ///</summary> public Task<int> DeleteComment(int? ownerId = null, int? commentId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (commentId != null) parameters.Add("comment_id", commentId.ToApiString()); return _vkontakte.RequestAsync<int>("photos.deleteComment", parameters); } ///<summary> /// Edits the caption of a photo. ///</summary> public Task<BaseOkResponse> Edit(int? ownerId = null, int? photoId = null, String caption = null, double? latitude = null, double? longitude = null, String placeStr = null, String foursquareId = null, Boolean? deletePlace = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); if (caption != null) parameters.Add("caption", caption.ToApiString()); if (latitude != null) parameters.Add("latitude", latitude.ToApiString()); if (longitude != null) parameters.Add("longitude", longitude.ToApiString()); if (placeStr != null) parameters.Add("place_str", placeStr.ToApiString()); if (foursquareId != null) parameters.Add("foursquare_id", foursquareId.ToApiString()); if (deletePlace != null) parameters.Add("delete_place", deletePlace.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.edit", parameters); } ///<summary> /// Edits information about a photo album. ///</summary> public Task<BaseOkResponse> EditAlbum(int? albumId = null, String title = null, String description = null, int? ownerId = null, String[] privacyView = null, String[] privacyComment = null, Boolean? uploadByAdminsOnly = null, Boolean? commentsDisabled = null) { var parameters = new Dictionary<string, string>(); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); if (title != null) parameters.Add("title", title.ToApiString()); if (description != null) parameters.Add("description", description.ToApiString()); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (privacyView != null) parameters.Add("privacy_view", privacyView.ToApiString()); if (privacyComment != null) parameters.Add("privacy_comment", privacyComment.ToApiString()); if (uploadByAdminsOnly != null) parameters.Add("upload_by_admins_only", uploadByAdminsOnly.ToApiString()); if (commentsDisabled != null) parameters.Add("comments_disabled", commentsDisabled.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.editAlbum", parameters); } ///<summary> /// Edits a comment on a photo. ///</summary> public Task<BaseOkResponse> EditComment(int? ownerId = null, int? commentId = null, String message = null, String[] attachments = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (commentId != null) parameters.Add("comment_id", commentId.ToApiString()); if (message != null) parameters.Add("message", message.ToApiString()); if (attachments != null) parameters.Add("attachments", attachments.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.editComment", parameters); } ///<summary> /// Returns a list of a user's or community's photos. ///</summary> public Task<PhotosGetResponse> Get(int? ownerId = null, String albumId = null, String[] photoIds = null, Boolean? rev = null, Boolean? extended = null, String feedType = null, int? feed = null, Boolean? photoSizes = null, int? offset = null, int? count = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); if (photoIds != null) parameters.Add("photo_ids", photoIds.ToApiString()); if (rev != null) parameters.Add("rev", rev.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (feedType != null) parameters.Add("feed_type", feedType.ToApiString()); if (feed != null) parameters.Add("feed", feed.ToApiString()); if (photoSizes != null) parameters.Add("photo_sizes", photoSizes.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); return _vkontakte.RequestAsync<PhotosGetResponse>("photos.get", parameters); } ///<summary> /// Returns a list of a user's or community's photo albums. ///</summary> public Task<PhotosGetAlbumsResponse> GetAlbums(int? ownerId = null, int[] albumIds = null, int? offset = null, int? count = null, Boolean? needSystem = null, Boolean? needCovers = null, Boolean? photoSizes = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (albumIds != null) parameters.Add("album_ids", albumIds.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (needSystem != null) parameters.Add("need_system", needSystem.ToApiString()); if (needCovers != null) parameters.Add("need_covers", needCovers.ToApiString()); if (photoSizes != null) parameters.Add("photo_sizes", photoSizes.ToApiString()); return _vkontakte.RequestAsync<PhotosGetAlbumsResponse>("photos.getAlbums", parameters); } ///<summary> /// Returns the number of photo albums belonging to a user or community. ///</summary> public Task<int> GetAlbumsCount(int? userId = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (userId != null) parameters.Add("user_id", userId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<int>("photos.getAlbumsCount", parameters); } ///<summary> /// Returns a list of photos belonging to a user or community, in reverse chronological order. ///</summary> public Task<PhotosGetAllResponse> GetAll(int? ownerId = null, Boolean? extended = null, int? offset = null, int? count = null, Boolean? photoSizes = null, Boolean? noServiceAlbums = null, Boolean? needHidden = null, Boolean? skipHidden = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (photoSizes != null) parameters.Add("photo_sizes", photoSizes.ToApiString()); if (noServiceAlbums != null) parameters.Add("no_service_albums", noServiceAlbums.ToApiString()); if (needHidden != null) parameters.Add("need_hidden", needHidden.ToApiString()); if (skipHidden != null) parameters.Add("skip_hidden", skipHidden.ToApiString()); return _vkontakte.RequestAsync<PhotosGetAllResponse>("photos.getAll", parameters); } ///<summary> /// Returns a list of comments on a specific photo album or all albums of the user sorted in reverse chronological order. ///</summary> public Task<PhotosGetAllCommentsResponse> GetAllComments(int? ownerId = null, int? albumId = null, Boolean? needLikes = null, int? offset = null, int? count = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); if (needLikes != null) parameters.Add("need_likes", needLikes.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); return _vkontakte.RequestAsync<PhotosGetAllCommentsResponse>("photos.getAllComments", parameters); } ///<summary> /// Returns information about photos by their IDs. ///</summary> public Task<PhotosPhoto[]> GetById(String[] photos = null, Boolean? extended = null, Boolean? photoSizes = null) { var parameters = new Dictionary<string, string>(); if (photos != null) parameters.Add("photos", photos.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (photoSizes != null) parameters.Add("photo_sizes", photoSizes.ToApiString()); return _vkontakte.RequestAsync<PhotosPhoto[]>("photos.getById", parameters); } ///<summary> /// Returns an upload link for chat cover pictures. ///</summary> public Task<BaseUploadServer> GetChatUploadServer(int? chatId = null, int? cropX = null, int? cropY = null, int? cropWidth = null) { var parameters = new Dictionary<string, string>(); if (chatId != null) parameters.Add("chat_id", chatId.ToApiString()); if (cropX != null) parameters.Add("crop_x", cropX.ToApiString()); if (cropY != null) parameters.Add("crop_y", cropY.ToApiString()); if (cropWidth != null) parameters.Add("crop_width", cropWidth.ToApiString()); return _vkontakte.RequestAsync<BaseUploadServer>("photos.getChatUploadServer", parameters); } ///<summary> /// Returns a list of comments on a photo. ///</summary> public Task<PhotosGetCommentsResponse> GetComments(int? ownerId = null, int? photoId = null, Boolean? needLikes = null, int? startCommentId = null, int? offset = null, int? count = null, String sort = null, String accessKey = null, Boolean? extended = null, UsersFields[] fields = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); if (needLikes != null) parameters.Add("need_likes", needLikes.ToApiString()); if (startCommentId != null) parameters.Add("start_comment_id", startCommentId.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (sort != null) parameters.Add("sort", sort.ToApiString()); if (accessKey != null) parameters.Add("access_key", accessKey.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); return _vkontakte.RequestAsync<PhotosGetCommentsResponse>("photos.getComments", parameters); } ///<summary> /// Returns the server address for market album photo upload. ///</summary> public Task<BaseUploadServer> GetMarketAlbumUploadServer(int? groupId = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<BaseUploadServer>("photos.getMarketAlbumUploadServer", parameters); } ///<summary> /// Returns the server address for market photo upload. ///</summary> public Task<BaseUploadServer> GetMarketUploadServer(int? groupId = null, Boolean? mainPhoto = null, int? cropX = null, int? cropY = null, int? cropWidth = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (mainPhoto != null) parameters.Add("main_photo", mainPhoto.ToApiString()); if (cropX != null) parameters.Add("crop_x", cropX.ToApiString()); if (cropY != null) parameters.Add("crop_y", cropY.ToApiString()); if (cropWidth != null) parameters.Add("crop_width", cropWidth.ToApiString()); return _vkontakte.RequestAsync<BaseUploadServer>("photos.getMarketUploadServer", parameters); } ///<summary> /// Returns the server address for photo upload in a private message for a user. ///</summary> public Task<PhotosPhotoUpload> GetMessagesUploadServer(int? peerId = null) { var parameters = new Dictionary<string, string>(); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); return _vkontakte.RequestAsync<PhotosPhotoUpload>("photos.getMessagesUploadServer", parameters); } ///<summary> /// Returns a list of photos with tags that have not been viewed. ///</summary> public Task<PhotosGetNewTagsResponse> GetNewTags(int? offset = null, int? count = null) { var parameters = new Dictionary<string, string>(); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); return _vkontakte.RequestAsync<PhotosGetNewTagsResponse>("photos.getNewTags", parameters); } ///<summary> /// Returns the server address for owner cover upload. ///</summary> public Task<BaseUploadServer> GetOwnerCoverPhotoUploadServer(int? groupId = null, int? cropX = null, int? cropY = null, int? cropX2 = null, int? cropY2 = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (cropX != null) parameters.Add("crop_x", cropX.ToApiString()); if (cropY != null) parameters.Add("crop_y", cropY.ToApiString()); if (cropX2 != null) parameters.Add("crop_x2", cropX2.ToApiString()); if (cropY2 != null) parameters.Add("crop_y2", cropY2.ToApiString()); return _vkontakte.RequestAsync<BaseUploadServer>("photos.getOwnerCoverPhotoUploadServer", parameters); } ///<summary> /// Returns an upload server address for a profile or community photo. ///</summary> public Task<BaseUploadServer> GetOwnerPhotoUploadServer(int? ownerId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); return _vkontakte.RequestAsync<BaseUploadServer>("photos.getOwnerPhotoUploadServer", parameters); } ///<summary> /// Returns a list of tags on a photo. ///</summary> public Task<PhotosPhotoTag[]> GetTags(int? ownerId = null, int? photoId = null, String accessKey = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); if (accessKey != null) parameters.Add("access_key", accessKey.ToApiString()); return _vkontakte.RequestAsync<PhotosPhotoTag[]>("photos.getTags", parameters); } ///<summary> /// Returns the server address for photo upload. ///</summary> public Task<PhotosPhotoUpload> GetUploadServer(int? groupId = null, int? albumId = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); return _vkontakte.RequestAsync<PhotosPhotoUpload>("photos.getUploadServer", parameters); } ///<summary> /// Returns a list of photos in which a user is tagged. ///</summary> public Task<PhotosGetUserPhotosResponse> GetUserPhotos(int? userId = null, int? offset = null, int? count = null, Boolean? extended = null, String sort = null) { var parameters = new Dictionary<string, string>(); if (userId != null) parameters.Add("user_id", userId.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (sort != null) parameters.Add("sort", sort.ToApiString()); return _vkontakte.RequestAsync<PhotosGetUserPhotosResponse>("photos.getUserPhotos", parameters); } ///<summary> /// Returns the server address for photo upload onto a user's wall. ///</summary> public Task<PhotosPhotoUpload> GetWallUploadServer(int? groupId = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<PhotosPhotoUpload>("photos.getWallUploadServer", parameters); } ///<summary> /// Makes a photo into an album cover. ///</summary> public Task<BaseOkResponse> MakeCover(int? ownerId = null, int? photoId = null, int? albumId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.makeCover", parameters); } ///<summary> /// Moves a photo from one album to another. ///</summary> public Task<BaseOkResponse> Move(int? ownerId = null, int? targetAlbumId = null, int? photoId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (targetAlbumId != null) parameters.Add("target_album_id", targetAlbumId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.move", parameters); } ///<summary> /// Adds a tag on the photo. ///</summary> public Task<int> PutTag(int? ownerId = null, int? photoId = null, int? userId = null, double? x = null, double? y = null, double? x2 = null, double? y2 = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); if (userId != null) parameters.Add("user_id", userId.ToApiString()); if (x != null) parameters.Add("x", x.ToApiString()); if (y != null) parameters.Add("y", y.ToApiString()); if (x2 != null) parameters.Add("x2", x2.ToApiString()); if (y2 != null) parameters.Add("y2", y2.ToApiString()); return _vkontakte.RequestAsync<int>("photos.putTag", parameters); } ///<summary> /// Removes a tag from a photo. ///</summary> public Task<BaseOkResponse> RemoveTag(int? ownerId = null, int? photoId = null, int? tagId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); if (tagId != null) parameters.Add("tag_id", tagId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.removeTag", parameters); } ///<summary> /// Reorders the album in the list of user albums. ///</summary> public Task<BaseOkResponse> ReorderAlbums(int? ownerId = null, int? albumId = null, int? before = null, int? after = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); if (before != null) parameters.Add("before", before.ToApiString()); if (after != null) parameters.Add("after", after.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.reorderAlbums", parameters); } ///<summary> /// Reorders the photo in the list of photos of the user album. ///</summary> public Task<BaseOkResponse> ReorderPhotos(int? ownerId = null, int? photoId = null, int? before = null, int? after = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); if (before != null) parameters.Add("before", before.ToApiString()); if (after != null) parameters.Add("after", after.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.reorderPhotos", parameters); } ///<summary> /// Reports (submits a complaint about) a photo. ///</summary> public Task<BaseOkResponse> Report(int? ownerId = null, int? photoId = null, int? reason = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); if (reason != null) parameters.Add("reason", reason.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.report", parameters); } ///<summary> /// Reports (submits a complaint about) a comment on a photo. ///</summary> public Task<BaseOkResponse> ReportComment(int? ownerId = null, int? commentId = null, int? reason = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (commentId != null) parameters.Add("comment_id", commentId.ToApiString()); if (reason != null) parameters.Add("reason", reason.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.reportComment", parameters); } ///<summary> /// Restores a deleted photo. ///</summary> public Task<BaseOkResponse> Restore(int? ownerId = null, int? photoId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (photoId != null) parameters.Add("photo_id", photoId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("photos.restore", parameters); } ///<summary> /// Restores a deleted comment on a photo. ///</summary> public Task<int> RestoreComment(int? ownerId = null, int? commentId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (commentId != null) parameters.Add("comment_id", commentId.ToApiString()); return _vkontakte.RequestAsync<int>("photos.restoreComment", parameters); } ///<summary> /// Saves photos after successful uploading. ///</summary> public Task<PhotosPhoto[]> Save(int? albumId = null, int? groupId = null, int? server = null, String photosList = null, String hash = null, double? latitude = null, double? longitude = null, String caption = null) { var parameters = new Dictionary<string, string>(); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (server != null) parameters.Add("server", server.ToApiString()); if (photosList != null) parameters.Add("photos_list", photosList.ToApiString()); if (hash != null) parameters.Add("hash", hash.ToApiString()); if (latitude != null) parameters.Add("latitude", latitude.ToApiString()); if (longitude != null) parameters.Add("longitude", longitude.ToApiString()); if (caption != null) parameters.Add("caption", caption.ToApiString()); return _vkontakte.RequestAsync<PhotosPhoto[]>("photos.save", parameters); } ///<summary> /// Saves market album photos after successful uploading. ///</summary> public Task<PhotosPhoto[]> SaveMarketAlbumPhoto(int? groupId = null, String photo = null, int? server = null, String hash = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (photo != null) parameters.Add("photo", photo.ToApiString()); if (server != null) parameters.Add("server", server.ToApiString()); if (hash != null) parameters.Add("hash", hash.ToApiString()); return _vkontakte.RequestAsync<PhotosPhoto[]>("photos.saveMarketAlbumPhoto", parameters); } ///<summary> /// Saves market photos after successful uploading. ///</summary> public Task<PhotosPhoto[]> SaveMarketPhoto(int? groupId = null, String photo = null, int? server = null, String hash = null, String cropData = null, String cropHash = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (photo != null) parameters.Add("photo", photo.ToApiString()); if (server != null) parameters.Add("server", server.ToApiString()); if (hash != null) parameters.Add("hash", hash.ToApiString()); if (cropData != null) parameters.Add("crop_data", cropData.ToApiString()); if (cropHash != null) parameters.Add("crop_hash", cropHash.ToApiString()); return _vkontakte.RequestAsync<PhotosPhoto[]>("photos.saveMarketPhoto", parameters); } ///<summary> /// Saves a photo after being successfully uploaded. URL obtained with [vk.com/dev/photos.getMessagesUploadServer|photos.getMessagesUploadServer] method. ///</summary> public Task<PhotosPhoto[]> SaveMessagesPhoto(String photo = null, int? server = null, String hash = null) { var parameters = new Dictionary<string, string>(); if (photo != null) parameters.Add("photo", photo.ToApiString()); if (server != null) parameters.Add("server", server.ToApiString()); if (hash != null) parameters.Add("hash", hash.ToApiString()); return _vkontakte.RequestAsync<PhotosPhoto[]>("photos.saveMessagesPhoto", parameters); } ///<summary> /// Saves cover photo after successful uploading. ///</summary> public Task<BaseImage[]> SaveOwnerCoverPhoto(String hash = null, String photo = null) { var parameters = new Dictionary<string, string>(); if (hash != null) parameters.Add("hash", hash.ToApiString()); if (photo != null) parameters.Add("photo", photo.ToApiString()); return _vkontakte.RequestAsync<BaseImage[]>("photos.saveOwnerCoverPhoto", parameters); } ///<summary> /// Saves a profile or community photo. Upload URL can be got with the [vk.com/dev/photos.getOwnerPhotoUploadServer|photos.getOwnerPhotoUploadServer] method. ///</summary> public Task<PhotosSaveOwnerPhotoResponse> SaveOwnerPhoto(String server = null, String hash = null, String photo = null) { var parameters = new Dictionary<string, string>(); if (server != null) parameters.Add("server", server.ToApiString()); if (hash != null) parameters.Add("hash", hash.ToApiString()); if (photo != null) parameters.Add("photo", photo.ToApiString()); return _vkontakte.RequestAsync<PhotosSaveOwnerPhotoResponse>("photos.saveOwnerPhoto", parameters); } ///<summary> /// Saves a photo to a user's or community's wall after being uploaded. ///</summary> public Task<PhotosPhoto[]> SaveWallPhoto(int? userId = null, int? groupId = null, String photo = null, int? server = null, String hash = null, double? latitude = null, double? longitude = null, String caption = null) { var parameters = new Dictionary<string, string>(); if (userId != null) parameters.Add("user_id", userId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (photo != null) parameters.Add("photo", photo.ToApiString()); if (server != null) parameters.Add("server", server.ToApiString()); if (hash != null) parameters.Add("hash", hash.ToApiString()); if (latitude != null) parameters.Add("latitude", latitude.ToApiString()); if (longitude != null) parameters.Add("longitude", longitude.ToApiString()); if (caption != null) parameters.Add("caption", caption.ToApiString()); return _vkontakte.RequestAsync<PhotosPhoto[]>("photos.saveWallPhoto", parameters); } ///<summary> /// Returns a list of photos. ///</summary> public Task<PhotosSearchResponse> Search(String q = null, double? lat = null, double? @long = null, int? startTime = null, int? endTime = null, int? sort = null, int? offset = null, int? count = null, int? radius = null) { var parameters = new Dictionary<string, string>(); if (q != null) parameters.Add("q", q.ToApiString()); if (lat != null) parameters.Add("lat", lat.ToApiString()); if (@long != null) parameters.Add("long", @long.ToApiString()); if (startTime != null) parameters.Add("start_time", startTime.ToApiString()); if (endTime != null) parameters.Add("end_time", endTime.ToApiString()); if (sort != null) parameters.Add("sort", sort.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (radius != null) parameters.Add("radius", radius.ToApiString()); return _vkontakte.RequestAsync<PhotosSearchResponse>("photos.search", parameters); } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System.Collections.Generic; using Encog.ML.Data; using Encog.Util; namespace Encog.ML.HMM.Alog { /// <summary> /// The forward-backward algorithm is an inference algorithm for hidden Markov /// models which computes the posterior marginals of all hidden state variables /// given a sequence of observations. /// </summary> public class ForwardBackwardCalculator { /// <summary> /// Alpha matrix. /// </summary> protected double[][] Alpha; /// <summary> /// Beta matrix. /// </summary> protected double[][] Beta; /// <summary> /// Probability. /// </summary> protected double probability; /// <summary> /// Construct an empty object. /// </summary> protected ForwardBackwardCalculator() { } /// <summary> /// Construct the forward/backward calculator. /// </summary> /// <param name="oseq">The sequence to use.</param> /// <param name="hmm">THe hidden markov model to use.</param> public ForwardBackwardCalculator(IMLDataSet oseq, HiddenMarkovModel hmm) : this(oseq, hmm, true, false) { } /// <summary> /// Construct the object. /// </summary> /// <param name="oseq">The sequence.</param> /// <param name="hmm">The hidden markov model to use.</param> /// <param name="doAlpha">Do alpha?</param> /// <param name="doBeta">Do beta?</param> public ForwardBackwardCalculator(IMLDataSet oseq, HiddenMarkovModel hmm, bool doAlpha, bool doBeta) { if (oseq.Count < 1) { throw new EncogError("Empty sequence"); } if (doAlpha) { ComputeAlpha(hmm, oseq); } if (doBeta) { ComputeBeta(hmm, oseq); } ComputeProbability(oseq, hmm, doAlpha, doBeta); } /// <summary> /// Alpha element. /// </summary> /// <param name="t">The row.</param> /// <param name="i">The column.</param> /// <returns>The element.</returns> public double AlphaElement(int t, int i) { if (Alpha == null) { throw new EncogError("Alpha array has not " + "been computed"); } return Alpha[t][i]; } /// <summary> /// Beta element, best element. /// </summary> /// <param name="t">From.</param> /// <param name="i">To.</param> /// <returns>The element.</returns> public double BetaElement(int t, int i) { if (Beta == null) { throw new EncogError("Beta array has not " + "been computed"); } return Beta[t][i]; } /// <summary> /// Compute alpha. /// </summary> /// <param name="hmm">The hidden markov model.</param> /// <param name="oseq">The sequence.</param> protected void ComputeAlpha(HiddenMarkovModel hmm, IMLDataSet oseq) { Alpha = EngineArray.AllocateDouble2D((int) oseq.Count, hmm.StateCount); for (int i = 0; i < hmm.StateCount; i++) { ComputeAlphaInit(hmm, oseq[0], i); } IEnumerator<IMLDataPair> seqIterator = oseq.GetEnumerator(); if (seqIterator.MoveNext()) { for (int t = 1; t < oseq.Count; t++) { seqIterator.MoveNext(); ///// IMLDataPair observation = seqIterator.Current; for (int i = 0; i < hmm.StateCount; i++) { ComputeAlphaStep(hmm, observation, t, i); } } } } /// <summary> /// Compute the alpha init. /// </summary> /// <param name="hmm">THe hidden markov model.</param> /// <param name="o">The element.</param> /// <param name="i">The state.</param> protected void ComputeAlphaInit(HiddenMarkovModel hmm, IMLDataPair o, int i) { Alpha[0][i] = hmm.GetPi(i) *hmm.StateDistributions[i].Probability(o); } /// <summary> /// Compute the alpha step. /// </summary> /// <param name="hmm">The hidden markov model.</param> /// <param name="o">The sequence element.</param> /// <param name="t">The alpha step.</param> /// <param name="j">The column.</param> protected void ComputeAlphaStep(HiddenMarkovModel hmm, IMLDataPair o, int t, int j) { double sum = 0.0; for (int i = 0; i < hmm.StateCount; i++) { sum += Alpha[t - 1][i]*hmm.TransitionProbability[i][j]; } Alpha[t][j] = sum*hmm.StateDistributions[j].Probability(o); } /// <summary> /// Compute the beta step. /// </summary> /// <param name="hmm">The hidden markov model.</param> /// <param name="oseq">The sequence.</param> protected void ComputeBeta(HiddenMarkovModel hmm, IMLDataSet oseq) { Beta = EngineArray.AllocateDouble2D((int) oseq.Count, hmm.StateCount); for (int i = 0; i < hmm.StateCount; i++) { Beta[oseq.Count - 1][i] = 1.0; } for (var t = (int) (oseq.Count - 2); t >= 0; t--) { for (int i = 0; i < hmm.StateCount; i++) { ComputeBetaStep(hmm, oseq[t + 1], t, i); } } } /// <summary> /// Compute the beta step. /// </summary> /// <param name="hmm">The hidden markov model.</param> /// <param name="o">THe data par to compute.</param> /// <param name="t">THe matrix row.</param> /// <param name="i">THe matrix column.</param> protected void ComputeBetaStep(HiddenMarkovModel hmm, IMLDataPair o, int t, int i) { double sum = 0.0; for (int j = 0; j < hmm.StateCount; j++) { sum += Beta[t + 1][j]*hmm.TransitionProbability[i][j] *hmm.StateDistributions[j].Probability(o); } Beta[t][i] = sum; } /// <summary> /// Compute the probability. /// </summary> /// <param name="oseq">The sequence.</param> /// <param name="hmm">THe hidden markov model.</param> /// <param name="doAlpha">Perform alpha step?</param> /// <param name="doBeta">Perform beta step?</param> private void ComputeProbability(IMLDataSet oseq, HiddenMarkovModel hmm, bool doAlpha, bool doBeta) { probability = 0.0; if (doAlpha) { for (int i = 0; i < hmm.StateCount; i++) { probability += Alpha[oseq.Count - 1][i]; } } else { for (int i = 0; i < hmm.StateCount; i++) { probability += hmm.GetPi(i) *hmm.StateDistributions[i].Probability(oseq[0]) *Beta[0][i]; } } } /// <summary> /// The probability. /// </summary> /// <returns>The probability.</returns> public double Probability() { return probability; } } }
// Copyright 2007-2015 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 MassTransit.Transports.InMemory { using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Logging; using Pipeline; using Util; /// <summary> /// Support in-memory message queue that is not durable, but supports parallel delivery of messages /// based on TPL usage. /// </summary> public class InMemoryTransport : IReceiveTransport, ISendTransport, IDisposable { static readonly ILog _log = Logger.Get<InMemoryTransport>(); readonly ReceiveEndpointObservable _endpointObservable; readonly Uri _inputAddress; readonly ITaskParticipant _participant; readonly ReceiveObservable _receiveObservable; readonly LimitedConcurrencyLevelTaskScheduler _scheduler; readonly SendObservable _sendObservable; readonly TaskSupervisor _supervisor; int _currentPendingDeliveryCount; long _deliveryCount; int _maxPendingDeliveryCount; IPipe<ReceiveContext> _receivePipe; public InMemoryTransport(Uri inputAddress, int concurrencyLimit) { _inputAddress = inputAddress; _sendObservable = new SendObservable(); _receiveObservable = new ReceiveObservable(); _endpointObservable = new ReceiveEndpointObservable(); _supervisor = new TaskSupervisor($"{TypeMetadataCache<InMemoryTransport>.ShortName} - {_inputAddress}"); _participant = _supervisor.CreateParticipant($"{TypeMetadataCache<InMemoryTransport>.ShortName} - {_inputAddress}"); _scheduler = new LimitedConcurrencyLevelTaskScheduler(concurrencyLimit); } public void Dispose() { _participant.SetComplete(); TaskUtil.Await(() => _supervisor.Stop("Disposed")); TaskUtil.Await(() => _supervisor.Completed); } public void Probe(ProbeContext context) { var scope = context.CreateScope("transport"); scope.Set(new { Address = _inputAddress }); } ReceiveTransportHandle IReceiveTransport.Start(IPipe<ReceiveContext> receivePipe) { try { _receivePipe = receivePipe; TaskUtil.Await(() => _endpointObservable.Ready(new Ready(_inputAddress))); _participant.SetReady(); return new Handle(_supervisor, _participant, this); } catch (Exception exception) { _participant.SetNotReady(exception); throw; } } public ConnectHandle ConnectReceiveObserver(IReceiveObserver observer) { return _receiveObservable.Connect(observer); } public ConnectHandle ConnectReceiveEndpointObserver(IReceiveEndpointObserver observer) { return _endpointObservable.Connect(observer); } async Task ISendTransport.Send<T>(T message, IPipe<SendContext<T>> pipe, CancellationToken cancelSend) { var context = new InMemorySendContext<T>(message, cancelSend); try { await pipe.Send(context).ConfigureAwait(false); var messageId = context.MessageId ?? NewId.NextGuid(); await _sendObservable.PreSend(context).ConfigureAwait(false); var transportMessage = new InMemoryTransportMessage(messageId, context.Body, context.ContentType.MediaType, TypeMetadataCache<T>.ShortName); #pragma warning disable 4014 Task.Factory.StartNew(() => DispatchMessage(transportMessage), _supervisor.StoppedToken, TaskCreationOptions.HideScheduler, _scheduler); #pragma warning restore 4014 context.DestinationAddress.LogSent(context.MessageId?.ToString("N") ?? "", TypeMetadataCache<T>.ShortName); await _sendObservable.PostSend(context).ConfigureAwait(false); } catch (Exception ex) { _log.Error($"SEND FAULT: {_inputAddress} {context.MessageId} {TypeMetadataCache<T>.ShortName}", ex); await _sendObservable.SendFault(context, ex).ConfigureAwait(false); throw; } } async Task ISendTransport.Move(ReceiveContext context, IPipe<SendContext> pipe) { var messageId = GetMessageId(context); byte[] body; using (var bodyStream = context.GetBody()) { body = await GetMessageBody(bodyStream).ConfigureAwait(false); } var messageType = "Unknown"; InMemoryTransportMessage receivedMessage; if (context.TryGetPayload(out receivedMessage)) messageType = receivedMessage.MessageType; var transportMessage = new InMemoryTransportMessage(messageId, body, context.ContentType.MediaType, messageType); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Factory.StartNew(() => DispatchMessage(transportMessage), _supervisor.StoppedToken, TaskCreationOptions.HideScheduler, _scheduler); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } Task ISendTransport.Close() { // an in-memory send transport does not get disposed return TaskUtil.Completed; } public ConnectHandle ConnectSendObserver(ISendObserver observer) { return _sendObservable.Connect(observer); } async Task DispatchMessage(InMemoryTransportMessage message) { await _supervisor.Ready.ConfigureAwait(false); if (_supervisor.StoppedToken.IsCancellationRequested) return; if (_receivePipe == null) throw new ArgumentException("ReceivePipe not configured"); var context = new InMemoryReceiveContext(_inputAddress, message, _receiveObservable); Interlocked.Increment(ref _deliveryCount); var current = Interlocked.Increment(ref _currentPendingDeliveryCount); while (current > _maxPendingDeliveryCount) Interlocked.CompareExchange(ref _maxPendingDeliveryCount, current, _maxPendingDeliveryCount); try { await _receiveObservable.PreReceive(context).ConfigureAwait(false); await _receivePipe.Send(context).ConfigureAwait(false); await context.CompleteTask.ConfigureAwait(false); await _receiveObservable.PostReceive(context).ConfigureAwait(false); _inputAddress.LogReceived(message.MessageId.ToString("N"), message.MessageType); } catch (Exception ex) { _log.Error($"RCV FAULT: {message.MessageId}", ex); await _receiveObservable.ReceiveFault(context, ex).ConfigureAwait(false); message.DeliveryCount++; } finally { Interlocked.Decrement(ref _currentPendingDeliveryCount); } } async Task<byte[]> GetMessageBody(Stream body) { using (var ms = new MemoryStream()) { await body.CopyToAsync(ms).ConfigureAwait(false); return ms.ToArray(); } } static Guid GetMessageId(ReceiveContext context) { object messageIdValue; return context.TransportHeaders.TryGetHeader("MessageId", out messageIdValue) ? new Guid(messageIdValue.ToString()) : NewId.NextGuid(); } class Handle : ReceiveTransportHandle { readonly ITaskParticipant _participant; readonly TaskSupervisor _supervisor; readonly InMemoryTransport _transport; public Handle(TaskSupervisor supervisor, ITaskParticipant participant, InMemoryTransport transport) { _supervisor = supervisor; _participant = participant; _transport = transport; } async Task ReceiveTransportHandle.Stop(CancellationToken cancellationToken) { _participant.SetComplete(); await _supervisor.Stop("Stopped", cancellationToken).ConfigureAwait(false); await _supervisor.Completed.ConfigureAwait(false); await _transport._endpointObservable.Completed(new Completed(_transport._inputAddress, _transport._deliveryCount, _transport._maxPendingDeliveryCount)).ConfigureAwait(false); } } class Ready : ReceiveEndpointReady { public Ready(Uri inputAddress) { InputAddress = inputAddress; } public Uri InputAddress { get; } } class Completed : ReceiveEndpointCompleted { public Completed(Uri inputAddress, long deliveryCount, long concurrentDeliveryCount) { InputAddress = inputAddress; DeliveryCount = deliveryCount; ConcurrentDeliveryCount = concurrentDeliveryCount; } public Uri InputAddress { get; } public long DeliveryCount { get; } public long ConcurrentDeliveryCount { get; } } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate; using System; using System.Collections.Generic; using Windows.Foundation; using Windows.UI; using Windows.UI.Core; using Windows.UI.Input.Inking; using Windows.UI.Input.Inking.Analysis; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Shapes; namespace SDKTemplate { /// <summary> /// This scenerio demostrates how to do shape recognition with InkAanlyzer. /// </summary> public sealed partial class Scenario1 : Page { private MainPage rootPage = MainPage.Current; InkPresenter inkPresenter; InkAnalyzer inkAnalyzer; DispatcherTimer dispatcherTimer; public Scenario1() { this.InitializeComponent(); inkPresenter = inkCanvas.InkPresenter; inkPresenter.StrokesCollected += InkPresenter_StrokesCollected; inkPresenter.StrokesErased += InkPresenter_StrokesErased; inkPresenter.StrokeInput.StrokeStarted += StrokeInput_StrokeStarted; inkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Touch; inkAnalyzer = new InkAnalyzer(); dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Tick += DispatcherTimer_Tick; // We perform analysis when there has been a change to the // ink presenter and the user has been idle for 200ms. dispatcherTimer.Interval = TimeSpan.FromMilliseconds(200); } protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; } protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { dispatcherTimer.Stop(); } private void StrokeInput_StrokeStarted(InkStrokeInput sender, PointerEventArgs args) { // Don't perform analysis while a stroke is in progress. dispatcherTimer.Stop(); } private void ClearButton_Click(object sender, RoutedEventArgs e) { // Don't run analysis when there is nothing to analyze. dispatcherTimer.Stop(); inkPresenter.StrokeContainer.Clear(); inkAnalyzer.ClearDataForAllStrokes(); canvas.Children.Clear(); } private void InkPresenter_StrokesCollected(InkPresenter sender, InkStrokesCollectedEventArgs args) { dispatcherTimer.Stop(); inkAnalyzer.AddDataForStrokes(args.Strokes); dispatcherTimer.Start(); } private void InkPresenter_StrokesErased(InkPresenter sender, InkStrokesErasedEventArgs args) { dispatcherTimer.Stop(); foreach (var stroke in args.Strokes) { inkAnalyzer.RemoveDataForStroke(stroke.Id); } dispatcherTimer.Start(); } private async void DispatcherTimer_Tick(object sender, object e) { dispatcherTimer.Stop(); if (!inkAnalyzer.IsAnalyzing) { InkAnalysisResult results = await inkAnalyzer.AnalyzeAsync(); if (results.Status == InkAnalysisStatus.Updated) { ConvertShapes(); } } else { // Ink analyzer is busy. Wait a while and try again. dispatcherTimer.Start(); } } private void ConvertShapes() { IReadOnlyList<IInkAnalysisNode> drawings = inkAnalyzer.AnalysisRoot.FindNodes(InkAnalysisNodeKind.InkDrawing); foreach (IInkAnalysisNode drawing in drawings) { var shape = (InkAnalysisInkDrawing)drawing; if (shape.DrawingKind == InkAnalysisDrawingKind.Drawing) { // Omit unsupported shape continue; } if (shape.DrawingKind == InkAnalysisDrawingKind.Circle || shape.DrawingKind == InkAnalysisDrawingKind.Ellipse) { // Create a Circle or Ellipse on the canvas. AddEllipseToCanvas(shape); } else { // Create a Polygon on the canvas. AddPolygonToCanvas(shape); } // Select the strokes that were recognized, so we can delete them. // The effect is that the shape added to the canvas replaces the strokes. foreach (var strokeId in shape.GetStrokeIds()) { InkStroke stroke = inkPresenter.StrokeContainer.GetStrokeById(strokeId); stroke.Selected = true; } // Remove the recognized strokes from the analyzer // so it won't re-analyze them. inkAnalyzer.RemoveDataForStrokes(shape.GetStrokeIds()); } inkPresenter.StrokeContainer.DeleteSelected(); } private void AddPolygonToCanvas(InkAnalysisInkDrawing shape) { Polygon polygon = new Polygon(); // The points of the polygon are reported clockwise. foreach (var point in shape.Points) { polygon.Points.Add(point); } canvas.Children.Add(polygon); } static double Distance(Point p0, Point p1) { double dX = p1.X - p0.X; double dY = p1.Y - p0.Y; return Math.Sqrt(dX * dX + dY * dY); } private void AddEllipseToCanvas(InkAnalysisInkDrawing shape) { Ellipse ellipse = new Ellipse(); // Ellipses and circles are reported as four points // in clockwise orientation. // Points 0 and 2 are the extrema of one axis, // and points 1 and 3 are the extrema of the other axis. // See Ellipse.svg for a diagram. IReadOnlyList<Point> points = shape.Points; // Calculate the geometric center of the ellipse. var center = new Point((points[0].X + points[2].X) / 2.0, (points[0].Y + points[2].Y) / 2.0); // Calculate the length of one axis. ellipse.Width = Distance(points[0], points[2]); var compositeTransform = new CompositeTransform(); if(shape.DrawingKind == InkAnalysisDrawingKind.Circle) { ellipse.Height = ellipse.Width; } else { // Calculate the length of the other axis. ellipse.Height = Distance(points[1], points[3]); // Calculate the amount by which the ellipse has been rotated // by looking at the angle our "width" axis has been rotated. // Since the Y coordinate is inverted, this calculates the amount // by which the ellipse has been rotated clockwise. double rotationAngle = Math.Atan2(points[2].Y - points[0].Y, points[2].X - points[0].X); RotateTransform rotateTransform = new RotateTransform(); // Convert radians to degrees. compositeTransform.Rotation = rotationAngle * 180.0 / Math.PI; compositeTransform.CenterX = ellipse.Width / 2.0; compositeTransform.CenterY = ellipse.Height / 2.0; } compositeTransform.TranslateX = center.X - ellipse.Width / 2.0; compositeTransform.TranslateY = center.Y - ellipse.Height / 2.0; ellipse.RenderTransform = compositeTransform; canvas.Children.Add(ellipse); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Commencement.Controllers.Filters; using Commencement.Controllers.Services; using Commencement.Controllers.ViewModels; using Commencement.Core.Domain; using UCDArch.Core.PersistanceSupport; using UCDArch.Core.Utils; using UCDArch.Web.ActionResults; using UCDArch.Web.Helpers; using MvcContrib; namespace Commencement.Controllers { [AnyoneWithRole] public class CeremonyController : ApplicationController { private readonly IRepositoryWithTypedId<TermCode, string> _termRepository; private readonly IRepositoryWithTypedId<vTermCode, string> _vTermRepository; private readonly IRepositoryWithTypedId<College, string> _collegeRepository; private readonly IMajorService _majorService; private readonly ICeremonyService _ceremonyService; private readonly IUserService _userService; public CeremonyController(IRepositoryWithTypedId<TermCode, string> termRepository, IRepositoryWithTypedId<vTermCode, string> vTermRepository, IRepositoryWithTypedId<College, string> collegeRepository, IMajorService majorService, ICeremonyService ceremonyService, IUserService userService) { _termRepository = termRepository; _vTermRepository = vTermRepository; _collegeRepository = collegeRepository; _majorService = majorService; _ceremonyService = ceremonyService; _userService = userService; } // // GET: /Commencement/ public ActionResult Index() { var viewModel = CommencementViewModel.Create(Repository, _ceremonyService, User.Identity.Name); if (User.IsInRole(Role.Codes.System)) { viewModel.Ceremonies = Repository.OfType<Ceremony>().GetAll(); } return View(viewModel); } public ActionResult Create() { var viewModel = CeremonyViewModel.Create(Repository, User, _majorService, new Ceremony()); return View(viewModel); } [HttpPost] [ValidateInput(false)] public ActionResult Create(CeremonyEditModel ceremonyEditModel) { ModelState.Clear(); if (string.IsNullOrEmpty(ceremonyEditModel.Term)) { ModelState.AddModelError("Term Code", "Term code must be selected."); } var termCode = _termRepository.GetNullableById(ceremonyEditModel.Term); if (termCode == null && !string.IsNullOrEmpty(ceremonyEditModel.Term)) { // term code doesn't exist, create a new one var vTermCode = _vTermRepository.GetNullableById(ceremonyEditModel.Term); termCode = new TermCode(vTermCode); } Ceremony ceremony = new Ceremony(); CopyCeremony(ceremony, ceremonyEditModel.Ceremony, ceremonyEditModel.CeremonyMajors, ceremonyEditModel.Colleges, ceremonyEditModel.TicketDistributionMethods); ceremony.TermCode = termCode; ceremony.AddEditor(_userService.GetCurrentUser(User), true); // fix the time on the end dates, so it ends on ceremony.TransferValidationMessagesTo(ModelState); if (ModelState.IsValid) { // save _termRepository.EnsurePersistent(termCode, true); Repository.OfType<Ceremony>().EnsurePersistent(ceremony); TermService.UpdateCurrent(termCode); // update the cache. // null out the current list of ceremonies the user has access to _ceremonyService.ResetUserCeremonies(); // display a message Message = "Ceremony has been created."; // redirect to the list return this.RedirectToAction(a => a.Edit(ceremony.Id)); } // redirect back to the page var viewModel = CeremonyViewModel.Create(Repository, User, _majorService, ceremony); viewModel.Ceremony = ceremony; return View(viewModel); } public ActionResult Edit(int id) { var ceremony = Repository.OfType<Ceremony>().GetNullableById(id); if (ceremony == null) { Message = "Unable to find ceremony."; return this.RedirectToAction(a => a.Index()); } if (!ceremony.IsEditor(User.Identity.Name) && !User.IsInRole(Role.Codes.System)) { Message = "You do not have permission to edit selected ceremony."; return this.RedirectToAction(a => a.Index()); } var viewModel = CeremonyViewModel.Create(Repository, User, _majorService, ceremony); return View(viewModel); } [HttpPost] [ValidateInput(false)] public ActionResult Edit(CeremonyEditModel ceremonyEditModel) { Check.Require(ceremonyEditModel.Ceremony != null, "Ceremony cannot be null."); //Check.Require(!ceremonyEditModel.id.HasValue, "Ceremony Id is required."); var destCeremony = Repository.OfType<Ceremony>().GetNullableById(ceremonyEditModel.id.Value); if (ceremonyEditModel.Ceremony == null) return this.RedirectToAction(a => a.Index()); if (!destCeremony.IsEditor(User.Identity.Name)) { Message = "You do not have permission to edit selected ceremony."; return this.RedirectToAction(a => a.Index()); } // update the term var termCode = _termRepository.GetNullableById(ceremonyEditModel.Term); destCeremony.TermCode = termCode; // copy all the fields CopyCeremony(destCeremony, ceremonyEditModel.Ceremony, ceremonyEditModel.CeremonyMajors, ceremonyEditModel.Colleges, ceremonyEditModel.TicketDistributionMethods); ModelState.Clear(); // validate the ceremony destCeremony.TransferValidationMessagesTo(ModelState); if (ModelState.IsValid) { Repository.OfType<Ceremony>().EnsurePersistent(destCeremony); _ceremonyService.ResetUserCeremonies(); return this.RedirectToAction(a => a.Index()); } var viewModel = CeremonyViewModel.Create(Repository, User, _majorService, destCeremony); return View(viewModel); } public ActionResult CanceledRegistrations(int id) { var model = new CanceledRegistrationsViewModel(); model.Ceremony = Repository.OfType<Ceremony>().GetNullableById(id); if (model.Ceremony == null) { Message = "Unable to find ceremony."; return this.RedirectToAction(a => a.Index()); } model.CancelledRegistrations = Repository.OfType<vCancelledRegistrations>().Queryable.Where(a => a.CeremonyId == id).ToList(); return View(model); } public ActionResult EditPermissions(int id) { var ceremony = Repository.OfType<Ceremony>().GetNullableById(id); if (ceremony == null) return this.RedirectToAction(a => a.Index()); if (!ceremony.IsEditor(User.Identity.Name) && !User.IsInRole(Role.Codes.System)) { Message = "You do not have permission to edit selected ceremony."; return this.RedirectToAction(a => a.Index()); } return View(ceremony); } [HttpPost] public ActionResult RemoveEditor(int id, int ceremonyEditorId) { var editor = Repository.OfType<CeremonyEditor>().GetNullableById(ceremonyEditorId); if (editor == null || editor.Owner) { Message = "Editor cannot be removed."; } else { Repository.OfType<CeremonyEditor>().Remove(editor); } return this.RedirectToAction(a => a.EditPermissions(id)); } public ActionResult AddEditor(int id) { var ceremony = Repository.OfType<Ceremony>().GetNullableById(id); if (ceremony == null) return this.RedirectToAction(a => a.Index()); var viewModel = AddEditorViewModel.Create(Repository, ceremony); return View(viewModel); } [HttpPost] public ActionResult AddEditor(int id, int? userId) { var ceremony = Repository.OfType<Ceremony>().GetNullableById(id); if (!userId.HasValue) { Message = "User is required."; return View(AddEditorViewModel.Create(Repository, ceremony)); } var user = Repository.OfType<vUser>().GetNullableById(userId.Value); if (ceremony == null) return this.RedirectToAction(a => a.Index()); if (user == null) { Message = "User is required."; return View(AddEditorViewModel.Create(Repository, ceremony)); } if (ceremony.Editors.Where(a=>a.User == user).Any()) { Message = "User is already an editor"; return View(AddEditorViewModel.Create(Repository, ceremony)); } ceremony.AddEditor(user, false); Repository.OfType<Ceremony>().EnsurePersistent(ceremony); return this.RedirectToAction(a => a.EditPermissions(id)); } /// <summary> /// Ajax method for returning majors by college /// </summary> /// <param name="colleges"></param> /// <returns></returns> public JsonNetResult GetMajors(string[] colleges) { if (colleges == null) return new JsonNetResult(); var colls = new List<College>(); // get the colleges foreach (var college in colleges) { colls.Add(_collegeRepository.GetById(college)); } return new JsonNetResult(_majorService.GetByCollege(colls).Select(a => new { Id = a.Id, Name = a.Name })); } #region Helper Methods private void MergeCeremonyMajors (IList<MajorCode> destMajors, IList<MajorCode> srcMajors, IList<College> srcColleges) { destMajors.Clear(); foreach (var m in srcMajors.Where(a=>srcColleges.Contains(a.College))) destMajors.Add(m); } private void MergeTicketDistributionMethods(IList<TicketDistributionMethod> dest, IList<TicketDistributionMethod> src) { dest.Clear(); foreach(var t in src) dest.Add(t); } private void CopyCeremony(Ceremony destCeremony, Ceremony srcCeremony, IList<MajorCode> srcMajors, IList<College> srcColleges, IList<TicketDistributionMethod> srcTicketDistributionMethods ) { destCeremony.Name = srcCeremony.Name; destCeremony.DateTime = srcCeremony.DateTime; destCeremony.Location = srcCeremony.Location; destCeremony.TicketsPerStudent = srcCeremony.TicketsPerStudent; destCeremony.TotalTickets = srcCeremony.TotalTickets; destCeremony.ExtraTicketBegin = srcCeremony.ExtraTicketBegin; destCeremony.ExtraTicketDeadline = CreateDeadline(srcCeremony.ExtraTicketDeadline); destCeremony.ExtraTicketPerStudent = srcCeremony.ExtraTicketPerStudent; destCeremony.PrintingDeadline = srcCeremony.PrintingDeadline; destCeremony.MinUnits = srcCeremony.MinUnits; destCeremony.PetitionThreshold = srcCeremony.PetitionThreshold; destCeremony.Colleges = srcColleges; destCeremony.ConfirmationText = srcCeremony.ConfirmationText; destCeremony.WebsiteUrl = srcCeremony.WebsiteUrl; destCeremony.SurveyUrl = srcCeremony.SurveyUrl; destCeremony.Survey = srcCeremony.Survey; foreach (var ceremonySurvey in srcCeremony.CeremonySurveys) { var destCeremonySurvey = destCeremony.CeremonySurveys.SingleOrDefault(a => a.College.Id == ceremonySurvey.College.Id); if (destCeremonySurvey == null) { var cSurvey = new CeremonySurvey(); cSurvey.Ceremony = destCeremony; cSurvey.College = ceremonySurvey.College; cSurvey.Survey = ceremonySurvey.Survey; cSurvey.SurveyUrl = ceremonySurvey.SurveyUrl; destCeremony.CeremonySurveys.Add(cSurvey); } else { destCeremonySurvey.Survey = ceremonySurvey.Survey; destCeremonySurvey.SurveyUrl = ceremonySurvey.SurveyUrl; } } MergeCeremonyMajors(destCeremony.Majors, srcMajors, srcColleges); MergeTicketDistributionMethods(destCeremony.TicketDistributionMethods, srcTicketDistributionMethods); } private DateTime CreateDeadline(DateTime src) { return new DateTime(src.Year, src.Month, src.Day, 23, 59, 59); } #endregion } public class CeremonyEditModel { public int? id { get; set; } public string Term { get; set; } public Ceremony Ceremony { get; set; } public IList<MajorCode> CeremonyMajors { get; set; } public IList<College> Colleges { get; set; } public IList<TicketDistributionMethod> TicketDistributionMethods { get; set; } public CeremonyEditModel() { CeremonyMajors = new List<MajorCode>(); Colleges = new List<College>(); TicketDistributionMethods = new List<TicketDistributionMethod>(); } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// DisplayApplianceEnvelope /// </summary> [DataContract] public partial class DisplayApplianceEnvelope : IEquatable<DisplayApplianceEnvelope>, IValidatableObject { public DisplayApplianceEnvelope() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="DisplayApplianceEnvelope" /> class. /// </summary> /// <param name="AddDemoStamp">.</param> /// <param name="AllowMultipleAttachments">.</param> /// <param name="BurnDefaultTabData">.</param> /// <param name="ConvertPdfFields">.</param> /// <param name="EnvelopeId">The envelope ID of the envelope status that failed to post..</param> /// <param name="EnvelopeType">.</param> /// <param name="IncludeSigsBeforeComplete">.</param> /// <param name="IsConcatMode">.</param> /// <param name="IsEnvelopeIDStampingEnabled">.</param> /// <param name="PdfFormConversionFontScale100">.</param> /// <param name="ShouldFlatten">.</param> /// <param name="ShowEnvelopeChanges">.</param> /// <param name="SignOnline">.</param> /// <param name="Status">Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later..</param> /// <param name="UserId">.</param> public DisplayApplianceEnvelope(bool? AddDemoStamp = default(bool?), bool? AllowMultipleAttachments = default(bool?), bool? BurnDefaultTabData = default(bool?), bool? ConvertPdfFields = default(bool?), string EnvelopeId = default(string), string EnvelopeType = default(string), bool? IncludeSigsBeforeComplete = default(bool?), bool? IsConcatMode = default(bool?), bool? IsEnvelopeIDStampingEnabled = default(bool?), bool? PdfFormConversionFontScale100 = default(bool?), bool? ShouldFlatten = default(bool?), bool? ShowEnvelopeChanges = default(bool?), bool? SignOnline = default(bool?), string Status = default(string), string UserId = default(string)) { this.AddDemoStamp = AddDemoStamp; this.AllowMultipleAttachments = AllowMultipleAttachments; this.BurnDefaultTabData = BurnDefaultTabData; this.ConvertPdfFields = ConvertPdfFields; this.EnvelopeId = EnvelopeId; this.EnvelopeType = EnvelopeType; this.IncludeSigsBeforeComplete = IncludeSigsBeforeComplete; this.IsConcatMode = IsConcatMode; this.IsEnvelopeIDStampingEnabled = IsEnvelopeIDStampingEnabled; this.PdfFormConversionFontScale100 = PdfFormConversionFontScale100; this.ShouldFlatten = ShouldFlatten; this.ShowEnvelopeChanges = ShowEnvelopeChanges; this.SignOnline = SignOnline; this.Status = Status; this.UserId = UserId; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="addDemoStamp", EmitDefaultValue=false)] public bool? AddDemoStamp { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="allowMultipleAttachments", EmitDefaultValue=false)] public bool? AllowMultipleAttachments { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="burnDefaultTabData", EmitDefaultValue=false)] public bool? BurnDefaultTabData { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="convertPdfFields", EmitDefaultValue=false)] public bool? ConvertPdfFields { get; set; } /// <summary> /// The envelope ID of the envelope status that failed to post. /// </summary> /// <value>The envelope ID of the envelope status that failed to post.</value> [DataMember(Name="envelopeId", EmitDefaultValue=false)] public string EnvelopeId { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="envelopeType", EmitDefaultValue=false)] public string EnvelopeType { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="includeSigsBeforeComplete", EmitDefaultValue=false)] public bool? IncludeSigsBeforeComplete { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="isConcatMode", EmitDefaultValue=false)] public bool? IsConcatMode { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="isEnvelopeIDStampingEnabled", EmitDefaultValue=false)] public bool? IsEnvelopeIDStampingEnabled { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="pdfFormConversionFontScale100", EmitDefaultValue=false)] public bool? PdfFormConversionFontScale100 { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="shouldFlatten", EmitDefaultValue=false)] public bool? ShouldFlatten { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="showEnvelopeChanges", EmitDefaultValue=false)] public bool? ShowEnvelopeChanges { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="signOnline", EmitDefaultValue=false)] public bool? SignOnline { get; set; } /// <summary> /// Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later. /// </summary> /// <value>Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.</value> [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="userId", EmitDefaultValue=false)] public string UserId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DisplayApplianceEnvelope {\n"); sb.Append(" AddDemoStamp: ").Append(AddDemoStamp).Append("\n"); sb.Append(" AllowMultipleAttachments: ").Append(AllowMultipleAttachments).Append("\n"); sb.Append(" BurnDefaultTabData: ").Append(BurnDefaultTabData).Append("\n"); sb.Append(" ConvertPdfFields: ").Append(ConvertPdfFields).Append("\n"); sb.Append(" EnvelopeId: ").Append(EnvelopeId).Append("\n"); sb.Append(" EnvelopeType: ").Append(EnvelopeType).Append("\n"); sb.Append(" IncludeSigsBeforeComplete: ").Append(IncludeSigsBeforeComplete).Append("\n"); sb.Append(" IsConcatMode: ").Append(IsConcatMode).Append("\n"); sb.Append(" IsEnvelopeIDStampingEnabled: ").Append(IsEnvelopeIDStampingEnabled).Append("\n"); sb.Append(" PdfFormConversionFontScale100: ").Append(PdfFormConversionFontScale100).Append("\n"); sb.Append(" ShouldFlatten: ").Append(ShouldFlatten).Append("\n"); sb.Append(" ShowEnvelopeChanges: ").Append(ShowEnvelopeChanges).Append("\n"); sb.Append(" SignOnline: ").Append(SignOnline).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" UserId: ").Append(UserId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as DisplayApplianceEnvelope); } /// <summary> /// Returns true if DisplayApplianceEnvelope instances are equal /// </summary> /// <param name="other">Instance of DisplayApplianceEnvelope to be compared</param> /// <returns>Boolean</returns> public bool Equals(DisplayApplianceEnvelope other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AddDemoStamp == other.AddDemoStamp || this.AddDemoStamp != null && this.AddDemoStamp.Equals(other.AddDemoStamp) ) && ( this.AllowMultipleAttachments == other.AllowMultipleAttachments || this.AllowMultipleAttachments != null && this.AllowMultipleAttachments.Equals(other.AllowMultipleAttachments) ) && ( this.BurnDefaultTabData == other.BurnDefaultTabData || this.BurnDefaultTabData != null && this.BurnDefaultTabData.Equals(other.BurnDefaultTabData) ) && ( this.ConvertPdfFields == other.ConvertPdfFields || this.ConvertPdfFields != null && this.ConvertPdfFields.Equals(other.ConvertPdfFields) ) && ( this.EnvelopeId == other.EnvelopeId || this.EnvelopeId != null && this.EnvelopeId.Equals(other.EnvelopeId) ) && ( this.EnvelopeType == other.EnvelopeType || this.EnvelopeType != null && this.EnvelopeType.Equals(other.EnvelopeType) ) && ( this.IncludeSigsBeforeComplete == other.IncludeSigsBeforeComplete || this.IncludeSigsBeforeComplete != null && this.IncludeSigsBeforeComplete.Equals(other.IncludeSigsBeforeComplete) ) && ( this.IsConcatMode == other.IsConcatMode || this.IsConcatMode != null && this.IsConcatMode.Equals(other.IsConcatMode) ) && ( this.IsEnvelopeIDStampingEnabled == other.IsEnvelopeIDStampingEnabled || this.IsEnvelopeIDStampingEnabled != null && this.IsEnvelopeIDStampingEnabled.Equals(other.IsEnvelopeIDStampingEnabled) ) && ( this.PdfFormConversionFontScale100 == other.PdfFormConversionFontScale100 || this.PdfFormConversionFontScale100 != null && this.PdfFormConversionFontScale100.Equals(other.PdfFormConversionFontScale100) ) && ( this.ShouldFlatten == other.ShouldFlatten || this.ShouldFlatten != null && this.ShouldFlatten.Equals(other.ShouldFlatten) ) && ( this.ShowEnvelopeChanges == other.ShowEnvelopeChanges || this.ShowEnvelopeChanges != null && this.ShowEnvelopeChanges.Equals(other.ShowEnvelopeChanges) ) && ( this.SignOnline == other.SignOnline || this.SignOnline != null && this.SignOnline.Equals(other.SignOnline) ) && ( this.Status == other.Status || this.Status != null && this.Status.Equals(other.Status) ) && ( this.UserId == other.UserId || this.UserId != null && this.UserId.Equals(other.UserId) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.AddDemoStamp != null) hash = hash * 59 + this.AddDemoStamp.GetHashCode(); if (this.AllowMultipleAttachments != null) hash = hash * 59 + this.AllowMultipleAttachments.GetHashCode(); if (this.BurnDefaultTabData != null) hash = hash * 59 + this.BurnDefaultTabData.GetHashCode(); if (this.ConvertPdfFields != null) hash = hash * 59 + this.ConvertPdfFields.GetHashCode(); if (this.EnvelopeId != null) hash = hash * 59 + this.EnvelopeId.GetHashCode(); if (this.EnvelopeType != null) hash = hash * 59 + this.EnvelopeType.GetHashCode(); if (this.IncludeSigsBeforeComplete != null) hash = hash * 59 + this.IncludeSigsBeforeComplete.GetHashCode(); if (this.IsConcatMode != null) hash = hash * 59 + this.IsConcatMode.GetHashCode(); if (this.IsEnvelopeIDStampingEnabled != null) hash = hash * 59 + this.IsEnvelopeIDStampingEnabled.GetHashCode(); if (this.PdfFormConversionFontScale100 != null) hash = hash * 59 + this.PdfFormConversionFontScale100.GetHashCode(); if (this.ShouldFlatten != null) hash = hash * 59 + this.ShouldFlatten.GetHashCode(); if (this.ShowEnvelopeChanges != null) hash = hash * 59 + this.ShowEnvelopeChanges.GetHashCode(); if (this.SignOnline != null) hash = hash * 59 + this.SignOnline.GetHashCode(); if (this.Status != null) hash = hash * 59 + this.Status.GetHashCode(); if (this.UserId != null) hash = hash * 59 + this.UserId.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.CSharp.Analyzers.Runtime.CSharpUseOrdinalStringComparisonAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.NetCore.VisualBasic.Analyzers.Runtime.BasicUseOrdinalStringComparisonAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests { public class UseOrdinalStringComparisonTests { #region Helper methods private DiagnosticResult CSharpResult(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic() .WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs private DiagnosticResult BasicResult(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic() .WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs #endregion #region Diagnostic tests [Fact] public async Task CA1309CompareOverloadTestCSharp() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Globalization; class C { void Method() { string a = null, b = null; // wrong overload string.Compare(a, b); string.Compare(a, b, true); string.Compare(a, b, true, default(CultureInfo)); string.Compare(a, b, default(CultureInfo), default(CompareOptions)); string.Compare(a, 0, b, 0, 0); string.Compare(a, 0, b, 0, 0, true); string.Compare(a, 0, b, 0, 0, true, default(CultureInfo)); string.Compare(a, 0, b, 0, 0, default(CultureInfo), default(CompareOptions)); System.String.Compare(a, b); // right overload, wrong value string.Compare(a, b, StringComparison.CurrentCulture); string.Compare(a, 0, b, 0, 0, StringComparison.CurrentCulture); // right overload, right value string.Compare(a, b, StringComparison.Ordinal); string.Compare(a, b, StringComparison.OrdinalIgnoreCase); string.Compare(a, 0, b, 0, 0, StringComparison.Ordinal); string.Compare(a, 0, b, 0, 0, StringComparison.OrdinalIgnoreCase); } } ", CSharpResult(11, 16), CSharpResult(12, 16), CSharpResult(13, 16), CSharpResult(14, 16), CSharpResult(15, 16), CSharpResult(16, 16), CSharpResult(17, 16), CSharpResult(18, 16), CSharpResult(19, 23), CSharpResult(21, 30), CSharpResult(22, 39)); } [Fact] public async Task CA1309CompareOverloadTestBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Globalization Class C Sub Method() Dim a As String Dim b As String Dim ci As CultureInfo Dim co As CompareOptions ' wrong overload String.Compare(a, b) String.Compare(a, b, True) String.Compare(a, b, True, ci) String.Compare(a, b, ci, co) String.Compare(a, 0, b, 0, 0) String.Compare(a, 0, b, 0, 0, True) String.Compare(a, 0, b, 0, 0, True, ci) String.Compare(a, 0, b, 0, 0, ci, co) System.String.Compare(a, b) ' right overload, wrong value String.Compare(a, b, StringComparison.CurrentCulture) String.Compare(a, 0, b, 0, 0, StringComparison.CurrentCulture) ' right overload, right value String.Compare(a, b, StringComparison.Ordinal) String.Compare(a, b, StringComparison.OrdinalIgnoreCase) String.Compare(a, 0, b, 0, 0, StringComparison.Ordinal) String.Compare(a, 0, b, 0, 0, StringComparison.OrdinalIgnoreCase) End Sub End Class ", BasicResult(12, 16), BasicResult(13, 16), BasicResult(14, 16), BasicResult(15, 16), BasicResult(16, 16), BasicResult(17, 16), BasicResult(18, 16), BasicResult(19, 16), BasicResult(20, 23), BasicResult(22, 30), BasicResult(23, 39)); } [Fact] public async Task CA1309EqualsOverloadTestCSharp() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void Method() { string a = null, b = null; // wrong overload string.Equals(a, b); // (string, string) is bad // right overload, wrong value string.Equals(a, b, StringComparison.CurrentCulture); // right overload, right value string.Equals(a, b, StringComparison.Ordinal); string.Equals(a, b, StringComparison.OrdinalIgnoreCase); string.Equals(a, 15); // this is the (object, object) overload } } ", CSharpResult(10, 16), CSharpResult(12, 29)); } [Fact] public async Task CA1309EqualsOverloadTestBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class C Sub Method() Dim a As String, b As String ' wrong overload String.Equals(a, b) ' (String, String) is bad ' right overload, wrong value String.Equals(a, b, StringComparison.CurrentCulture) ' right overload, right value String.Equals(a, b, StringComparison.Ordinal) String.Equals(a, b, StringComparison.OrdinalIgnoreCase) String.Equals(a, 15) ' this is the (Object, Object) overload End Sub End Class ", BasicResult(8, 16), BasicResult(10, 29)); } [Fact] public async Task CA1309InstanceEqualsTestCSharp() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void Method() { string a = null, b = null; // wrong overload a.Equals(b); // right overload, wrong value a.Equals(b, StringComparison.CurrentCulture); // right overload, right value a.Equals(b, StringComparison.Ordinal); a.Equals(b, StringComparison.OrdinalIgnoreCase); a.Equals(15); // this is the (object) overload } } ", CSharpResult(10, 11), CSharpResult(12, 21)); } [Fact] public async Task CA1309InstanceEqualsTestBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class C Sub Method() Dim a As String, b As String ' wrong overload a.Equals(b) ' right overload, wrong value a.Equals(b, StringComparison.CurrentCulture) ' right overload, right value a.Equals(b, StringComparison.Ordinal) a.Equals(b, StringComparison.OrdinalIgnoreCase) a.Equals(15) ' this is the (Object) overload End Sub End Class ", BasicResult(8, 11), BasicResult(10, 21)); } [Fact] public async Task CA1309OperatorOverloadTestCSharp_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void Method() { string a = null, b = null; if (a == b) { } if (a != b) { } if (a == null) { } if (null == a) { } } } "); } [Fact] public async Task CA1309OperatorOverloadTestBasic_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class C Sub Method() Dim a As String, b As String If a = b Then End If If a <> b Then End If If a = Nothing Then End If If a Is Nothing Then End If If Nothing = a Then End If End Sub End Class "); } [Fact] public async Task CA1309NotReallyCompareOrEqualsTestCSharp() { await VerifyCS.VerifyAnalyzerAsync(@" class C { void Method() { string s = null; // verify extension methods don't trigger if (s.Equals(1, 2, 3)) { } if (s.Compare(1, 2, 3)) { } // verify other static string methods don't trigger string.Format(s); // verify other instance string methods don't trigger s.EndsWith(s); } } static class Extensions { public static bool Equals(this string s, int a, int b, int c) { return false; } public static bool Compare(this string s, int a, int b, int c) { return false; } } "); } [Fact] public async Task CA1309NotReallyCompareOrEqualsTestBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Runtime.CompilerServices Class C Sub Method() Dim s As String ' verify extension methods don't trigger If s.Equals(1, 2, 3) Then End If If s.Compare(1, 2) Then End If ' verify other static string methods don't trigger String.Format(s) ' verify other instance string methods don't trigger s.EndsWith(s) End Sub End Class Module Extensions <Extension> Public Function Equals(s As String, a As Integer, b As Integer, c As Integer) As Boolean Return False End Function <Extension()> Public Function Compare(s As String, a As Integer, b As Integer) As Boolean Return False End Function End Module "); } #endregion } }