context
stringlengths
2.52k
185k
gt
stringclasses
1 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.Diagnostics; using System.Linq; using System.Net; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Cassandra.Collections; using Cassandra.Connections; using Cassandra.Connections.Control; using Cassandra.Helpers; using Cassandra.ProtocolEvents; using Cassandra.Requests; using Cassandra.Serialization; using Cassandra.SessionManagement; using Cassandra.Tasks; namespace Cassandra { /// <inheritdoc cref="ICluster" /> public class Cluster : IInternalCluster { private static ProtocolVersion _maxProtocolVersion = ProtocolVersion.MaxSupported; internal static readonly Logger Logger = new Logger(typeof(Cluster)); private readonly CopyOnWriteList<IInternalSession> _connectedSessions = new CopyOnWriteList<IInternalSession>(); private readonly IControlConnection _controlConnection; private volatile bool _initialized; private volatile Exception _initException; private readonly SemaphoreSlim _initLock = new SemaphoreSlim(1, 1); private long _sessionCounter = -1; private readonly Metadata _metadata; private readonly IProtocolEventDebouncer _protocolEventDebouncer; private IReadOnlyList<ILoadBalancingPolicy> _loadBalancingPolicies; /// <inheritdoc /> public event Action<Host> HostAdded; /// <inheritdoc /> public event Action<Host> HostRemoved; internal IInternalCluster InternalRef => this; /// <inheritdoc /> IControlConnection IInternalCluster.GetControlConnection() { return _controlConnection; } /// <inheritdoc /> ConcurrentDictionary<byte[], PreparedStatement> IInternalCluster.PreparedQueries { get; } = new ConcurrentDictionary<byte[], PreparedStatement>(new ByteArrayComparer()); /// <summary> /// Build a new cluster based on the provided initializer. <p> Note that for /// building a cluster programmatically, Cluster.NewBuilder provides a slightly less /// verbose shortcut with <link>NewBuilder#Build</link>. </p><p> Also note that that all /// the contact points provided by <c>initializer</c> must share the same /// port.</p> /// </summary> /// <param name="initializer">the Cluster.Initializer to use</param> /// <returns>the newly created Cluster instance </returns> public static Cluster BuildFrom(IInitializer initializer) { return BuildFrom(initializer, null, null); } internal static Cluster BuildFrom(IInitializer initializer, IReadOnlyList<object> nonIpEndPointContactPoints) { return BuildFrom(initializer, nonIpEndPointContactPoints, null); } internal static Cluster BuildFrom(IInitializer initializer, IReadOnlyList<object> nonIpEndPointContactPoints, Configuration config) { nonIpEndPointContactPoints = nonIpEndPointContactPoints ?? new object[0]; if (initializer.ContactPoints.Count == 0 && nonIpEndPointContactPoints.Count == 0) { throw new ArgumentException("Cannot build a cluster without contact points"); } return new Cluster( initializer.ContactPoints.Concat(nonIpEndPointContactPoints), config ?? initializer.GetConfiguration()); } /// <summary> /// Creates a new <link>Cluster.NewBuilder</link> instance. <p> This is a shortcut /// for <c>new Cluster.NewBuilder()</c></p>. /// </summary> /// <returns>the new cluster builder.</returns> public static Builder Builder() { return new Builder(); } /// <summary> /// Gets or sets the maximum protocol version used by this driver. /// <para> /// While property value is maintained for backward-compatibility, /// use <see cref="ProtocolOptions.SetMaxProtocolVersion(ProtocolVersion)"/> to set the maximum protocol version used by the driver. /// </para> /// <para> /// Protocol version used can not be higher than <see cref="ProtocolVersion.MaxSupported"/>. /// </para> /// </summary> public static int MaxProtocolVersion { get { return (int)_maxProtocolVersion; } set { if (value > (int)ProtocolVersion.MaxSupported) { // Ignore return; } _maxProtocolVersion = (ProtocolVersion)value; } } /// <summary> /// Gets the cluster configuration. /// </summary> public Configuration Configuration { get; private set; } /// <inheritdoc /> public Metadata Metadata { get { TaskHelper.WaitToComplete(Init()); return _metadata; } } private Cluster(IEnumerable<object> contactPoints, Configuration configuration) { Configuration = configuration; _metadata = new Metadata(configuration); var protocolVersion = _maxProtocolVersion; if (Configuration.ProtocolOptions.MaxProtocolVersionValue != null && Configuration.ProtocolOptions.MaxProtocolVersionValue.Value.IsSupported(configuration)) { protocolVersion = Configuration.ProtocolOptions.MaxProtocolVersionValue.Value; } _protocolEventDebouncer = new ProtocolEventDebouncer( configuration.TimerFactory, TimeSpan.FromMilliseconds(configuration.MetadataSyncOptions.RefreshSchemaDelayIncrement), TimeSpan.FromMilliseconds(configuration.MetadataSyncOptions.MaxTotalRefreshSchemaDelay)); var parsedContactPoints = configuration.ContactPointParser.ParseContactPoints(contactPoints); _controlConnection = configuration.ControlConnectionFactory.Create( this, _protocolEventDebouncer, protocolVersion, Configuration, _metadata, parsedContactPoints); _metadata.ControlConnection = _controlConnection; } /// <summary> /// Initializes once (Thread-safe) the control connection and metadata associated with the Cluster instance /// </summary> private async Task Init() { if (_initialized) { //It was already initialized return; } await _initLock.WaitAsync().ConfigureAwait(false); try { if (_initialized) { //It was initialized when waiting on the lock return; } if (_initException != null) { //There was an exception that is not possible to recover from throw _initException; } Cluster.Logger.Info("Connecting to cluster using {0}", GetAssemblyInfo()); try { // Collect all policies in collections var loadBalancingPolicies = new HashSet<ILoadBalancingPolicy>(new ReferenceEqualityComparer<ILoadBalancingPolicy>()); var speculativeExecutionPolicies = new HashSet<ISpeculativeExecutionPolicy>(new ReferenceEqualityComparer<ISpeculativeExecutionPolicy>()); foreach (var options in Configuration.RequestOptions.Values) { loadBalancingPolicies.Add(options.LoadBalancingPolicy); speculativeExecutionPolicies.Add(options.SpeculativeExecutionPolicy); } _loadBalancingPolicies = loadBalancingPolicies.ToList(); // Only abort the async operations when at least twice the time for ConnectTimeout per host passed var initialAbortTimeout = Configuration.SocketOptions.ConnectTimeoutMillis * 2 * _metadata.Hosts.Count; initialAbortTimeout = Math.Max(initialAbortTimeout, Configuration.SocketOptions.MetadataAbortTimeout); var initTask = _controlConnection.InitAsync(); try { await initTask.WaitToCompleteAsync(initialAbortTimeout).ConfigureAwait(false); } catch (TimeoutException ex) { var newEx = new TimeoutException( "Cluster initialization was aborted after timing out. This mechanism is put in place to" + " avoid blocking the calling thread forever. This usually caused by a networking issue" + " between the client driver instance and the cluster. You can increase this timeout via " + "the SocketOptions.ConnectTimeoutMillis config setting. This can also be related to deadlocks " + "caused by mixing synchronous and asynchronous code.", ex); _initException = new InitFatalErrorException(newEx); initTask.ContinueWith(t => { if (t.IsFaulted && t.Exception != null) { _initException = new InitFatalErrorException(t.Exception.InnerException); } }, TaskContinuationOptions.ExecuteSynchronously).Forget(); throw newEx; } // Initialize policies foreach (var lbp in loadBalancingPolicies) { lbp.Initialize(this); } foreach (var sep in speculativeExecutionPolicies) { sep.Initialize(this); } InitializeHostDistances(); // Set metadata dependent options SetMetadataDependentOptions(); } catch (NoHostAvailableException) { //No host available now, maybe later it can recover from throw; } catch (TimeoutException) { throw; } catch (Exception ex) { //There was an error that the driver is not able to recover from //Store the exception for the following times _initException = new InitFatalErrorException(ex); //Throw the actual exception for the first time throw; } Cluster.Logger.Info("Cluster Connected using binary protocol version: [" + _controlConnection.Serializer.CurrentProtocolVersion + "]"); _initialized = true; _metadata.Hosts.Added += OnHostAdded; _metadata.Hosts.Removed += OnHostRemoved; _metadata.Hosts.Up += OnHostUp; } finally { _initLock.Release(); } Cluster.Logger.Info("Cluster #{0} [{1}] has been initialized.", GetHashCode(), Metadata.ClusterName); return; } private void InitializeHostDistances() { foreach (var host in AllHosts()) { InternalRef.RetrieveAndSetDistance(host); } } private static string GetAssemblyInfo() { var assembly = typeof(ISession).GetTypeInfo().Assembly; var info = FileVersionInfo.GetVersionInfo(assembly.Location); return $"{info.ProductName} v{info.FileVersion}"; } IReadOnlyDictionary<IContactPoint, IEnumerable<IConnectionEndPoint>> IInternalCluster.GetResolvedEndpoints() { return _metadata.ResolvedContactPoints; } /// <inheritdoc /> public ICollection<Host> AllHosts() { //Do not connect at first return _metadata.AllHosts(); } /// <summary> /// Creates a new session on this cluster. /// </summary> public ISession Connect() { return Connect(Configuration.ClientOptions.DefaultKeyspace); } /// <summary> /// Creates a new session on this cluster. /// </summary> public Task<ISession> ConnectAsync() { return ConnectAsync(Configuration.ClientOptions.DefaultKeyspace); } /// <summary> /// Creates a new session on this cluster and using a keyspace an existing keyspace. /// </summary> /// <param name="keyspace">Case-sensitive keyspace name to use</param> public ISession Connect(string keyspace) { return TaskHelper.WaitToComplete(ConnectAsync(keyspace)); } /// <summary> /// Creates a new session on this cluster and using a keyspace an existing keyspace. /// </summary> /// <param name="keyspace">Case-sensitive keyspace name to use</param> public async Task<ISession> ConnectAsync(string keyspace) { await Init().ConfigureAwait(false); var newSessionName = GetNewSessionName(); var session = await Configuration.SessionFactory.CreateSessionAsync(this, keyspace, _controlConnection.Serializer, newSessionName).ConfigureAwait(false); try { await session.Init().ConfigureAwait(false); } catch { await session.ShutdownAsync().ConfigureAwait(false); throw; } _connectedSessions.Add(session); Cluster.Logger.Info("Session connected ({0})", session.GetHashCode()); return session; } private string GetNewSessionName() { var sessionCounter = GetAndIncrementSessionCounter(); if (sessionCounter == 0 && Configuration.SessionName != null) { return Configuration.SessionName; } var prefix = Configuration.SessionName ?? Configuration.DefaultSessionName; return prefix + sessionCounter; } private long GetAndIncrementSessionCounter() { var newCounter = Interlocked.Increment(ref _sessionCounter); // Math.Abs just to avoid negative counters if it overflows return newCounter < 0 ? Math.Abs(newCounter) : newCounter; } private void SetMetadataDependentOptions() { if (_metadata.IsDbaas) { Configuration.SetDefaultConsistencyLevel(ConsistencyLevel.LocalQuorum); } } /// <summary> /// Creates new session on this cluster, and sets it to default keyspace. /// If default keyspace does not exist then it will be created and session will be set to it. /// Name of default keyspace can be specified during creation of cluster object with <c>Cluster.Builder().WithDefaultKeyspace("keyspace_name")</c> method. /// </summary> /// <param name="replication">Replication property for this keyspace. To set it, refer to the <see cref="ReplicationStrategies"/> class methods. /// It is a dictionary of replication property sub-options where key is a sub-option name and value is a value for that sub-option. /// <p>Default value is <c>SimpleStrategy</c> with <c>'replication_factor' = 2</c></p></param> /// <param name="durableWrites">Whether to use the commit log for updates on this keyspace. Default is set to <c>true</c>.</param> /// <returns>a new session on this cluster set to default keyspace.</returns> public ISession ConnectAndCreateDefaultKeyspaceIfNotExists(Dictionary<string, string> replication = null, bool durableWrites = true) { var session = Connect(null); session.CreateKeyspaceIfNotExists(Configuration.ClientOptions.DefaultKeyspace, replication, durableWrites); session.ChangeKeyspace(Configuration.ClientOptions.DefaultKeyspace); return session; } bool IInternalCluster.AnyOpenConnections(Host host) { return _connectedSessions.Any(session => session.HasConnections(host)); } public void Dispose() { Shutdown(); } /// <inheritdoc /> public Host GetHost(IPEndPoint address) { return Metadata.GetHost(address); } /// <inheritdoc /> public ICollection<Host> GetReplicas(byte[] partitionKey) { return Metadata.GetReplicas(partitionKey); } /// <inheritdoc /> public ICollection<Host> GetReplicas(string keyspace, byte[] partitionKey) { return Metadata.GetReplicas(keyspace, partitionKey); } private void OnHostRemoved(Host h) { HostRemoved?.Invoke(h); } private void OnHostAdded(Host h) { HostAdded?.Invoke(h); } private async void OnHostUp(Host h) { try { if (!Configuration.QueryOptions.IsReprepareOnUp()) { return; } // We should prepare all current queries on the host await ReprepareAllQueries(h).ConfigureAwait(false); } catch (Exception ex) { Cluster.Logger.Error( "An exception was thrown when preparing all queries on a host ({0}) " + "that came UP:" + Environment.NewLine + "{1}", h?.Address?.ToString(), ex.ToString()); } } /// <inheritdoc /> public bool RefreshSchema(string keyspace = null, string table = null) { return Metadata.RefreshSchema(keyspace, table); } /// <inheritdoc /> public Task<bool> RefreshSchemaAsync(string keyspace = null, string table = null) { return Metadata.RefreshSchemaAsync(keyspace, table); } /// <inheritdoc /> public void Shutdown(int timeoutMs = Timeout.Infinite) { ShutdownAsync(timeoutMs).GetAwaiter().GetResult(); } /// <inheritdoc /> public async Task ShutdownAsync(int timeoutMs = Timeout.Infinite) { if (!_initialized) { _metadata.ShutDown(timeoutMs); _controlConnection.Dispose(); await _protocolEventDebouncer.ShutdownAsync().ConfigureAwait(false); Configuration.Timer.Dispose(); Cluster.Logger.Info("Cluster #{0} has been shut down.", GetHashCode()); return; } var sessions = _connectedSessions.ClearAndGet(); try { var tasks = new List<Task>(); foreach (var s in sessions) { tasks.Add(s.ShutdownAsync()); } await Task.WhenAll(tasks).WaitToCompleteAsync(timeoutMs).ConfigureAwait(false); } catch (AggregateException ex) { if (ex.InnerExceptions.Count == 1) { throw ex.InnerExceptions[0]; } throw; } _metadata.ShutDown(timeoutMs); _controlConnection.Dispose(); await _protocolEventDebouncer.ShutdownAsync().ConfigureAwait(false); Configuration.Timer.Dispose(); // Dispose policies var speculativeExecutionPolicies = new HashSet<ISpeculativeExecutionPolicy>(new ReferenceEqualityComparer<ISpeculativeExecutionPolicy>()); foreach (var options in Configuration.RequestOptions.Values) { speculativeExecutionPolicies.Add(options.SpeculativeExecutionPolicy); } foreach (var sep in speculativeExecutionPolicies) { sep.Dispose(); } Cluster.Logger.Info("Cluster #{0} [{1}] has been shut down.", GetHashCode(), Metadata.ClusterName); return; } /// <inheritdoc /> HostDistance IInternalCluster.RetrieveAndSetDistance(Host host) { var distance = _loadBalancingPolicies[0].Distance(host); for (var i = 1; i < _loadBalancingPolicies.Count; i++) { var lbp = _loadBalancingPolicies[i]; var lbpDistance = lbp.Distance(host); if (lbpDistance < distance) { distance = lbpDistance; } } host.SetDistance(distance); return distance; } /// <inheritdoc /> async Task<PreparedStatement> IInternalCluster.Prepare( IInternalSession session, ISerializerManager serializerManager, PrepareRequest request) { var lbp = session.Cluster.Configuration.DefaultRequestOptions.LoadBalancingPolicy; var handler = InternalRef.Configuration.PrepareHandlerFactory.CreatePrepareHandler(serializerManager, this); var ps = await handler.Prepare(request, session, lbp.NewQueryPlan(session.Keyspace, null).GetEnumerator()).ConfigureAwait(false); var psAdded = InternalRef.PreparedQueries.GetOrAdd(ps.Id, ps); if (ps != psAdded) { PrepareHandler.Logger.Warning("Re-preparing already prepared query is generally an anti-pattern and will likely " + "affect performance. Consider preparing the statement only once. Query='{0}'", ps.Cql); ps = psAdded; } return ps; } private async Task ReprepareAllQueries(Host host) { ICollection<PreparedStatement> preparedQueries = InternalRef.PreparedQueries.Values; IEnumerable<IInternalSession> sessions = _connectedSessions; if (preparedQueries.Count == 0) { return; } // Get the first pool for that host that has open connections var pool = sessions.Select(s => s.GetExistingPool(host.Address)).Where(p => p != null).FirstOrDefault(p => p.HasConnections); if (pool == null) { PrepareHandler.Logger.Info($"Not re-preparing queries on {host.Address} as there wasn't an open connection to the node."); return; } PrepareHandler.Logger.Info($"Re-preparing {preparedQueries.Count} queries on {host.Address}"); var tasks = new List<Task>(preparedQueries.Count); var handler = InternalRef.Configuration.PrepareHandlerFactory.CreateReprepareHandler(); var serializer = _metadata.ControlConnection.Serializer.GetCurrentSerializer(); using (var semaphore = new SemaphoreSlim(64, 64)) { foreach (var ps in preparedQueries) { var request = new PrepareRequest(serializer, ps.Cql, ps.Keyspace, null); await semaphore.WaitAsync().ConfigureAwait(false); tasks.Add(Task.Run(() => handler.ReprepareOnSingleNodeAsync( new KeyValuePair<Host, IHostConnectionPool>(host, pool), ps, request, semaphore, true))); } try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (Exception ex) { PrepareHandler.Logger.Info( "There was an error when re-preparing queries on {0}. " + "The driver will re-prepare the queries individually the next time they are sent to this node. " + "Exception: {1}", host.Address, ex); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class implements a set of methods for retrieving // sort key information. // // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { using System; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public partial class SortKey { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // [OptionalField(VersionAdded = 3)] internal string _localeName; // locale identifier [OptionalField(VersionAdded = 1)] // LCID field so serialization is Whidbey compatible though we don't officially support it internal int _win32LCID; // Whidbey serialization internal CompareOptions _options; // options internal string _string; // original string internal byte[] _keyData; // sortkey data // // The following constructor is designed to be called from CompareInfo to get the // the sort key of specific string for synthetic culture // internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData) { _keyData = keyData; _localeName = localeName; _options = options; _string = str; } [OnSerializing] private void OnSerializing(StreamingContext context) { //set LCID to proper value for Whidbey serialization (no other use) if (_win32LCID == 0) { _win32LCID = CultureInfo.GetCultureInfo(_localeName).LCID; } } [OnDeserialized] private void OnDeserialized(StreamingContext context) { //set locale name to proper value after Whidbey deserialization if (String.IsNullOrEmpty(_localeName) && _win32LCID != 0) { _localeName = CultureInfo.GetCultureInfo(_win32LCID).Name; } } //////////////////////////////////////////////////////////////////////// // // GetOriginalString // // Returns the original string used to create the current instance // of SortKey. // //////////////////////////////////////////////////////////////////////// public virtual String OriginalString { get { return (_string); } } //////////////////////////////////////////////////////////////////////// // // GetKeyData // // Returns a byte array representing the current instance of the // sort key. // //////////////////////////////////////////////////////////////////////// public virtual byte[] KeyData { get { return (byte[])(_keyData.Clone()); } } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the two sort keys. Returns 0 if the two sort keys are // equal, a number less than 0 if sortkey1 is less than sortkey2, // and a number greater than 0 if sortkey1 is greater than sortkey2. // //////////////////////////////////////////////////////////////////////// public static int Compare(SortKey sortkey1, SortKey sortkey2) { if (sortkey1==null || sortkey2==null) { throw new ArgumentNullException((sortkey1 == null ? nameof(sortkey1) : nameof(sortkey2))); } Contract.EndContractBlock(); byte[] key1Data = sortkey1._keyData; byte[] key2Data = sortkey2._keyData; Contract.Assert(key1Data != null, "key1Data != null"); Contract.Assert(key2Data != null, "key2Data != null"); if (key1Data.Length == 0) { if (key2Data.Length == 0) { return (0); } return (-1); } if (key2Data.Length == 0) { return (1); } int compLen = (key1Data.Length<key2Data.Length)?key1Data.Length:key2Data.Length; for (int i=0; i<compLen; i++) { if (key1Data[i]>key2Data[i]) { return (1); } if (key1Data[i]<key2Data[i]) { return (-1); } } return 0; } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same SortKey as the current instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { SortKey that = value as SortKey; if (that != null) { return Compare(this, that) == 0; } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // SortKey. The hash code is guaranteed to be the same for // SortKey A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (CompareInfo.GetCompareInfo(_localeName).GetHashCodeOfString(_string, _options)); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns a string describing the // SortKey. // //////////////////////////////////////////////////////////////////////// public override String ToString() { return ("SortKey - " + _localeName + ", " + _options + ", " + _string); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/18/2009 9:31:11 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** using System; using System.Diagnostics; using DotSpatial.Projections.Nad; using DotSpatial.Projections.Transforms; namespace DotSpatial.Projections { public static class GridShift { private const double HUGE_VAL = double.MaxValue; private const int MAX_TRY = 9; private const double TOL = 1E-12; #region Private Variables private static readonly NadTables _shift = new NadTables(); #endregion #region Methods /// <summary> /// Applies either a forward or backward gridshift based on the specified name /// </summary> public static void Apply(string[] names, bool inverse, double[] xy, int startIndex, long numPoints) { for (int i = startIndex; i < numPoints; i++) { PhiLam input, output; input.Phi = xy[i * 2 + 1]; input.Lambda = xy[i * 2]; output.Phi = HUGE_VAL; output.Lambda = HUGE_VAL; /* keep trying till we find a Table that works from the ones listed */ foreach (string name in names) { Lazy<NadTable> tableLazy; if (!_shift.Tables.TryGetValue(name, out tableLazy)) continue; var table = tableLazy.Value; bool found = false; // For GSB tables, we need to check for the appropriate sub-table if (table.SubGrids != null && table.SubGrids.Count > 1) { foreach (NadTable subGrid in table.SubGrids) { /* skip tables that don't match our point at all. */ double wLam = subGrid.LowerLeft.Lambda; double eLam = wLam + (subGrid.NumLambdas - 1) * subGrid.CellSize.Lambda; double sPhi = subGrid.LowerLeft.Phi; double nPhi = sPhi + (subGrid.NumPhis - 1) * subGrid.CellSize.Lambda; if (input.Lambda < wLam || input.Lambda > eLam || input.Phi < sPhi || input.Phi > nPhi) continue; table = subGrid; found = true; break; } if (!found) continue; } else { /* skip tables that don't match our point at all. */ double minLam = table.LowerLeft.Lambda; double maxLam = minLam + (table.NumLambdas - 1) * table.CellSize.Lambda; double minPhi = table.LowerLeft.Phi; double maxPhi = minPhi + (table.NumPhis - 1) * table.CellSize.Lambda; if (input.Lambda < minLam || input.Lambda > maxLam || input.Phi < minPhi || input.Phi > maxPhi) continue; } // TO DO: handle child nodes? Not sure what format would require this output = Convert(input, inverse, table); if (output.Lambda == HUGE_VAL) { Debug.WriteLine("GridShift failed"); break; } break; } if (output.Lambda == HUGE_VAL) { Debug.WriteLine( "pj_apply_gridshift(): failed to find a grid shift Table for location: (" + xy[i * 2] * 180 / Math.PI + ", " + xy[i * 2 + 1] * 180 / Math.PI + ")"); } else { xy[i * 2] = output.Lambda; xy[i * 2 + 1] = output.Phi; } } } private static PhiLam Convert(PhiLam input, bool inverse, NadTable table) { if (input.Lambda == HUGE_VAL) return input; // Normalize input to ll origin if (!table.Filled) table.FillData(); PhiLam tb = input; tb.Lambda -= table.LowerLeft.Lambda; tb.Phi -= table.LowerLeft.Phi; tb.Lambda = Proj.Adjlon(tb.Lambda - Math.PI) + Math.PI; PhiLam t = NadInterpolate(tb, table); if (inverse) { PhiLam del, dif; int i = MAX_TRY; if (t.Lambda == HUGE_VAL) return t; t.Lambda = tb.Lambda + t.Lambda; t.Phi = tb.Phi - t.Phi; do { del = NadInterpolate(t, table); /* This case used to return failure, but I have changed it to return the first order approximation of the inverse shift. This avoids cases where the grid shift *into* this grid came from another grid. While we aren't returning optimally correct results I feel a close result in this case is better than no result. NFW To demonstrate use -112.5839956 49.4914451 against the NTv2 grid shift file from Canada. */ if (del.Lambda == HUGE_VAL) { Debug.WriteLine(ProjectionMessages.InverseShiftFailed); break; } t.Lambda -= dif.Lambda = t.Lambda - del.Lambda - tb.Lambda; t.Phi -= dif.Phi = t.Phi + del.Phi - tb.Phi; } while (i-- > 0 && Math.Abs(dif.Lambda) > TOL && Math.Abs(dif.Phi) > TOL); if (i < 0) { Debug.WriteLine(ProjectionMessages.InvShiftConvergeFailed); t.Lambda = t.Phi = HUGE_VAL; return t; } input.Lambda = Proj.Adjlon(t.Lambda + table.LowerLeft.Lambda); input.Phi = t.Phi + table.LowerLeft.Phi; } else { if (t.Lambda == HUGE_VAL) { input = t; } else { input.Lambda -= t.Lambda; input.Phi += t.Phi; } } return input; } /// <summary> /// /// </summary> /// <param name="t"></param> /// <param name="ct"></param> /// <returns></returns> private static PhiLam NadInterpolate(PhiLam t, NadTable ct) { PhiLam result, remainder; result.Phi = HUGE_VAL; result.Lambda = HUGE_VAL; // find indices and normalize by the cell size (so fractions range from 0 to 1) int iLam = (int)Math.Floor(t.Lambda /= ct.CellSize.Lambda); int iPhi = (int)Math.Floor(t.Phi /= ct.CellSize.Phi); // use the index to determine the remainder remainder.Lambda = t.Lambda - iLam; remainder.Phi = t.Phi - iPhi; //int offLam = 0; // normally we look to the right and bottom neighbor cells //int offPhi = 0; //if (remainder.Lambda < .5) offLam = -1; // look to cell left of the current cell //if (remainder.Phi < .5) offPhi = -1; // look to cell above the of the current cell //// because the fractional weights are between cells, we need to adjust the //// "remainder" so that it is now relative to the center of the top left //// cell, taking into account that the definition of the top left cell //// depends on whether the original remainder was larger than .5 //remainder.Phi = (remainder.Phi > .5) ? remainder.Phi - .5 : remainder.Phi + .5; //remainder.Lambda = (remainder.Lambda > .5) ? remainder.Lambda - .5 : remainder.Phi + .5; if (iLam < 0) { if (iLam == -1 && remainder.Lambda > 0.99999999999) { iLam++; remainder.Lambda = 0; } else { return result; } } else if (iLam + 1 >= ct.NumLambdas) { if (iLam + 1 == ct.NumLambdas && remainder.Lambda < 1e-11) { iLam--; } else { return result; } } if (iPhi < 0) { if (iPhi == -1 && remainder.Phi > 0.99999999999) { iPhi++; remainder.Phi = 0; } else { return result; } } else if (iPhi + 1 >= ct.NumPhis) { if (iPhi + 1 == ct.NumPhis && remainder.Phi < 1e-11) { iPhi--; remainder.Phi = 1; } else { return result; } } PhiLam f00 = GetValue(iPhi, iLam, ct); PhiLam f01 = GetValue(iPhi + 1, iLam, ct); PhiLam f10 = GetValue(iPhi, iLam + 1, ct); PhiLam f11 = GetValue(iPhi + 1, iLam + 1, ct); // The cell weight is equivalent to the area of a cell sized square centered // on the actual point that overlaps with the cell. // Since the overlap must add up to 1, any portion that does not overlap // on the left must overlap on the right, hence (1-remainder.Lambda) double m00 = (1 - remainder.Lambda) * (1 - remainder.Phi); double m01 = (1 - remainder.Lambda) * remainder.Phi; double m10 = remainder.Lambda * (1 - remainder.Phi); double m11 = remainder.Lambda * remainder.Phi; result.Lambda = m00 * f00.Lambda + m01 * f01.Lambda + m10 * f10.Lambda + m11 * f11.Lambda; result.Phi = m00 * f00.Phi + m01 * f01.Phi + m10 * f10.Phi + m11 * f11.Phi; return result; } /// <summary> /// Checks the edges to make sure that we are not attempting to interpolate /// from cells that don't exist. /// </summary> /// <param name="iPhi">The cell index in the phi direction</param> /// <param name="iLam">The cell index in the lambda direction</param> /// <param name="table">The Table with the values</param> /// <returns>A PhiLam that has the shift coefficeints.</returns> private static PhiLam GetValue(int iPhi, int iLam, NadTable table) { if (iPhi < 0) iPhi = 0; if (iPhi >= table.NumPhis) iPhi = table.NumPhis - 1; if (iLam < 0) iLam = 0; if (iLam >= table.NumLambdas) iLam = table.NumPhis - 1; return table.Cvs[iPhi][iLam]; } /// <summary> /// Load grids from the default GeogTransformsGrids subfolder /// </summary> public static void InitializeExternalGrids() { _shift.InitializeExternalGrids(); } /// <summary> /// Load grids from the specified folder /// </summary> /// <param name="gridsFolder"></param> /// <param name="recursive"></param> public static void InitializeExternalGrids(string gridsFolder, bool recursive) { _shift.InitializeExternalGrids(gridsFolder, recursive); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Media.Imaging; using Microsoft.CodeAnalysis.Editor.Extensibility.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo; using Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; using Moq; using Roslyn.Test.EditorUtilities.NavigateTo; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NavigateTo { public class InteractiveNavigateToTests : AbstractNavigateToTests { protected override string Language => "csharp"; protected override TestWorkspace CreateWorkspace(string content, ExportProvider exportProvider) => TestWorkspace.CreateCSharp(content, parseOptions: Options.Script); [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task NoItemsForEmptyFile() { await TestAsync("", async w => { Assert.Empty(await _aggregator.GetItemsAsync("Hello")); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClass() { await TestAsync( @"class Foo { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", "[|Foo|]", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindNestedClass() { await TestAsync( @"class Foo { class Bar { internal class DogBed { } } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("DogBed")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DogBed", "[|DogBed|]", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMemberInANestedClass() { await TestAsync( @"class Foo { class Bar { class DogBed { public void Method() { } } } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Method")).Single(); VerifyNavigateToResultItem(item, "Method", "[|Method|]()", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo.Bar.DogBed"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindGenericClassWithConstraints() { await TestAsync( @"using System.Collections; class Foo<T> where T : IEnumerable { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", "[|Foo|]<T>", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindGenericMethodWithConstraints() { await TestAsync( @"using System; class Foo<U> { public void Bar<T>(T item) where T : IComparable<T> { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|]<T>(T)", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo<U>"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialClass() { await TestAsync( @"public partial class Foo { int a; } partial class Foo { int b; }", async w => { var expecteditem1 = new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Foo"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindTypesInMetadata() { await TestAsync( @"using System; Class Program { FileStyleUriParser f; }", async w => { var items = await _aggregator.GetItemsAsync("FileStyleUriParser"); Assert.Equal(items.Count(), 0); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClassInNamespace() { await TestAsync( @"namespace Bar { class Foo { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", "[|Foo|]", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindStruct() { await TestAsync( @"struct Bar { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupStruct, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("B")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Bar", "[|B|]ar", MatchKind.Prefix, NavigateToItemKind.Structure); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEnum() { await TestAsync( @"enum Colors { Red, Green, Blue }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnum, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Colors")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Colors", "[|Colors|]", MatchKind.Exact, NavigateToItemKind.Enum); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEnumMember() { await TestAsync( @"enum Colors { Red, Green, Blue }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnumMember, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("R")).Single(); VerifyNavigateToResultItem(item, "Red", "[|R|]ed", MatchKind.Prefix, NavigateToItemKind.EnumItem); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindConstField() { await TestAsync( @"class Foo { const int bar = 7; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupConstant, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("ba")).Single(); VerifyNavigateToResultItem(item, "bar", "[|ba|]r", MatchKind.Prefix, NavigateToItemKind.Constant); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindVerbatimIdentifier() { await TestAsync( @"class Foo { string @string; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("string")).Single(); VerifyNavigateToResultItem(item, "string", "[|string|]", MatchKind.Exact, NavigateToItemKind.Field, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindIndexer() { var program = @"class Foo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("this")).Single(); VerifyNavigateToResultItem(item, "this", "[|this|][int]", MatchKind.Exact, NavigateToItemKind.Property, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEvent() { var program = "class Foo { public event EventHandler ChangedEventHandler; }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEvent, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("CEH")).Single(); VerifyNavigateToResultItem(item, "ChangedEventHandler", "[|C|]hanged[|E|]vent[|H|]andler", MatchKind.Regular, NavigateToItemKind.Event, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindAutoProperty() { await TestAsync( @"class Foo { int Bar { get; set; } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("B")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|B|]ar", MatchKind.Prefix, NavigateToItemKind.Property, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMethod() { await TestAsync( @"class Foo { void DoSomething(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething()", MatchKind.Regular, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindParameterizedMethod() { await TestAsync( @"class Foo { void DoSomething(int a, string b) { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething(int, string)", MatchKind.Regular, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindConstructor() { await TestAsync( @"class Foo { public Foo() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Foo", "[|Foo|]()", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindParameterizedConstructor() { await TestAsync( @"class Foo { public Foo(int i) { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Foo", "[|Foo|](int)", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindStaticConstructor() { await TestAsync( @"class Foo { static Foo() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method && t.Name != ".ctor"); VerifyNavigateToResultItem(item, "Foo", "[|Foo|].static Foo()", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethods() { await TestAsync("partial class Foo { partial void Bar(); } partial class Foo { partial void Bar() { Console.Write(\"hello\"); } }", async w => { var expecteditem1 = new NavigateToItem("Bar", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Bar"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethodDefinitionOnly() { await TestAsync( @"partial class Foo { partial void Bar(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindOverriddenMembers() { var program = "class Foo { public virtual string Name { get; set; } } class DogBed : Foo { public override string Name { get { return base.Name; } set {} } }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic); var expecteditem1 = new NavigateToItem("Name", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Name"); VerifyNavigateToResultItems(expecteditems, items); var item = items.ElementAt(0); var itemDisplay = item.DisplayFactory.CreateItemDisplay(item); var unused = itemDisplay.Glyph; Assert.Equal("Name", itemDisplay.Name); Assert.Equal($"{FeaturesResources.type_space}DogBed", itemDisplay.AdditionalInformation); _glyphServiceMock.Verify(); item = items.ElementAt(1); itemDisplay = item.DisplayFactory.CreateItemDisplay(item); unused = itemDisplay.Glyph; Assert.Equal("Name", itemDisplay.Name); Assert.Equal($"{FeaturesResources.type_space}Foo", itemDisplay.AdditionalInformation); _glyphServiceMock.Verify(); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindInterface() { await TestAsync( @"public interface IFoo { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupInterface, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("IF")).Single(); VerifyNavigateToResultItem(item, "IFoo", "[|IF|]oo", MatchKind.Prefix, NavigateToItemKind.Interface); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindDelegateInNamespace() { await TestAsync( @"namespace Foo { delegate void DoStuff(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupDelegate, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("DoStuff")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DoStuff", "[|DoStuff|]", MatchKind.Exact, NavigateToItemKind.Delegate); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindLambdaExpression() { await TestAsync( @"using System; class Foo { Func<int, int> sqr = x => x * x; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("sqr")).Single(); VerifyNavigateToResultItem(item, "sqr", "[|sqr|]", MatchKind.Exact, NavigateToItemKind.Field, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task OrderingOfConstructorsAndTypes() { await TestAsync( @"class C1 { C1(int i) { } } class C2 { C2(float f) { } static C2() { } }", async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("C1", NavigateToItemKind.Class, "csharp", "C1", null, MatchKind.Prefix, true, null), new NavigateToItem("C1", NavigateToItemKind.Method, "csharp", "C1", null, MatchKind.Prefix, true, null), new NavigateToItem("C2", NavigateToItemKind.Class, "csharp", "C2", null, MatchKind.Prefix, true, null), new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), // this is the static ctor new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), }; var items = (await _aggregator.GetItemsAsync("C")).ToList(); items.Sort(CompareNavigateToItems); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task StartStopSanity() { // Verify that multiple calls to start/stop and dispose don't blow up await TestAsync( @"public class Foo { }", async w => { // Do one set of queries Assert.Single((await _aggregator.GetItemsAsync("Foo")).Where(x => x.Kind != "Method")); _provider.StopSearch(); // Do the same query again, make sure nothing was left over Assert.Single((await _aggregator.GetItemsAsync("Foo")).Where(x => x.Kind != "Method")); _provider.StopSearch(); // Dispose the provider _provider.Dispose(); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DescriptionItems() { var code = "public\r\nclass\r\nFoo\r\n{ }"; await TestAsync(code, async w => { var item = (await _aggregator.GetItemsAsync("F")).Single(x => x.Kind != "Method"); var itemDisplay = item.DisplayFactory.CreateItemDisplay(item); var descriptionItems = itemDisplay.DescriptionItems; Action<string, string> assertDescription = (label, value) => { var descriptionItem = descriptionItems.Single(i => i.Category.Single().Text == label); Assert.Equal(value, descriptionItem.Details.Single().Text); }; assertDescription("File:", w.Documents.Single().Name); assertDescription("Line:", "3"); // one based line number assertDescription("Project:", "Test"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest1() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_keyword", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem3 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2, expecteditem3 }; var items = await _aggregator.GetItemsAsync("GK"); Assert.Equal(expecteditems.Count(), items.Count()); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest2() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = await _aggregator.GetItemsAsync("GKW"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest3() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = await _aggregator.GetItemsAsync("K W"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest4() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var items = await _aggregator.GetItemsAsync("WKG"); Assert.Empty(items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest5() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("G_K_W")).Single(); VerifyNavigateToResultItem(item, "get_key_word", "[|g|]et[|_k|]ey[|_w|]ord", MatchKind.Regular, NavigateToItemKind.Field); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest7() { ////Diff from dev10 var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = await _aggregator.GetItemsAsync("K*W"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest8() { ////Diff from dev10 var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var items = await _aggregator.GetItemsAsync("GTW"); Assert.Empty(items); }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.MathUtils; using osu.Framework.Screens; using osu.Game.Configuration; using osu.Game.Graphics.Containers; using osu.Game.Overlays; using osu.Game.Overlays.Notifications; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; using osu.Game.Screens; using osu.Game.Screens.Play; using osu.Game.Screens.Play.PlayerSettings; using osuTK.Input; namespace osu.Game.Tests.Visual.Gameplay { public class TestScenePlayerLoader : ManualInputManagerTestScene { private TestPlayerLoader loader; private TestPlayerLoaderContainer container; private TestPlayer player; [Resolved] private AudioManager audioManager { get; set; } [Resolved] private SessionStatics sessionStatics { get; set; } /// <summary> /// Sets the input manager child to a new test player loader container instance. /// </summary> /// <param name="interactive">If the test player should behave like the production one.</param> /// <param name="beforeLoadAction">An action to run before player load but after bindable leases are returned.</param> /// <param name="afterLoadAction">An action to run after container load.</param> public void ResetPlayer(bool interactive, Action beforeLoadAction = null, Action afterLoadAction = null) { audioManager.Volume.SetDefault(); InputManager.Clear(); beforeLoadAction?.Invoke(); Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo); InputManager.Child = container = new TestPlayerLoaderContainer( loader = new TestPlayerLoader(() => { afterLoadAction?.Invoke(); return player = new TestPlayer(interactive, interactive); })); } [Test] public void TestBlockLoadViaMouseMovement() { AddStep("load dummy beatmap", () => ResetPlayer(false)); AddUntilStep("wait for current", () => loader.IsCurrentScreen()); AddRepeatStep("move mouse", () => InputManager.MoveMouseTo(loader.VisualSettings.ScreenSpaceDrawQuad.TopLeft + (loader.VisualSettings.ScreenSpaceDrawQuad.BottomRight - loader.VisualSettings.ScreenSpaceDrawQuad.TopLeft) * RNG.NextSingle()), 20); AddAssert("loader still active", () => loader.IsCurrentScreen()); AddUntilStep("loads after idle", () => !loader.IsCurrentScreen()); } [Test] public void TestLoadContinuation() { SlowLoadPlayer slowPlayer = null; AddStep("load dummy beatmap", () => ResetPlayer(false)); AddUntilStep("wait for current", () => loader.IsCurrentScreen()); AddStep("mouse in centre", () => InputManager.MoveMouseTo(loader.ScreenSpaceDrawQuad.Centre)); AddUntilStep("wait for player to be current", () => player.IsCurrentScreen()); AddStep("load slow dummy beatmap", () => { InputManager.Child = container = new TestPlayerLoaderContainer( loader = new TestPlayerLoader(() => slowPlayer = new SlowLoadPlayer(false, false))); Scheduler.AddDelayed(() => slowPlayer.AllowLoad.Set(), 5000); }); AddUntilStep("wait for player to be current", () => slowPlayer.IsCurrentScreen()); } [Test] public void TestModReinstantiation() { TestMod gameMod = null; TestMod playerMod1 = null; TestMod playerMod2 = null; AddStep("load player", () => { ResetPlayer(true, () => Mods.Value = new[] { gameMod = new TestMod() }); }); AddUntilStep("wait for loader to become current", () => loader.IsCurrentScreen()); AddStep("mouse in centre", () => InputManager.MoveMouseTo(loader.ScreenSpaceDrawQuad.Centre)); AddUntilStep("wait for player to be current", () => player.IsCurrentScreen()); AddStep("retrieve mods", () => playerMod1 = (TestMod)player.Mods.Value.Single()); AddAssert("game mods not applied", () => gameMod.Applied == false); AddAssert("player mods applied", () => playerMod1.Applied); AddStep("restart player", () => { var lastPlayer = player; player = null; lastPlayer.Restart(); }); AddUntilStep("wait for player to be current", () => player.IsCurrentScreen()); AddStep("retrieve mods", () => playerMod2 = (TestMod)player.Mods.Value.Single()); AddAssert("game mods not applied", () => gameMod.Applied == false); AddAssert("player has different mods", () => playerMod1 != playerMod2); AddAssert("player mods applied", () => playerMod2.Applied); } [Test] public void TestMutedNotificationMasterVolume() => addVolumeSteps("master volume", () => audioManager.Volume.Value = 0, null, () => audioManager.Volume.IsDefault); [Test] public void TestMutedNotificationTrackVolume() => addVolumeSteps("music volume", () => audioManager.VolumeTrack.Value = 0, null, () => audioManager.VolumeTrack.IsDefault); [Test] public void TestMutedNotificationMuteButton() => addVolumeSteps("mute button", null, () => container.VolumeOverlay.IsMuted.Value = true, () => !container.VolumeOverlay.IsMuted.Value); /// <remarks> /// Created for avoiding copy pasting code for the same steps. /// </remarks> /// <param name="volumeName">What part of the volume system is checked</param> /// <param name="beforeLoad">The action to be invoked to set the volume before loading</param> /// <param name="afterLoad">The action to be invoked to set the volume after loading</param> /// <param name="assert">The function to be invoked and checked</param> private void addVolumeSteps(string volumeName, Action beforeLoad, Action afterLoad, Func<bool> assert) { AddStep("reset notification lock", () => sessionStatics.GetBindable<bool>(Static.MutedAudioNotificationShownOnce).Value = false); AddStep("load player", () => ResetPlayer(false, beforeLoad, afterLoad)); AddUntilStep("wait for player", () => player.IsLoaded); AddAssert("check for notification", () => container.NotificationOverlay.UnreadCount.Value == 1); AddStep("click notification", () => { var scrollContainer = (OsuScrollContainer)container.NotificationOverlay.Children.Last(); var flowContainer = scrollContainer.Children.OfType<FillFlowContainer<NotificationSection>>().First(); var notification = flowContainer.First(); InputManager.MoveMouseTo(notification); InputManager.Click(MouseButton.Left); }); AddAssert("check " + volumeName, assert); } private class TestPlayerLoaderContainer : Container { [Cached] public readonly NotificationOverlay NotificationOverlay; [Cached] public readonly VolumeOverlay VolumeOverlay; public TestPlayerLoaderContainer(IScreen screen) { RelativeSizeAxes = Axes.Both; InternalChildren = new Drawable[] { new OsuScreenStack(screen) { RelativeSizeAxes = Axes.Both, }, NotificationOverlay = new NotificationOverlay { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, }, VolumeOverlay = new VolumeOverlay { Anchor = Anchor.TopLeft, Origin = Anchor.TopLeft, } }; } } private class TestPlayerLoader : PlayerLoader { public new VisualSettings VisualSettings => base.VisualSettings; public TestPlayerLoader(Func<Player> createPlayer) : base(createPlayer) { } } private class TestMod : Mod, IApplicableToScoreProcessor { public override string Name => string.Empty; public override string Acronym => string.Empty; public override double ScoreMultiplier => 1; public bool Applied { get; private set; } public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { Applied = true; } public ScoreRank AdjustRank(ScoreRank rank, double accuracy) => rank; } private class TestPlayer : Visual.TestPlayer { public new Bindable<IReadOnlyList<Mod>> Mods => base.Mods; public TestPlayer(bool allowPause = true, bool showResults = true) : base(allowPause, showResults) { } } protected class SlowLoadPlayer : Visual.TestPlayer { public readonly ManualResetEventSlim AllowLoad = new ManualResetEventSlim(false); public SlowLoadPlayer(bool allowPause = true, bool showResults = true) : base(allowPause, showResults) { } [BackgroundDependencyLoader] private void load() { if (!AllowLoad.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException(); } } } }
#region Using directives using System; using System.Management.Automation; using System.Management.Automation.SecurityAccountsManager; using System.Management.Automation.SecurityAccountsManager.Extensions; using Microsoft.PowerShell.LocalAccounts; using System.Diagnostics.CodeAnalysis; #endregion namespace Microsoft.PowerShell.Commands { /// <summary> /// The Remove-LocalUser cmdlet deletes a user account from the Windows Security /// Accounts manager. /// </summary> [Cmdlet(VerbsCommon.Remove, "LocalUser", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717982")] [Alias("rlu")] public class RemoveLocalUserCommand : Cmdlet { #region Instance Data private Sam sam = null; #endregion Instance Data #region Parameter Properties /// <summary> /// The following is the definition of the input parameter "InputObject". /// Specifies the of the local user accounts to remove in the local Security /// Accounts Manager. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "InputObject")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Microsoft.PowerShell.Commands.LocalUser[] InputObject { get { return this.inputobject;} set { this.inputobject = value; } } private Microsoft.PowerShell.Commands.LocalUser[] inputobject; /// <summary> /// The following is the definition of the input parameter "Name". /// Specifies the user accounts to be deleted from the local Security Accounts /// Manager. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Default")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Name { get { return this.name; } set { this.name = value; } } private string[] name; /// <summary> /// The following is the definition of the input parameter "SID". /// Specifies the local user accounts to remove by /// System.Security.Principal.SecurityIdentifier. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "SecurityIdentifier")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public System.Security.Principal.SecurityIdentifier[] SID { get { return this.sid; } set { this.sid = value; } } private System.Security.Principal.SecurityIdentifier[] sid; #endregion Parameter Properties #region Cmdlet Overrides /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { sam = new Sam(); } /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { try { ProcessUsers(); ProcessNames(); ProcessSids(); } catch (Exception ex) { WriteError(ex.MakeErrorRecord()); } } /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { if (sam != null) { sam.Dispose(); sam = null; } } #endregion Cmdlet Overrides #region Private Methods /// <summary> /// Process users requested by -Name /// </summary> /// <remarks> /// All arguments to -Name will be treated as names, /// even if a name looks like a SID. /// </remarks> private void ProcessNames() { if (Name != null) { foreach (var name in Name) { try { if (CheckShouldProcess(name)) sam.RemoveLocalUser(sam.GetLocalUser(name)); } catch (Exception ex) { WriteError(ex.MakeErrorRecord()); } } } } /// <summary> /// Process users requested by -SID /// </summary> private void ProcessSids() { if (SID != null) { foreach (var sid in SID) { try { if (CheckShouldProcess(sid.ToString())) sam.RemoveLocalUser(sid); } catch (Exception ex) { WriteError(ex.MakeErrorRecord()); } } } } /// <summary> /// Process users given through -InputObject /// </summary> private void ProcessUsers() { if (InputObject != null) { foreach (var user in InputObject) { try { if (CheckShouldProcess(user.Name)) sam.RemoveLocalUser(user); } catch (Exception ex) { WriteError(ex.MakeErrorRecord()); } } } } private bool CheckShouldProcess(string target) { return ShouldProcess(target, Strings.ActionRemoveUser); } #endregion Private Methods }//End Class }//End namespace
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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.Windows.Forms; using System.Collections.Generic; using System.Text; using Axiom.MathLib; using Axiom.Core; using Axiom.Animating; using System.ComponentModel; using System.Xml; using Multiverse.CollisionLib; using Multiverse.ToolBox; namespace Multiverse.Tools.WorldEditor { public class StaticObject : IWorldObject, IObjectPosition, IObjectScale, IWorldContainer, IObjectDrag, IObjectChangeCollection, IObjectDelete, IObjectCutCopy, IObjectCameraLockable, IObjectOrientation { protected DisplayObject displayObject; protected String name; protected IWorldContainer parent; protected WorldEditor app; protected WorldTreeNode node = null; protected WorldTreeNode parentNode = null; protected List<IWorldObject> children; protected Vector3 rotation; protected Vector3 direction; protected Vector3 scale; protected Vector3 location; protected Quaternion orientation; protected bool locationDirty = true; protected PathData pathData; protected String meshName; protected bool highlight = false; protected bool inTree = false; protected bool inScene = false; protected SubMeshCollection subMeshes; protected NameValueObject nameValuePairs; protected float terrainOffset = 0; protected bool allowAdjustHeightOffTerrain = true; protected bool offsetFound = false; protected bool castShadows = true; protected bool receiveShadows = true; protected bool acceptObjectPlacement = false; protected bool worldViewSelectable = true; protected float azimuth; protected float zenith; protected bool targetable = false; protected string soundAssetName = null; protected List<ToolStripButton> buttonBar; protected float perceptionRadius = 0; public StaticObject(String objectName, IWorldContainer parentContainer, WorldEditor worldEditor, string meshName, Vector3 position, Vector3 scale, Vector3 rotation) { name = objectName; parent = parentContainer; app = worldEditor; children = new List<IWorldObject>(); this.SetDirection(rotation.y, 90f); this.scale = scale; this.location = position; this.meshName = meshName; this.nameValuePairs = new NameValueObject(); this.terrainOffset = 0f; displayObject = null; subMeshes = new SubMeshCollection(meshName); } public StaticObject(IWorldContainer parentContainer, WorldEditor worldEditor, XmlReader r) { parent = parentContainer; app = worldEditor; children = new List<IWorldObject>(); FromXml(r); if (nameValuePairs == null) { nameValuePairs = new NameValueObject(); } } protected void FromXml(XmlReader r) { bool adjustHeightFound = false; bool offsetFound = false; bool pRFound = false; // first parse name and mesh, which are attributes for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); // set the field in this object based on the element we just read switch (r.Name) { case "Name": this.name = r.Value; break; case "Mesh": this.meshName = r.Value; break; case "Sound": string filename = r.Value; if (!String.Equals(filename, "")) { ICommandFactory ret = new AddSoundCommandFactory(app, this, r.Value); ICommand com = ret.CreateCommand(); com.Execute(); } break; case "TerrainOffset": terrainOffset = float.Parse(r.Value); offsetFound = true; break; case "AllowHeightAdjustment": if (String.Equals(r.Value.ToLower(), "false")) { allowAdjustHeightOffTerrain = false; } break; case "AcceptObjectPlacement": acceptObjectPlacement = bool.Parse(r.Value); break; case "PerceptionRadius": pRFound = true; perceptionRadius = float.Parse(r.Value); break; case "CastShadows": castShadows = bool.Parse(r.Value); break; case "ReceiveShadows": receiveShadows = bool.Parse(r.Value); break; case "Azimuth": azimuth = float.Parse(r.Value); break; case "Zenith": zenith = float.Parse(r.Value); break; case "WorldViewSelect": worldViewSelectable = bool.Parse(r.Value); break; case "Targetable": targetable = bool.Parse(r.Value); break; } } r.MoveToElement(); //Moves the reader back to the element node. // now parse the sub-elements while (r.Read()) { // look for the start of an element if (r.NodeType == XmlNodeType.Element) { // parse that element // save the name of the element string elementName = r.Name; switch (elementName) { case "Position": location = XmlHelperClass.ParseVectorAttributes(r); break; case "Scale": scale = XmlHelperClass.ParseVectorAttributes(r); break; case "Rotation": Vector3 rotation = XmlHelperClass.ParseVectorAttributes(r); // force rotation to be between -180 and 180 while (rotation.y < -180) { rotation.y += 360; } while (rotation.y > 180) { rotation.y -= 360; } SetDirection(rotation.y, 90f); break; case "Orientation": orientation = XmlHelperClass.ParseQuaternion(r); break; case "SubMeshes": subMeshes = new SubMeshCollection(r); if (!subMeshes.CheckValid(app, meshName)) { app.AddPopupMessage(string.Format("Some submesh names in {0} changed. Submesh display and material parameters for this object were reset.", meshName)); // if the check fails, then reset the subMeshes from the mesh subMeshes = new SubMeshCollection(meshName); } break; case "NameValuePairs": nameValuePairs = new NameValueObject(r); break; case "ParticleEffect": ParticleEffect particle = new ParticleEffect(r, this, app); Add(particle); break; case "PathData": pathData = new PathData(r); locationDirty = pathData.Version != pathData.CodeVersion; break; case "Sound": Sound sound = new Sound(r, this, app); Add(sound); break; } } else if (r.NodeType == XmlNodeType.EndElement) { break; } } if (!adjustHeightFound) { allowAdjustHeightOffTerrain = true; } if (!offsetFound) { terrainOffset = location.y - app.GetTerrainHeight(location.x, location.z); } if (!pRFound && nameValuePairs != null) { valueItem value = nameValuePairs.LookUp("perceptionRadius"); if (value != null && ValidityHelperClass.isFloat(value.value)) { perceptionRadius = float.Parse(value.value); } } return; } [BrowsableAttribute(false)] public float Radius { get { if (inScene && displayObject != null) { return displayObject.Radius; } else { return 0f; } } } [BrowsableAttribute(false)] public Vector3 Center { get { if (inScene && displayObject != null) { return displayObject.Center; } else { return Vector3.Zero; } } } [BrowsableAttribute(false)] public List<string> AttachmentPoints { get { List<string> attachmentPoints = new List<string>(); Mesh mesh = MeshManager.Instance.Load(meshName); for (int i = 0; i < mesh.AttachmentPoints.Count; i++) { AttachmentPoint attachmentPoint = mesh.AttachmentPoints[i] as AttachmentPoint; attachmentPoints.Add(attachmentPoint.Name); } if (mesh.Skeleton != null) { for (int i = 0; i < mesh.Skeleton.AttachmentPoints.Count; i++) { AttachmentPoint attachmentPoint = mesh.Skeleton.AttachmentPoints[i] as AttachmentPoint; attachmentPoints.Add(attachmentPoint.Name); } } //mesh.Dispose(); return attachmentPoints; } } [BrowsableAttribute(false)] public DisplayObject DisplayObject { get { return displayObject; } } [BrowsableAttribute(false)] public DisplayObject Display { get { return displayObject; } } public void SetCamera(Camera cam, CameraDirection dir) { AxisAlignedBox boundingBox = displayObject.BoundingBox; // find the size along the largest axis float size = Math.Max(Math.Max(boundingBox.Size.x, boundingBox.Size.y), boundingBox.Size.z); Vector3 dirVec; switch (dir) { default: case CameraDirection.Above: // for some reason axiom messes up the camera matrix when you point // the camera directly down, so this vector is ever so slightly off // from negative Y. dirVec = new Vector3(0.0001f, -1f, 0f); dirVec.Normalize(); break; case CameraDirection.North: dirVec = Vector3.UnitZ; break; case CameraDirection.South: dirVec = Vector3.NegativeUnitZ; break; case CameraDirection.West: dirVec = Vector3.UnitX; break; case CameraDirection.East: dirVec = Vector3.NegativeUnitX; break; } cam.Position = boundingBox.Center + (size * 2 * (-dirVec)); cam.Direction = dirVec; } [BrowsableAttribute(true), DescriptionAttribute("Whether the object preserves the height above terrain when the terrain is changed or the object is dragged or pasted to another location."), CategoryAttribute("Miscellaneous")] public bool AllowAdjustHeightOffTerrain { get { return allowAdjustHeightOffTerrain; } set { allowAdjustHeightOffTerrain = value; } } [BrowsableAttribute(true), DescriptionAttribute("This allows you to select if an object casts shadows."), CategoryAttribute("Display Propeties")] public bool CastShadows { get { return castShadows; } set { castShadows = value; if (inScene && displayObject != null) { displayObject.CastShadows = value; } } } [BrowsableAttribute(false)] public bool ReceiveShadows { get { return receiveShadows; } set { receiveShadows = value; } } [BrowsableAttribute(true), DescriptionAttribute("Used by the Multiverse World Browser to determine if an object is targetable."), CategoryAttribute("Miscellaneous")] public bool Targetable { get { return targetable; } set { targetable = value; } } #region IWorldObject Members public void AddToTree(WorldTreeNode parentNode) { if (parentNode != null) { this.parentNode = parentNode; inTree = true; // create a node for the collection and add it to the parent node = app.MakeTreeNode(this, NodeName); parentNode.Nodes.Add(node); // build the menu CommandMenuBuilder menuBuilder = new CommandMenuBuilder(); if (AttachmentPoints.Count > 0) { menuBuilder.Add("Attach Particle Effect", new AddObjectParticleEffectCommandFactory(app, this), app.DefaultCommandClickHandler); } menuBuilder.Add("Add Sound", new AddSoundCommandFactory(app, this), app.DefaultCommandClickHandler); menuBuilder.AddDropDown("View From"); menuBuilder.Add("Above", new DirectionAndObject(CameraDirection.Above, this), app.CameraObjectDirClickHandler); menuBuilder.Add("North", new DirectionAndObject(CameraDirection.North, this), app.CameraObjectDirClickHandler); menuBuilder.Add("South", new DirectionAndObject(CameraDirection.South, this), app.CameraObjectDirClickHandler); menuBuilder.Add("West", new DirectionAndObject(CameraDirection.West, this), app.CameraObjectDirClickHandler); menuBuilder.Add("East", new DirectionAndObject(CameraDirection.East, this), app.CameraObjectDirClickHandler); menuBuilder.FinishDropDown(); menuBuilder.Add("Drag Object", new DragObjectsFromMenuCommandFactory(app), app.DefaultCommandClickHandler); menuBuilder.AddDropDown("Move to Collection", menuBuilder.ObjectCollectionDropDown_Opening); menuBuilder.FinishDropDown(); menuBuilder.Add("Copy Description", "", app.copyToClipboardMenuButton_Click); menuBuilder.Add("Help", "Object", app.HelpClickHandler); menuBuilder.Add("Delete", new DeleteObjectCommandFactory(app, parent, this), app.DefaultCommandClickHandler); // menuBuilder.Add("Generate Model Paths", new GenerateModelPathsCommandFactory(this), app.DefaultCommandClickHandler); node.ContextMenuStrip = menuBuilder.Menu; foreach (IWorldObject child in children) { child.AddToTree(node); } buttonBar = menuBuilder.ButtonBar; } } [BrowsableAttribute(false)] public bool IsGlobal { get { return false; } } [BrowsableAttribute(false)] public bool IsTopLevel { get { return true; } } [CategoryAttribute("Miscellaneous"), DescriptionAttribute("Sets if the object may be selected in the world view")] public bool WorldViewSelectable { get { return worldViewSelectable; } set { worldViewSelectable = value; } } public void Clone(IWorldContainer copyParent) { StaticObject clone = new StaticObject(name, copyParent, app, meshName, Position, scale, rotation); clone.ReceiveShadows = receiveShadows; clone.CastShadows = castShadows; clone.AllowAdjustHeightOffTerrain = allowAdjustHeightOffTerrain; clone.SubMeshes = new SubMeshCollection(this.SubMeshes); clone.NameValue = new NameValueObject(this.NameValue); clone.TerrainOffset = terrainOffset; foreach (IWorldObject child in children) { child.Clone(clone); } copyParent.Add(clone); } [BrowsableAttribute(false)] public string ObjectAsString { get { string objString = String.Format("Name:{0}\r\n", this.NodeName); objString += String.Format("\tAllowAdjustHeightOffTerrain={0}\r\n", AllowAdjustHeightOffTerrain); objString += String.Format("\tWorldViewSelectable = {0}\r\n", worldViewSelectable.ToString()); objString += String.Format("\tAcceptObjectPlacement = {0}\r\n", acceptObjectPlacement.ToString()); objString += String.Format("\tPerceptionRadius={0}\r\n", PerceptionRadius); objString += String.Format("\tMeshName={0}\r\n", MeshName); objString += String.Format("\tCastShadows={0}\r\n", castShadows); objString += String.Format("\tPosition=({0},{1},{2})\r\n", location.x, location.y, location.z); objString += String.Format("\tOrientation=({0},{1},{2},{3})\r\n", orientation.w, orientation.x, orientation.y, orientation.z); objString += String.Format("\tTargetable={0}\r\n", targetable); //objString += String.Format("\tReceiveShadows={0}", recieveShadows); objString += "\r\n"; return objString; } } [BrowsableAttribute(false)] public List<ToolStripButton> ButtonBar { get { return buttonBar; } } public void RemoveFromTree() { if (node != null && parentNode != null) { if (node != null && node.IsSelected) { node.UnSelect(); } foreach (IWorldObject child in children) { child.RemoveFromTree(); } parentNode.Nodes.Remove(node); parentNode = null; node = null; } } [BrowsableAttribute(true), DescriptionAttribute("This allows you to set the distance at which the object can be seen, in millimeters. 0 means it will be displayed out to the normal perception radius of the player."), CategoryAttribute("Display Propeties")] public float PerceptionRadius { get { return perceptionRadius; } set { perceptionRadius = value; } } public void AddToScene() { if (!inScene) { if (!offsetFound) { terrainOffset = location.y - app.GetTerrainHeight(location.x, location.z); offsetFound = true; } inScene = true; displayObject = new DisplayObject(this, name, app, "StaticObject", app.Scene, meshName, location, scale, orientation, subMeshes); displayObject.TerrainOffset = this.terrainOffset; displayObject.Highlight = highlight; displayObject.CastShadows = castShadows; // Create the list of triangles used to query mouse hits if (displayObject.Entity.Mesh.TriangleIntersector == null) displayObject.Entity.Mesh.CreateTriangleIntersector(); } foreach (IWorldObject child in children) { child.AddToScene(); if (child is ParticleEffect) { (child as ParticleEffect).Orientation = orientation; } } } public void UpdateScene(UpdateTypes type, UpdateHint hint) { foreach (IWorldObject child in children) { child.UpdateScene(type, hint); } if ((type == UpdateTypes.All || type == UpdateTypes.Object) && hint == UpdateHint.TerrainUpdate && allowAdjustHeightOffTerrain) { this.location.y = app.GetTerrainHeight(location.x, location.z) + terrainOffset; } } public void RemoveFromScene() { if (inScene) { inScene = false; foreach (IWorldObject child in children) { child.RemoveFromScene(); } displayObject.Dispose(); displayObject = null; } } public void CheckAssets() { if (!app.CheckAssetFileExists(meshName)) { app.AddMissingAsset(meshName); } foreach (IWorldObject child in children) { child.CheckAssets(); } } protected void MaybeGeneratePathData() { PathObjectTypeContainer pathObjectTypes = WorldRoot.Instance.PathObjectTypes; if (pathObjectTypes.Count == 0) PathData = null; else if (WorldRoot.Instance.PathObjectTypes.AllObjectsDirty || locationDirty) { List<CollisionShape> meshShapes = WorldEditor.Instance.FindMeshCollisionShapes(meshName, displayObject.Entity); if (meshShapes.Count == 0) PathData = null; else { PathData = new PathData(); float terrainHeight = WorldEditor.Instance.GetTerrainHeight(location.x, location.z) - location.y; for (int i=0; i<pathObjectTypes.Count; i++) { PathObjectType type = pathObjectTypes.GetType(i); try { PathData.AddModelPathObject(WorldEditor.Instance.LogPathGeneration, type, name, location, displayObject.SceneNode.FullTransform, meshShapes, terrainHeight); } catch (Exception e) { MessageBox.Show(string.Format("An exception was raised when generating pathing information for " + "model {0}, for path object type {1}. The exception message was '{2}'. Please run the World " + "Editor again, with the command-line option --log_paths, save the world file to generate " + "pathing information, and zip up the generated file " + "PathGenerationLog.txt, found in the World Editor's bin directory, and send it to Multiverse, " + "along with the {3} file so the problem can be identified and fixed.", name, type.name, e.Message, meshName), "Error Generating Path Information For Model " + name + "!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } } public void ToXml(XmlWriter w) { MaybeGeneratePathData(); w.WriteStartElement("StaticObject"); w.WriteAttributeString("Name", this.Name); w.WriteAttributeString("Mesh", this.meshName); w.WriteAttributeString("TerrainOffest", this.terrainOffset.ToString()); w.WriteAttributeString("AllowHeightAdjustment", this.AllowAdjustHeightOffTerrain.ToString()); w.WriteAttributeString("WorldViewSelect", worldViewSelectable.ToString()); w.WriteAttributeString("AcceptObjectPlacement", acceptObjectPlacement.ToString()); w.WriteAttributeString("PerceptionRadius", this.perceptionRadius.ToString()); w.WriteAttributeString("CastShadows", this.castShadows.ToString()); w.WriteAttributeString("Azimuth", this.azimuth.ToString()); w.WriteAttributeString("Zenith", this.zenith.ToString()); w.WriteAttributeString("Targetable", this.targetable.ToString()); //w.WriteAttributeString("ReceiveShadows", this.receiveShadows.ToString()); w.WriteStartElement("Position"); w.WriteAttributeString("x", this.Position.x.ToString()); w.WriteAttributeString("y", this.Position.y.ToString()); w.WriteAttributeString("z", this.Position.z.ToString()); w.WriteEndElement(); // Position end w.WriteStartElement("Scale"); w.WriteAttributeString("x", this.scale.x.ToString()); w.WriteAttributeString("y", this.scale.y.ToString()); w.WriteAttributeString("z", this.scale.z.ToString()); w.WriteEndElement(); // Scale end w.WriteStartElement("Orientation"); w.WriteAttributeString("x", Orientation.x.ToString()); w.WriteAttributeString("y", Orientation.y.ToString()); w.WriteAttributeString("z", Orientation.z.ToString()); w.WriteAttributeString("w", Orientation.w.ToString()); w.WriteEndElement(); // Orientation end //w.WriteStartElement("Rotation"); //w.WriteAttributeString("x", this.rotation.x.ToString()); //w.WriteAttributeString("y", this.rotation.y.ToString()); //w.WriteAttributeString("z", this.rotation.z.ToString()); //w.WriteEndElement(); // Rotation end subMeshes.ToXml(w); nameValuePairs.ToXml(w); if (pathData != null) pathData.ToXml(w); foreach (IWorldObject child in children) { child.ToXml(w); } w.WriteEndElement(); // StaticObject end; } [BrowsableAttribute(false)] public float Rotation { get { return rotation.y; } set { if (value != rotation.y) { locationDirty = true; rotation = new Vector3(0, value, 0); if (inScene) { displayObject.SetRotation(value); } } } } [BrowsableAttribute(false)] public float Scale { get { return scale.y; } set { if (scale.x != value) { locationDirty = true; scale = new Vector3(value, value, value); if (inScene) { displayObject.Scale = scale; } } } } [BrowsableAttribute(false)] public Vector3 FocusLocation { get { return Position; } } [BrowsableAttribute(false)] public bool Highlight { get { return highlight; } set { highlight = value; if (displayObject != null) { displayObject.Highlight = highlight; } } } [BrowsableAttribute(false)] public WorldTreeNode Node { get { return node; } } [DescriptionAttribute("The name of this object."), CategoryAttribute("Miscellaneous")] public String Name { get { return name; } set { name = value; locationDirty = true; UpdateNode(); } } protected void UpdateNode() { if (inTree) { node.Text = NodeName; } } protected string NodeName { get { string ret; if (app.Config.ShowTypeLabelsInTreeView) { ret = string.Format("{0}: {1}", ObjectType, name); } else { ret = name; } return ret; } } [BrowsableAttribute(true), DescriptionAttribute("This shows the mesh name of the model"), CategoryAttribute("Display Propeties")] public string MeshName { get { return meshName; } } [EditorAttribute(typeof(SubmeshUITypeEditor),typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Which submeshes of a model are displayed. Click [...] to view the submeshes and assign different materials to them."), CategoryAttribute("Display Propeties")] public SubMeshCollection SubMeshes { get { return subMeshes; } set { subMeshes = value; if (inScene) { displayObject.SubMeshCollection = subMeshes; } } } [EditorAttribute(typeof(NameValueUITypeEditorObject), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Arbitrary Name/Value pair used to pass information about an object to server scripts and plug-ins. Click [...] to add or edit name/value pairs."), CategoryAttribute("Miscellaneous")] public NameValueObject NameValue { get { return nameValuePairs; } set { nameValuePairs = value; } } public void ToManifest(System.IO.StreamWriter w) { w.WriteLine("Mesh:{0}", meshName); // output any materials that have been set manually subMeshes.ToManifest(w, meshName); if (children != null) { foreach (IWorldObject child in children) { child.ToManifest(w); } } } #endregion IWorldObject #region IObjectPosition [BrowsableAttribute(false)] public bool AllowYChange { get { return true; } } [BrowsableAttribute(false)] public bool InScene { get { return inScene; } } [BrowsableAttribute(false)] public Vector3 Position { get { return location; } set { Vector3 position = value; terrainOffset = position.y - app.GetTerrainHeight(position.x, position.z); if ((location - value).LengthSquared > 0.0001f) { locationDirty = true; location = value; if (inScene) { displayObject.Position = location; displayObject.TerrainOffset = terrainOffset; } } } } [DescriptionAttribute("If true allows other objects to be placed on the object."), CategoryAttribute("Miscellaneous")] public bool AcceptObjectPlacement { get { return acceptObjectPlacement; } set { acceptObjectPlacement = value; } } [BrowsableAttribute(false)] public float TerrainOffset { get { return terrainOffset; } set { terrainOffset = value; if (inScene) { this.DisplayObject.TerrainOffset = terrainOffset; } } } #endregion IObjectPosition #region IDisposable Members public void Dispose() { if (displayObject != null) { displayObject.Dispose(); displayObject = null; } } #endregion #region IObjectDrag Members [BrowsableAttribute(true), DescriptionAttribute("The type of this object."), CategoryAttribute("Miscellaneous")] public string ObjectType { get { return "Object"; } } [BrowsableAttribute(false)] public IWorldContainer Parent { get { return parent; } set { parent = value; } } #endregion IObjectDrag Members #region ICollection<IWorldObject> Members public void Add(IWorldObject item) { children.Add(item); if (inTree) { item.AddToTree(node); } if (inScene) { item.AddToScene(); } } public void Clear() { children.Clear(); } public bool Contains(IWorldObject item) { return children.Contains(item); } public void CopyTo(IWorldObject[] array, int arrayIndex) { children.CopyTo(array, arrayIndex); } [BrowsableAttribute(false)] public int Count { get { return children.Count; } } [BrowsableAttribute(false)] public bool IsReadOnly { get { return false; } } [BrowsableAttribute(false)] public bool LocationDirty { get { return locationDirty; } set { locationDirty = value; } } [BrowsableAttribute(false)] public PathData PathData { get { return pathData; } set { pathData = value; } } [BrowsableAttribute(false)] public float MeshHeight { get { return 0f; } } public bool Remove(IWorldObject item) { item.RemoveFromTree(); item.RemoveFromScene(); return children.Remove(item); } #endregion #region IEnumerable<IWorldObject> Members public IEnumerator<IWorldObject> GetEnumerator() { return children.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion #region IObjectOrientation Members [DescriptionAttribute("The Orientation of this marker in the world"), BrowsableAttribute(false)] public Quaternion Orientation { get { return orientation; } } public void SetDirection(float lightAzimuth, float lightZenith) { this.azimuth = lightAzimuth; this.zenith = lightZenith; UpdateOrientation(); } [BrowsableAttribute(false)] public float Azimuth { get { return azimuth; } set { azimuth = value; UpdateOrientation(); } } [BrowsableAttribute(false)] public float Zenith { get { return zenith; } set { zenith = value; UpdateOrientation(); } } protected void UpdateOrientation() { Quaternion azimuthRotation = Quaternion.FromAngleAxis(MathUtil.DegreesToRadians(azimuth), Vector3.UnitY); Quaternion zenithRotation = Quaternion.FromAngleAxis(MathUtil.DegreesToRadians(-zenith), Vector3.UnitX); Quaternion displayZenithRotation = Quaternion.FromAngleAxis(MathUtil.DegreesToRadians(-Zenith + 90), Vector3.UnitX); orientation = azimuthRotation * displayZenithRotation; if (inScene) { this.displayObject.SetOrientation(orientation); } foreach (IWorldObject child in children) { if (child is ParticleEffect) { (child as ParticleEffect).Orientation = this.orientation; } } } #endregion IObjectOrientation Members } public enum CameraDirection { Above, North, South, East, West } /// <summary> /// This class is used to hold a direction and object, and set a camera based on them. /// </summary> public class DirectionAndObject { CameraDirection dir; StaticObject obj; public DirectionAndObject(CameraDirection dir, StaticObject obj) { this.dir = dir; this.obj = obj; } public void SetCamera(Camera cam) { obj.SetCamera(cam, dir); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using global::System; using global::System.Reflection; using global::System.Collections.Generic; using global::Internal.Runtime.Augments; using global::Internal.Reflection.Core; using global::Internal.Reflection.Core.Execution; using global::Internal.Reflection.Execution.MethodInvokers; using global::Internal.Metadata.NativeFormat; using global::System.Runtime.CompilerServices; using global::System.Runtime.InteropServices; using global::Internal.Runtime; using Debug = System.Diagnostics.Debug; using TargetException = System.ArgumentException; namespace Internal.Reflection.Execution { internal sealed partial class ExecutionEnvironmentImplementation : ExecutionEnvironment { internal unsafe struct MetadataTable : IEnumerable<IntPtr> { public readonly uint ElementCount; int _elementSize; byte* _blob; public struct Enumerator : IEnumerator<IntPtr> { byte* _base; byte* _current; byte* _limit; int _elementSize; internal Enumerator(ref MetadataTable table) { _base = table._blob; _elementSize = table._elementSize; _current = _base - _elementSize; _limit = _base + (_elementSize * table.ElementCount); } public IntPtr Current { get { return (IntPtr)_current; } } public void Dispose() { } object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { _current += _elementSize; if (_current < _limit) { return true; } _current = _limit; return false; } public void Reset() { _current = _base - _elementSize; } } public MetadataTable(IntPtr moduleHandle, ReflectionMapBlob blobId, int elementSize) { Debug.Assert(elementSize != 0); _elementSize = elementSize; byte* pBlob; uint cbBlob; if (!RuntimeAugments.FindBlob(moduleHandle, (int)blobId, new IntPtr(&pBlob), new IntPtr(&cbBlob))) { pBlob = null; cbBlob = 0; } Debug.Assert(cbBlob % elementSize == 0); _blob = pBlob; ElementCount = cbBlob / (uint)elementSize; } public IntPtr this[uint index] { get { Debug.Assert(index < ElementCount); return (IntPtr)(_blob + (index * _elementSize)); } } public Enumerator GetEnumerator() { return new Enumerator(ref this); } IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator() { return GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } struct ExternalReferencesTable { unsafe uint* _base; uint _count; IntPtr _moduleHandle; unsafe public ExternalReferencesTable(IntPtr moduleHandle, ReflectionMapBlob blobId) { _moduleHandle = moduleHandle; uint* pBlob; uint cbBlob; if (RuntimeAugments.FindBlob(moduleHandle, (int)blobId, (IntPtr)(&pBlob), (IntPtr)(&cbBlob))) { _count = cbBlob / sizeof(uint); _base = pBlob; } else { _count = 0; _base = null; } } unsafe public uint GetRvaFromIndex(uint index) { Debug.Assert(_moduleHandle != IntPtr.Zero); if (index >= _count) throw new BadImageFormatException(); return _base[index]; } unsafe public IntPtr GetIntPtrFromIndex(uint index) { uint rva = GetRvaFromIndex(index); if ((rva & 0x80000000) != 0) { // indirect through IAT return *(IntPtr*)((byte*)_moduleHandle + (rva & ~0x80000000)); } else { return (IntPtr)((byte*)_moduleHandle + rva); } } public RuntimeTypeHandle GetRuntimeTypeHandleFromIndex(uint index) { return RuntimeAugments.CreateRuntimeTypeHandle(GetIntPtrFromIndex(index)); } } [StructLayout(LayoutKind.Sequential)] struct TypeMapEntry { public uint EETypeRva; public int TypeDefinitionHandle; } [StructLayout(LayoutKind.Sequential)] struct BlockReflectionTypeMapEntry { public uint EETypeRva; } [StructLayout(LayoutKind.Sequential)] struct ArrayMapEntry { public uint ElementEETypeRva; public uint ArrayEETypeRva; } [StructLayout(LayoutKind.Sequential)] struct GenericInstanceMapEntry { public uint TypeSpecEETypeRva; public uint TypeDefEETypeRva; public uint ArgumentIndex; } struct DynamicInvokeMapEntry { public const uint IsImportMethodFlag = 0x40000000; public const uint InstantiationDetailIndexMask = 0x3FFFFFFF; } [Flags] enum InvokeTableFlags : uint { HasVirtualInvoke = 0x00000001, IsGenericMethod = 0x00000002, HasMetadataHandle = 0x00000004, IsDefaultConstructor = 0x00000008, RequiresInstArg = 0x00000010, HasEntrypoint = 0x00000020, IsUniversalCanonicalEntry = 0x00000040, HasDefaultParameters = 0x00000080, } struct VirtualInvokeTableEntry { public const int GenericVirtualMethod = 1; public const int FlagsMask = 1; } static class FieldAccessFlags { public const int RemoteStaticFieldRVA = unchecked((int)0x80000000); } [Flags] enum FieldTableFlags : uint { Instance = 0x00, Static = 0x01, ThreadStatic = 0x02, StorageClass = 0x03, IsUniversalCanonicalEntry = 0x04, HasMetadataHandle = 0x08, IsGcSection = 0x10, } /// <summary> /// This structure describes one static field in an external module. It is represented /// by an indirection cell pointer and an offset within the cell - the final address /// of the static field is essentially *IndirectionCell + Offset. /// </summary> [StructLayout(LayoutKind.Sequential)] struct RemoteStaticFieldDescriptor { public unsafe IntPtr* IndirectionCell; public int Offset; } [StructLayout(LayoutKind.Sequential)] struct CctorContextEntry { public uint EETypeRva; public uint CctorContextRva; } [StructLayout(LayoutKind.Sequential)] struct PointerTypeMapEntry { public uint PointerTypeEETypeRva; public uint ElementTypeEETypeRva; } private const uint s_NotActuallyAMetadataHandle = 0x80000000; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Cci; using ModelFileToCCI2; using System; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.Tools.Transformer.CodeModel { public static class Util { public static INamedTypeDefinition ResolveTypeThrowing(INamedTypeReference typeRef) { INamedTypeDefinition result = typeRef.ResolvedType; if (result == Dummy.Type || result == Dummy.NamespaceTypeDefinition || result == Dummy.NestedType) { throw new Exception(String.Format("Cannot resolve type '{0}'. Are all dependent assemblies loaded?", typeRef.ToString())); } if (result == Dummy.GenericTypeParameter) { throw new InvalidOperationException("Why is a generic parameter being resolved?"); } Debug.Assert(!result.GetType().Name.Contains("Dummy")); return result; } public static ITypeDefinitionMember ResolveMemberThrowing(ITypeMemberReference memberRef) { ITypeDefinitionMember result = memberRef.ResolvedTypeDefinitionMember; if (result == Dummy.Method || result == Dummy.Field || result == Dummy.Event || result == Dummy.Property || result == null) { throw new Exception(String.Format("Cannot resolve member '{0}'. Are all dependent assemblies loaded?", memberRef.ToString())); } Debug.Assert(!result.GetType().Name.Contains("Dummy")); return result; } public static IMethodDefinition ResolveMethodThrowing(IMethodReference method) { IMethodDefinition result = method.ResolvedMethod; if (result == Dummy.Method || result == null) { throw new Exception(String.Format("Cannot resolve member '{0}'. Are all dependent assemblies loaded?", method.ToString())); } Debug.Assert(!result.GetType().Name.Contains("Dummy")); return result; } public static bool HasAttribute(IEnumerable<ICustomAttribute> attributes, ITypeReference attributeType) { foreach (ICustomAttribute attribute in attributes) { if (TypeHelper.TypesAreEquivalent(attribute.Type, attributeType)) { return true; } } return false; } public static IAssembly GetDefiningAssembly(ITypeReference type) { IUnit unit = TypeHelper.GetDefiningUnit(CanonicalizeType(type)); // TODO: Does this work? IModule module = unit as IModule; if (module != null) unit = module.ContainingAssembly; return unit as IAssembly; } //TODO: this doesn't work on nested types, e.g. List<Dictionary<Key, Value>> // Or types that begin with <> e.g. System.Threading.Tasks.Future<T>+<>c__DisplayClasse<T,U> public static void ParseGenName(string longName, out string shortName, out int numGenArgs) { int startIndex = 0; if (longName.StartsWith("<>")) { startIndex = 2; } //1. Removing signature for methods int sigStart = longName.IndexOf('(', startIndex); string name = sigStart > 0 ? longName.Substring(startIndex, sigStart - startIndex) : longName; //2. Parse type parameters numGenArgs = 0; int bra = name.IndexOf('<', startIndex); int ket = name.LastIndexOf('>'); //Debug.Assert(ket == longName.Length-1 || ket == -1); if (bra > 0 && ket > bra) { ++numGenArgs; int start = bra; int comma; do { comma = name.IndexOf(',', start, ket - start); if (comma > 0 && comma < ket) { ++numGenArgs; start = comma + 1; } } while (comma > 0 && comma < ket); shortName = name.Substring(0, bra); } else { shortName = name; } } public static bool IsSystemBoolean(ITypeReference type) { return (type.TypeCode == PrimitiveTypeCode.Boolean); } public static bool IsSystemObject(ITypeReference type) { return TypeHelper.TypesAreEquivalent(type, type.PlatformType.SystemObject); } public static bool IsPropertyVirtual(IPropertyDefinition prop) { if (Util.ContainingTypeDefinition(prop).IsInterface) return true; IMethodReference getter = prop.Getter; if (getter != null) return ResolveMethodThrowing(getter).IsVirtual; IMethodReference setter = prop.Setter; if (setter != null) return ResolveMethodThrowing(setter).IsVirtual; throw new Exception(String.Format("Property {0} has no accessors. Cannot determine whether it is virtual or not", prop.ToString())); } public static bool IsEventVirtual(IEventDefinition eventDef) { if (Util.ContainingTypeDefinition(eventDef).IsInterface) return true; foreach (IMethodDefinition method in eventDef.Accessors) { return ResolveMethodThrowing(method).IsVirtual; } throw new Exception(String.Format("Event {0} has no accessors. Cannot determine whether it is virtual or not", eventDef.ToString())); } public static IPropertyDefinition GetProperty(INamedTypeDefinition type, IName propName) { foreach (ITypeDefinitionMember member in type.GetMembersNamed(propName, false)) { IPropertyDefinition prop = member as IPropertyDefinition; if (prop != null) return prop; } return null; } public static IPropertyDefinition GetProperty(INamedTypeDefinition type, IPropertyDefinition property) { foreach (ITypeDefinitionMember member in type.GetMembersNamed(property.Name, false)) { IPropertyDefinition prop = member as IPropertyDefinition; if (prop != null && ParametersMatch(property.Parameters, prop.Parameters)) return prop; } return null; } public static IMethodDefinition GetMethod(INamedTypeDefinition type, IMethodReference methodRef) { foreach (ITypeDefinitionMember member in type.GetMembersNamed(methodRef.Name, false)) { IMethodDefinition methodDef = member as IMethodDefinition; if (methodDef != null && ParametersMatch(methodRef.Parameters, methodDef.Parameters)) return methodDef; } return null; } public static IFieldDefinition GetField(INamedTypeDefinition type, IName fieldName) { foreach (ITypeDefinitionMember member in type.GetMembersNamed(fieldName, false)) { IFieldDefinition fieldDef = member as IFieldDefinition; if (fieldDef != null) return fieldDef; } return null; } public static IFieldDefinition GetField(INamedTypeDefinition type, IFieldReference fieldRef) { return Util.GetField(type, fieldRef.Name); } public static IEventDefinition GetEvent(INamedTypeDefinition type, IEventDefinition evnt) { foreach (ITypeDefinitionMember member in type.GetMembersNamed(evnt.Name, false)) { IEventDefinition evntDef = member as IEventDefinition; if (evntDef != null) return evntDef; } return null; } public static uint ParameterCount(IMethodDefinition method) { uint i = 0; foreach (IParameterDefinition param in method.Parameters) ++i; return i; } public static ITypeDefinitionMember OwnerPropertyOrEvent(IMethodDefinition method) { // TODO: Don't use names for this. Use prop.Accessors and evnt.Accessors instead if (method.Name.Value.StartsWith("get_") || method.Name.Value.StartsWith("set_")) { string propName = method.Name.Value.Substring(4); foreach (IPropertyDefinition prop in Util.ContainingTypeDefinition(method).Properties) { if (prop.Name.Value.Equals(propName)) { return prop; } } } if (method.Name.Value.StartsWith("add_") || method.Name.Value.StartsWith("remove_")) { string eventName = method.Name.Value.Substring(method.Name.Value.IndexOf('_') + 1); foreach (IEventDefinition evnt in Util.ContainingTypeDefinition(method).Events) { if (evnt.Name.Value.Equals(eventName)) { return evnt; } } } return null; } // this method doesn't take into account the FrameworkInternal annotation public static bool IsTypeExternallyVisible(INamedTypeDefinition type) { INamespaceTypeDefinition nsType = type as INamespaceTypeDefinition; if (nsType != null) return nsType.IsPublic; INestedTypeDefinition nestedType = type as INestedTypeDefinition; if (nestedType != null) { return IsMemberExternallyVisible(nestedType); } throw new Exception("We shouldn't ask this question on anything else"); } // this method doesn't take into account the FrameworkInternal annotation public static bool IsMemberExternallyVisible(ITypeDefinitionMember member) { INamedTypeDefinition containingTypeDef = ContainingTypeDefinition(member); // TODO: Review switch (member.Visibility) { case TypeMemberVisibility.Public: return IsTypeExternallyVisible(containingTypeDef); case TypeMemberVisibility.Family: case TypeMemberVisibility.FamilyOrAssembly: return IsTypeExternallyVisible(containingTypeDef) && !containingTypeDef.IsSealed; default: return false; } } public static bool ParametersMatch(IEnumerable<IParameterDefinition> params1, IEnumerable<IParameterDefinition> params2) { //return TypeHelper.ParameterListsAreEquivalent(params1, params2); List<ITypeDefinition> lhs = new List<ITypeDefinition>(); List<ITypeDefinition> rhs = new List<ITypeDefinition>(); foreach (IParameterDefinition param in params1) { lhs.Add(param.Type.ResolvedType); } foreach (IParameterDefinition param in params2) { rhs.Add(param.Type.ResolvedType); } if (lhs.Count != rhs.Count) return false; for (int i = 0; i < lhs.Count; ++i) { if (!TypeHelper.TypesAreEquivalent(lhs[i], rhs[i])) return false; } return true; } public static bool ParametersMatch(IEnumerable<IParameterTypeInformation> params1, IEnumerable<IParameterDefinition> params2) { //List<ITypeDefinition> lhs = new List<ITypeDefinition>(); //List<ITypeDefinition> rhs = new List<ITypeDefinition>(); List<ITypeReference> lhs = new List<ITypeReference>(); List<ITypeReference> rhs = new List<ITypeReference>(); foreach (IParameterTypeInformation param in params1) { lhs.Add(param.Type); } foreach (IParameterDefinition param in params2) { rhs.Add(param.Type); } if (lhs.Count != rhs.Count) return false; for (int i = 0; i < lhs.Count; ++i) { if (!TypeHelper.TypesAreEquivalent(CanonicalizeType(lhs[i]), CanonicalizeType(rhs[i]))) return false; } return true; } public static MemberTypes TypeMemberType(ITypeMemberReference member) { if (member is IMethodReference) return MemberTypes.Method; else if (member is IFieldReference) return MemberTypes.Field; else if (member is IPropertyDefinition) return MemberTypes.Property; else if (member is IEventDefinition) return MemberTypes.Event; else return MemberTypes.Unknown; } public static bool IsRoot(IncludeStatus status) { return ((status == IncludeStatus.ApiRoot) || (status == IncludeStatus.ImplRoot) || (status == IncludeStatus.ApiFxInternal)); } public static bool IsApi(IncludeStatus status) { return ((status == IncludeStatus.ApiRoot) || (status == IncludeStatus.ApiClosure) || (status == IncludeStatus.ApiFxInternal)); } public static string GetTypeName(ITypeReference type) { return (new ModelSigFormatter()).GetTypeSignature(type); } public static string FullyQualifiedTypeNameFromType(ITypeReference type) { return (new ModelSigFormatter()).GetTypeSignature(type); } public static string GetMemberSignature(ITypeMemberReference member, bool MemberTypePrefix) { return (new ModelSigFormatter()).GetMemberSignature(member, MemberTypePrefix); } // This returns null for everything other than op_Explicit and op_Implicit public static string GetConversionOperatorReturnType(ITypeDefinitionMember member) { IMethodDefinition method = member as IMethodDefinition; if (method != null && (method.Name.Value.Equals("op_Explicit") || method.Name.Value.Equals("op_Implicit"))) { return Util.FullyQualifiedTypeNameFromType(method.Type); } return null; } public static bool IsDelegateType(ITypeDefinition typeDef) { foreach (ITypeReference typeRef in typeDef.BaseClasses) { // TODO: Better way of doing this that doesn't require strings even if the type is out of assembly? if (typeRef.ToString().Equals(typeDef.PlatformType.SystemMulticastDelegate.ToString())) { return true; } } return false; } public static ITypeMemberReference CanonicalizeMemberReference(ITypeMemberReference member) { if (null == member) return null; if (member == null || member == Dummy.Method) throw new Exception("Can't resolve member"); // function pointers don't have declaring types and they don't // really fit our model, so we ignore them. if (null == member.ContainingType) return null; // // first canonicalize the method... // IGenericMethodInstanceReference genMeth = member as IGenericMethodInstanceReference; if ((genMeth != null)) { member = genMeth.GenericMethod; } ISpecializedMethodReference specializedMethodRef = member as ISpecializedMethodReference; ISpecializedFieldReference specializedFieldRef = member as ISpecializedFieldReference; ISpecializedPropertyDefinition specializedPropertyDef = member as ISpecializedPropertyDefinition; ISpecializedEventDefinition specializedEventDef = member as ISpecializedEventDefinition; ISpecializedMethodDefinition specializedMethodDef = member as ISpecializedMethodDefinition; ISpecializedFieldDefinition specializedFieldDef = member as ISpecializedFieldDefinition; if (specializedMethodRef != null) member = specializedMethodRef.UnspecializedVersion; else if (specializedFieldRef != null) member = specializedFieldRef.UnspecializedVersion; else if (specializedPropertyDef != null) member = specializedPropertyDef.UnspecializedVersion; else if (specializedEventDef != null) member = specializedEventDef.UnspecializedVersion; else if (specializedMethodDef != null) member = specializedMethodDef.UnspecializedVersion; else if (specializedFieldDef != null) member = specializedFieldDef.UnspecializedVersion; if (member == null) throw new Exception("Can't canonicalize some member."); return member; } public static IMethodReference CanonicalizeMethodReference(IMethodReference method) { // function pointers don't have declaring types and they don't // really fit our model, so we ignore them. if (null == method.ContainingType) return null; // // first canonicalize the method... // IGenericMethodInstanceReference genMeth = method as IGenericMethodInstanceReference; if ((genMeth != null)) { method = genMeth.GenericMethod; } //ITypeDefinitionMember memberDef; ISpecializedMethodReference specializedMethodRef = method as ISpecializedMethodReference; if (specializedMethodRef != null) method = specializedMethodRef.UnspecializedVersion; //else //member = member as ITypeDefinitionMember; return method; } public static INamedTypeReference CanonicalizeTypeReference(ITypeReference type) { while (type != null) { IModifiedTypeReference modifiedType = type as IModifiedTypeReference; IPointerTypeReference ptrType = type as IPointerTypeReference; IManagedPointerType refType = type as IManagedPointerType; IArrayTypeReference arrType = type as IArrayTypeReference; IGenericTypeInstanceReference genType = type as IGenericTypeInstanceReference; ISpecializedNestedTypeReference nestedType = type as ISpecializedNestedTypeReference; // TODO: Why doesn't ISpecializedNestedTypeDefinition derive from ISpecializedNestedTypeReference? ISpecializedNestedTypeDefinition nestedTypeDef = type as ISpecializedNestedTypeDefinition; if (modifiedType != null) type = modifiedType.UnmodifiedType; else if (ptrType != null) type = ptrType.TargetType; else if (refType != null) type = refType.TargetType; else if (arrType != null) type = arrType.ElementType; else if (genType != null) type = genType.GenericType; else if (nestedType != null) type = nestedType.UnspecializedVersion; else if (nestedTypeDef != null) type = nestedTypeDef.UnspecializedVersion; else /* ITypeDefinition */ break; } return type as INamedTypeReference; } public static MemberTypes GetMemberTypeFromMember(IDefinition member) { if (member is IMethodDefinition) return MemberTypes.Method; else if (member is IFieldDefinition) return MemberTypes.Field; else if (member is IPropertyDefinition) return MemberTypes.Property; else if (member is IEventDefinition) return MemberTypes.Event; else if (member is ITypeDefinition) return MemberTypes.Type; else return MemberTypes.Unknown; } public static MemberTypes GetMemberTypeFromMember(ITypeMemberReference member) { if (member is IMethodReference) return MemberTypes.Method; else if (member is IFieldReference) return MemberTypes.Field; else if (member is IPropertyDefinition) return MemberTypes.Property; else if (member is IEventDefinition) return MemberTypes.Event; else if (member is ITypeReference) return MemberTypes.Type; else return MemberTypes.Unknown; } public static string GetMemberSignature(ITypeMemberReference member) { return (new ModelSigFormatter()).GetMemberSignature(member, true); } public static string MemberKeyFromMember(ITypeMemberReference member) { return MemberNameFromMember(member);//nameBuilder.ToString(); } public static string MemberNameFromMember(ITypeMemberReference member) { return GetMemberSignature(member); } public static bool HasRelatedInterfaceMembers(IMethodDefinition method) { var explicitOverrides = MemberHelper.GetExplicitlyOverriddenMethods(method); var implicitOverrides = MemberHelper.GetImplicitlyImplementedInterfaceMethods(method); if (IteratorHelper.EnumerableIsEmpty(explicitOverrides) && IteratorHelper.EnumerableIsEmpty(implicitOverrides)) { return false; } else { return true; } } public static List<ITypeDefinitionMember> FindRelatedInterfaceMembers(ITypeDefinitionMember member) { List<ITypeDefinitionMember> relatedMembers = new List<ITypeDefinitionMember>(); Dictionary<uint, ITypeReference> participatingTypes = new Dictionary<uint, ITypeReference>(); ITypeDefinition currentType = member.ContainingTypeDefinition; foreach (ITypeReference iface in currentType.Interfaces) { // check the closure against the template type, but add // the specialized type to participatingTypes so that // argument matching works if (!participatingTypes.ContainsKey(iface.InternedKey)) { participatingTypes.Add(iface.InternedKey, iface); } } foreach (ITypeReference type in participatingTypes.Values) { ITypeDefinitionMember relatedMember = FindRelatedMember(type, member); if (null != relatedMember) { relatedMembers.Add(relatedMember); } } return relatedMembers; } public static ITypeDefinitionMember FindRelatedMember(ITypeReference type, ITypeDefinitionMember member) { ITypeDefinition typeDef = type.ResolvedType; IMethodDefinition method = member as IMethodDefinition; IPropertyDefinition property = member as IPropertyDefinition; bool findProperty = (property != null); bool findMethod = (method != null); bool findEvent = (member is IEventDefinition); string prefix = ""; if (typeDef.IsInterface) { prefix = Util.FullyQualifiedTypeNameFromType(type) + "."; } foreach (ITypeDefinitionMember curMember in typeDef.Members) { IMethodDefinition curMethod = curMember as IMethodDefinition; if (findMethod && curMethod == null) continue; IPropertyDefinition curProperty = curMember as IPropertyDefinition; if (findProperty && curProperty == null) continue; if (findEvent && !(curMember is IEventDefinition)) continue; //string currentMemberName = Util.CCI2StyleMemberNameFromMember(curMember); string currentMemberName = curMember.Name.Value; // // handle explicit member overrides // string memberName = member.Name.Value; // TODO: hack here because member.Name doesn't have spaces between generic type arguments. //string memberName = Util.CCI2StyleMemberNameFromMember(member); if (findProperty || findEvent) { if (typeDef.IsInterface && memberName.StartsWith(prefix)) { string simpleName = memberName.Substring(prefix.Length); if (simpleName == currentMemberName) { return curMember; } } } if (memberName == currentMemberName) { if (findEvent || findProperty || (findMethod && Util.ParametersMatch(method.Parameters, curMethod.Parameters) && method.GenericParameterCount == curMethod.GenericParameterCount)) { return curMember; } } } return null; } public static INamedTypeDefinition ContainingTypeDefinition(ITypeDefinitionMember member) { return CanonicalizeType(CanonicalizeMemberReference(member).ContainingType); } public static bool IsInternal(TypeMemberVisibility typeMemberVisibility) { return typeMemberVisibility == TypeMemberVisibility.FamilyAndAssembly || typeMemberVisibility == TypeMemberVisibility.Assembly; } public delegate bool TypeIncluded(INamedTypeReference type); public static List<ITypeDefinitionMember> FindRelatedMembers(ITypeDefinitionMember member, TypeIncluded includeType) { List<ITypeDefinitionMember> relatedMembers = new List<ITypeDefinitionMember>(); Dictionary<uint, ITypeReference> participatingTypes = new Dictionary<uint, ITypeReference>(); ITypeDefinition currentType = member.ContainingTypeDefinition; do { // // add the type // participatingTypes.Add(currentType.InternedKey, currentType); // // add any interfaces it implements that are part of the closure // foreach (ITypeReference iface in currentType.Interfaces) { INamedTypeReference ifaceTemplate = Util.CanonicalizeTypeReference(iface); // check the closure against the template type, but add // the specialized type to participatingTypes so that // argument matching works if (includeType(ifaceTemplate) && !participatingTypes.ContainsKey(iface.InternedKey)) { // Should we add ifaceTemplate or iface? participatingTypes.Add(iface.InternedKey, iface); } } // // go up to the base type // currentType = TypeHelper.BaseClass(currentType); } while (currentType != null); foreach (ITypeReference type in participatingTypes.Values) { ITypeDefinitionMember relatedMember = FindRelatedMember(type, member); if (null != relatedMember) { relatedMembers.Add(relatedMember); } // TODO: Review foreach (IMethodImplementation methodImpl in Util.CanonicalizeType(type).ExplicitImplementationOverrides) { ITypeDefinitionMember implementingMethod = Util.CanonicalizeMember(methodImpl.ImplementingMethod); ITypeDefinitionMember implementedMethod = Util.CanonicalizeMember(methodImpl.ImplementedMethod); bool implementedTypeIncluded = includeType(Util.CanonicalizeType(implementedMethod.ContainingType)); if ((implementedMethod == member) || (implementingMethod == member && implementedTypeIncluded)) { if (!relatedMembers.Contains(implementingMethod)) { relatedMembers.Add(implementingMethod); } if (!relatedMembers.Contains(implementedMethod)) { relatedMembers.Add(implementedMethod); } } } } return relatedMembers; } public delegate bool CanIncludeCheck(INamedTypeReference type); public static List<ITypeDefinitionMember> FindRelatedExternalMembers(ITypeDefinitionMember member, CanIncludeCheck canInclude) { List<ITypeDefinitionMember> relatedMembers = new List<ITypeDefinitionMember>(); Dictionary<uint, ITypeReference> participatingTypes = new Dictionary<uint, ITypeReference>(); ITypeDefinition currentType = member.ContainingTypeDefinition; do { // // add the type // if (!canInclude(Util.CanonicalizeTypeReference(currentType))) { participatingTypes.Add(currentType.InternedKey, currentType); } // // add any interfaces it implements that are part of the closure // foreach (ITypeReference iface in currentType.Interfaces) { INamedTypeReference ifaceTemplate = Util.CanonicalizeTypeReference(iface); // check the closure against the template type, but add // the specialized type to participatingTypes so that // argument matching works if (!canInclude(ifaceTemplate) && !participatingTypes.ContainsKey(iface.InternedKey)) { // Should we add ifaceTemplate or iface? participatingTypes.Add(iface.InternedKey, iface); } } // // go up to the base type // currentType = TypeHelper.BaseClass(currentType); } while (currentType != null); foreach (ITypeReference type in participatingTypes.Values) { ITypeDefinitionMember relatedMember = FindRelatedMember(type, member); if (null != relatedMember) { relatedMembers.Add(relatedMember); } } return relatedMembers; } public static bool HasAttributeNamed(IEnumerable<ICustomAttribute> attributes, string attributeTypeName) { foreach (ICustomAttribute attribute in attributes) { if (GetTypeName(attribute.Type).Equals(attributeTypeName)) { return true; } } return false; } public static INamedTypeDefinition CanonicalizeType(ITypeReference type) { if (type == null) return null; return ResolveTypeThrowing(CanonicalizeTypeReference(type)); } public static ITypeDefinitionMember CanonicalizeMember(ITypeMemberReference member) { return ResolveMemberThrowing(CanonicalizeMemberReference(member)); } public static String GetTypeForwarderSignature(string assemblyName, string typeName) { return assemblyName + " " + typeName; } public static String GetTypeForwarderSignature(IAliasForType alias) { ITypeReference type = alias.AliasedType; return GetTypeForwarderSignature(Util.GetDefiningAssembly(type).Name.Value, Util.GetTypeName(type)); } // Walk up the path of defining namespaces and units until we get to the assembly public static IAssembly GetDefiningAssembly(IAliasForType aliasForType) { INamespaceAliasForType namespaceAliasForType = GetAliasForType(aliasForType); if (namespaceAliasForType == null) return null; INamespaceDefinition containingNamespace = namespaceAliasForType.ContainingNamespace; IUnitNamespace unitNamespace = GetUnitNamespace(containingNamespace); if (unitNamespace == null) return null; IUnit unit = unitNamespace.Unit; IAssembly assembly = GetAssembly(unit); return assembly; } private static IAssembly GetAssembly(IUnit unit) { IAssembly assembly = unit as IAssembly; if (assembly == null) { IModule module = unit as IModule; if (module != null) assembly = module.ContainingAssembly; } return assembly; } private static IUnitNamespace GetUnitNamespace(INamespaceDefinition containingNamespace) { INestedUnitNamespace nestedUnitNamespace = containingNamespace as INestedUnitNamespace; if (nestedUnitNamespace != null) { containingNamespace = nestedUnitNamespace.ContainingUnitNamespace; } IUnitNamespace unitNamespace = containingNamespace as IUnitNamespace; return unitNamespace; } private static INamespaceAliasForType GetAliasForType(IAliasForType aliasForType) { INestedAliasForType nestedAliasForType = aliasForType as INestedAliasForType; while (nestedAliasForType != null) { aliasForType = nestedAliasForType.ContainingAlias; nestedAliasForType = aliasForType as INestedAliasForType; } INamespaceAliasForType namespaceAliasForType = aliasForType as INamespaceAliasForType; return namespaceAliasForType; } } }
using System; using System.Diagnostics; using System.Collections.Generic; using Deuterium.AST; using FusionCore; namespace Deuterium { public class BackpatchNode { public int bp; public int pc; } public class BackpatchTable { public List<BackpatchNode> backpatchList { get; private set; } public BackpatchTable() { backpatchList = new List<BackpatchNode>(); } public void append(int bp, int pc) { BackpatchNode node = new BackpatchNode(); node.bp = bp; node.pc = pc; backpatchList.Add(node); } public void append(int bp) { BackpatchNode node = new BackpatchNode(); node.bp = bp; node.pc = (int)FusionCore.DSASM.Constants.kInvalidIndex; backpatchList.Add(node); } } public class CodeGen { private int locals = 0; private int argOffset = 0; private int functionindex = (int)FusionCore.DSASM.Constants.kGlobalScope; private bool isEntrySet = false; private List<Node> astNodes; public FusionCore.DSASM.SymbolTable symbols { get; set; } public FusionCore.DSASM.FunctionTable functions { get; set; } public FusionCore.DSASM.Executable executable { get; set; } private int pc = 0; private int globOffset = 0; private int baseOffset = 0; private bool dumpByteCode = false; public BackpatchTable backpatchTable{ get; set; } public CodeGen() { locals = 0; globOffset = 0; baseOffset = 0; argOffset = 0; symbols = symbols = new FusionCore.DSASM.SymbolTable(); astNodes = new List<Node>(); functions = new FusionCore.DSASM.FunctionTable(); executable = new FusionCore.DSASM.Executable(); backpatchTable = new BackpatchTable(); } private void setEntry() { if (functionindex == (int)FusionCore.DSASM.Constants.kGlobalScope && !isEntrySet) { isEntrySet = true; executable.entrypoint = pc; } } private void Allocate(string ident, int funcIndex, FusionCore.PrimitiveType datatype, int datasize = (int)FusionCore.DSASM.Constants.kPrimitiveSize) { FusionCore.DSASM.SymbolNode node = new FusionCore.DSASM.SymbolNode(); node.name = ident; node.size = datasize; node.functionIndex = funcIndex; node.datatype = datatype; node.isArgument = false; // TODO Jun: Shouldnt the offset increment be done upon successfully appending the symbol? if ((int)FusionCore.DSASM.Constants.kGlobalScope == funcIndex) { node.index = globOffset; globOffset += node.size; } else { node.index = -2 - baseOffset; baseOffset += node.size; } symbols.Update(node); } private void AllocateArg(string ident, int funcIndex, FusionCore.PrimitiveType datatype, int datasize = (int)FusionCore.DSASM.Constants.kPrimitiveSize) { FusionCore.DSASM.SymbolNode node = new FusionCore.DSASM.SymbolNode(); node.name = ident; node.size = datasize; node.functionIndex = funcIndex; node.datatype = datatype; node.isArgument = true; int locOffset = functions.functionList[funcIndex].localCount; // This is standard argOffset++; node.index = -2 - (locOffset + argOffset); // This is through FEP //node.index = argOffset++; symbols.Update(node); } FusionCore.DSASM.AddressType getOpType(FusionCore.PrimitiveType type) { FusionCore.DSASM.AddressType optype = FusionCore.DSASM.AddressType.Int; // Data coercion for the prototype // The JIL executive handles int primitives if (FusionCore.PrimitiveType.kTypeInt == type || FusionCore.PrimitiveType.kTypeDouble == type || FusionCore.PrimitiveType.kTypeBool == type || FusionCore.PrimitiveType.kTypeChar == type || FusionCore.PrimitiveType.kTypeString == type) { optype = FusionCore.DSASM.AddressType.Int; } else if (FusionCore.PrimitiveType.kTypeVar == type) { optype = FusionCore.DSASM.AddressType.VarIndex; } else if (FusionCore.PrimitiveType.kTypeReturn == type) { optype = FusionCore.DSASM.AddressType.Register; } else { Debug.Assert(false); } return optype; } FusionCore.DSASM.OpCode getOpCode(Operator optr) { FusionCore.DSASM.OpCode opcode = FusionCore.DSASM.OpCode.ADD; // TODO jun: perhaps a table? if (Operator.add == optr) { opcode = FusionCore.DSASM.OpCode.ADD; } else if (Operator.sub == optr) { opcode = FusionCore.DSASM.OpCode.SUB; } else if (Operator.mul == optr) { opcode = FusionCore.DSASM.OpCode.MULT; } else if (Operator.div == optr) { opcode = FusionCore.DSASM.OpCode.DIV; } else if (Operator.eq == optr) { opcode = FusionCore.DSASM.OpCode.EQ; } else if (Operator.nq == optr) { opcode = FusionCore.DSASM.OpCode.NQ; } else if (Operator.ge == optr) { opcode = FusionCore.DSASM.OpCode.GE; } else if (Operator.gt == optr) { opcode = FusionCore.DSASM.OpCode.GT; } else if (Operator.le == optr) { opcode = FusionCore.DSASM.OpCode.LE; } else if (Operator.lt == optr) { opcode = FusionCore.DSASM.OpCode.LT; } else { Debug.Assert(false); } return opcode; } FusionCore.DSASM.Operand buildOperand(TerminalNode node) { FusionCore.DSASM.Operand op = new FusionCore.DSASM.Operand(); op.optype = getOpType((FusionCore.PrimitiveType)node.type); if (FusionCore.DSASM.AddressType.VarIndex == op.optype) { //FusionCore.DSASM.SymbolNode int size = symbols.symbolList.Count; for (int n = 0; n < size; ++n) { // TODO jun: Hash the string if (functionindex == symbols.symbolList[n].functionIndex && symbols.symbolList[n].name == node.Value) { op.opdata = n; // symbols.symbolList[n].index; break; } } } else if (FusionCore.DSASM.AddressType.Int == op.optype) { op.opdata = System.Convert.ToInt32(node.Value); } else if (FusionCore.DSASM.AddressType.Register == op.optype) { op.opdata = (int)FusionCore.DSASM.Registers.RX; } else { Debug.Assert(false); } return op; } public void emit(string s) { if (dumpByteCode) { System.Console.Write("[" + pc + "]" + s); } } private void emitPush(FusionCore.DSASM.Operand op) { setEntry(); FusionCore.DSASM.Instruction instr = new FusionCore.DSASM.Instruction(); instr.opCode = FusionCore.DSASM.OpCode.PUSH; instr.op1 = op; pc++; executable.instructionList.Add(instr); } private void emitPop(FusionCore.DSASM.Operand op) { FusionCore.DSASM.Instruction instr = new FusionCore.DSASM.Instruction(); instr.opCode = FusionCore.DSASM.OpCode.POP; instr.op1 = op; // For debugging, assert here but these should raise runtime errors in the VM Debug.Assert(FusionCore.DSASM.AddressType.VarIndex == op.optype || FusionCore.DSASM.AddressType.Register == op.optype); pc++; executable.instructionList.Add(instr); } private void emitReturn() { FusionCore.DSASM.Instruction instr = new FusionCore.DSASM.Instruction(); instr.opCode = FusionCore.DSASM.OpCode.RETURN; pc++; executable.instructionList.Add(instr); } private void emitBinary(FusionCore.DSASM.OpCode opcode, FusionCore.DSASM.Operand op1, FusionCore.DSASM.Operand op2) { setEntry(); FusionCore.DSASM.Instruction instr = new FusionCore.DSASM.Instruction(); instr.opCode = opcode; instr.op1 = op1; instr.op2 = op2; // For debugging, assert here but these should raise runtime errors in the VM Debug.Assert(FusionCore.DSASM.AddressType.VarIndex == op1.optype || FusionCore.DSASM.AddressType.Register == op1.optype); pc++; executable.instructionList.Add(instr); } private void emitCall(int funcIndex) { setEntry(); FusionCore.DSASM.Instruction instr = new FusionCore.DSASM.Instruction(); instr.opCode = FusionCore.DSASM.OpCode.CALL; FusionCore.DSASM.Operand op = new FusionCore.DSASM.Operand(); op.optype = FusionCore.DSASM.AddressType.FunctionIndex; op.opdata = funcIndex; instr.op1 = op; pc++; executable.instructionList.Add(instr); } private void emitJmp(int L1) { emit(FusionCore.DSASM.kw.jmp + " L1(" + L1 + ")" + FusionCore.DSASM.Constants.termline); FusionCore.DSASM.Instruction instr = new FusionCore.DSASM.Instruction(); instr.opCode = FusionCore.DSASM.OpCode.JMP; FusionCore.DSASM.Operand op1 = new FusionCore.DSASM.Operand(); op1.optype = FusionCore.DSASM.AddressType.LabelIndex; op1.opdata = L1; instr.op1 = op1; pc++; executable.instructionList.Add(instr); } private void emitCJmp(int L1, int L2) { emit(FusionCore.DSASM.kw.cjmp + " " + FusionCore.DSASM.kw.regCX + " L1(" + L1 + ") L2(" + L2 + ")" + FusionCore.DSASM.Constants.termline); FusionCore.DSASM.Instruction instr = new FusionCore.DSASM.Instruction(); instr.opCode = FusionCore.DSASM.OpCode.CJMP; FusionCore.DSASM.Operand op1 = new FusionCore.DSASM.Operand(); op1.optype = FusionCore.DSASM.AddressType.Register; op1.opdata = (int)FusionCore.DSASM.Registers.CX; instr.op1 = op1; FusionCore.DSASM.Operand op2 = new FusionCore.DSASM.Operand(); op2.optype = FusionCore.DSASM.AddressType.LabelIndex; op2.opdata = L1; instr.op2 = op2; FusionCore.DSASM.Operand op3 = new FusionCore.DSASM.Operand(); op3.optype = FusionCore.DSASM.AddressType.LabelIndex; op3.opdata = L2; instr.op3 = op3; pc++; executable.instructionList.Add(instr); } private void backpatch(int bp, int pc) { if(FusionCore.DSASM.OpCode.JMP == executable.instructionList[bp].opCode && FusionCore.DSASM.AddressType.LabelIndex == executable.instructionList[bp].op1.optype) { executable.instructionList[bp].op1.opdata = pc; } else if (FusionCore.DSASM.OpCode.CJMP == executable.instructionList[bp].opCode && FusionCore.DSASM.AddressType.LabelIndex == executable.instructionList[bp].op3.optype) { executable.instructionList[bp].op3.opdata = pc; } } private void backpatch(List<BackpatchNode> table, int pc) { foreach( BackpatchNode node in table ) { backpatch(node.bp, pc); } } private string getOperator(Operator op) { // TODO jun: perhaps a table? string sOp = ""; if (Operator.add == op) { sOp = "add"; } else if (Operator.sub == op) { sOp = "sub"; } else if (Operator.mul == op) { sOp = "mul"; } else if (Operator.div == op) { sOp = "div"; } else if (Operator.eq == op) { sOp = "eq"; } else if (Operator.nq == op) { sOp = "nq"; } else if (Operator.ge == op) { sOp = "ge"; } else if (Operator.gt == op) { sOp = "gt"; } else if (Operator.le == op) { sOp = "le"; } else if (Operator.lt == op) { sOp = "lt"; } return sOp; } private bool isAssignmentNode( Node node ) { if( node is BinaryExpressionNode ) { BinaryExpressionNode b = node as BinaryExpressionNode; if( Operator.assign == b.Operator ) { return false; } } return false; } private void emitAssignLHS(Node node) { } public void emit(CodeBlockNode codeblock) { astNodes = codeblock.Body; foreach(Node node in astNodes) { dfsTraverse(node); } executable.functionTable = functions; executable.globsize = symbols.globs; executable.debugsymbols = symbols; } private void dfsTraverse(Node node) { if (node is TerminalNode) { TerminalNode t = node as TerminalNode; emit("push " + t.Value + ";\n"); FusionCore.DSASM.Operand op = buildOperand(t); emitPush(op); } else if (node is FunctionDefinitionNode) { FunctionDefinitionNode funcDef = node as FunctionDefinitionNode; // TODO jun: Add semantics for checking overloads (different parameter types) FusionCore.DSASM.FunctionNode fnode = new FusionCore.DSASM.FunctionNode(); fnode.name = funcDef.Name; fnode.paramCount = null == funcDef.Signature ? 0 : funcDef.Signature.Arguments.Count; fnode.pc = pc; fnode.localCount = funcDef.localVars; fnode.returntype = FusionCore.TypeSystem.getType(funcDef.ReturnType.Name); functionindex = functions.Append(fnode); // Append arg symbols if (fnode.paramCount > 0) { foreach (VarDeclNode argNode in funcDef.Signature.Arguments) { AllocateArg(argNode.NameNode.Value, functionindex, FusionCore.TypeSystem.getType(argNode.ArgumentType.Name)); } } // Traverse definition foreach (Node bnode in funcDef.FunctionBody.Body) { dfsTraverse(bnode); } // Append to the function group functiontable FusionCore.FunctionGroup funcGroup = new FusionCore.FunctionGroup(); // ArgList if (fnode.paramCount > 0) { List<FusionCore.Type> parameterTypes = new List<FusionCore.Type>(); foreach (VarDeclNode argNode in funcDef.Signature.Arguments) { parameterTypes.Add(FusionCore.TypeSystem.buildTypeObject(FusionCore.TypeSystem.getType(argNode.ArgumentType.Name), false)); } } // function return emit("ret" + FusionCore.DSASM.Constants.termline); emitReturn(); functionindex = (int)FusionCore.DSASM.Constants.kGlobalScope; argOffset = 0; baseOffset = 0; } else if (node is FunctionCallNode) { FunctionCallNode funcCall = node as FunctionCallNode; FusionCore.DSASM.FunctionNode fnode = new FusionCore.DSASM.FunctionNode(); fnode.name = funcCall.Function.Name; fnode.paramCount = funcCall.FormalArguments.Count; // Traverse the function args foreach (Node paramNode in funcCall.FormalArguments) { dfsTraverse(paramNode); } int fIndex = functions.getIndex(fnode); if ((int)FusionCore.DSASM.Constants.kInvalidIndex != fIndex) { emit("call " + fnode.name + FusionCore.DSASM.Constants.termline); emitCall(fIndex); if (FusionCore.PrimitiveType.kTypeVoid != functions.functionList[fIndex].returntype) { emit("push " + FusionCore.DSASM.kw.regRX + FusionCore.DSASM.Constants.termline); FusionCore.DSASM.Operand opRes; opRes.optype = FusionCore.DSASM.AddressType.Register; opRes.opdata = (int)FusionCore.DSASM.Registers.RX; emitPush(opRes); } } else { System.Console.WriteLine("Method '" + fnode.name + "' not found\n"); } } else if (node is IfStmtNode) { /* def backpatch(bp, pc) instr = instrstream[bp] if instr.opcode is jmp instr.op1 = pc elseif instr.opcode is cjmp instr.op2 = pc end end def backpatch(table, pc) foreach node in table backpatch(node.pc, pc) end end */ /* if(E) -> traverse E bpTable = new instance L1 = pc + 1 L2 = null bp = pc emit(jmp, _cx, L1, L2) { S -> traverse S L1 = null bpTable.append(pc) emit(jmp,labelEnd) backpatch(bp,pc) } * */ // TODO jun: Try to break up this emitter without while retaining theoretical meaning int bp = (int)FusionCore.DSASM.Constants.kInvalidIndex; int L1 = (int)FusionCore.DSASM.Constants.kInvalidIndex; int L2 = (int)FusionCore.DSASM.Constants.kInvalidIndex; FusionCore.DSASM.Operand opCX; // If-expr IfStmtNode ifnode = node as IfStmtNode; dfsTraverse(ifnode.IfExprNode); emit("pop " + FusionCore.DSASM.kw.regCX + FusionCore.DSASM.Constants.termline); opCX.optype = FusionCore.DSASM.AddressType.Register; opCX.opdata = (int)FusionCore.DSASM.Registers.CX; emitPop(opCX); L1 = pc + 1; L2 = (int)FusionCore.DSASM.Constants.kInvalidIndex; bp = pc; emitCJmp(L1, L2); // If-body foreach (Node ifBody in ifnode.IfBody) { dfsTraverse(ifBody); } L1 = (int)FusionCore.DSASM.Constants.kInvalidIndex; backpatchTable.append(pc, L1); emitJmp(L1); backpatch(bp, pc); /* else if(E) -> traverse E L1 = pc + 1 L2 = null bp = pc emit(jmp, _cx, L1, L2) { S -> traverse S L1 = null bpTable.append(pc) emit(jmp,labelEnd) backpatch(bp,pc) } * */ // Elseif-expr foreach (ElseIfBlock elseifNode in ifnode.ElseIfList) { dfsTraverse(elseifNode.Expr); emit("pop " + FusionCore.DSASM.kw.regCX + FusionCore.DSASM.Constants.termline); opCX.optype = FusionCore.DSASM.AddressType.Register; opCX.opdata = (int)FusionCore.DSASM.Registers.CX; emitPop(opCX); L1 = pc + 1; L2 = (int)FusionCore.DSASM.Constants.kInvalidIndex; bp = pc; emitCJmp(L1, L2); // Elseif-body if (null != elseifNode.Body) { foreach (Node elseifBody in elseifNode.Body) { dfsTraverse(elseifBody); } } L1 = (int)FusionCore.DSASM.Constants.kInvalidIndex; backpatchTable.append(pc, L1); emitJmp(L1); backpatch(bp, pc); } /* else { S -> traverse S L1 = null bpTable.append(pc) emit(jmp,labelEnd) backpatch(bp,pc) } * */ // Else-body if (null != ifnode.ElseBody) { foreach (Node elseBody in ifnode.ElseBody) { dfsTraverse(elseBody); } L1 = (int)FusionCore.DSASM.Constants.kInvalidIndex; backpatchTable.append(pc, L1); emitJmp(L1); //backpatch(bp, pc); } /* * -> backpatch(bpTable, pc) */ // ifstmt-exit backpatch(backpatchTable.backpatchList, pc); } else if (node is VarDeclNode) { VarDeclNode varNode = node as VarDeclNode; Allocate(varNode.NameNode.Value, functionindex, FusionCore.TypeSystem.getType(varNode.ArgumentType.Name)); } else if (node is BinaryExpressionNode) { BinaryExpressionNode b = node as BinaryExpressionNode; if (Operator.assign != b.Operator) { dfsTraverse(b.LeftNode); } dfsTraverse(b.RightNode); if (Operator.assign == b.Operator) { if (b.LeftNode is TerminalNode) { TerminalNode t = b.LeftNode as TerminalNode; bool isReturn = false; string s = t.Value; if (s == "return") { s = "_rx"; //isReturn = true; } // TODO jun: the emit string are only for console logging, // wrap them together with the actual emit function and flag them out as needed emit("pop " + s + FusionCore.DSASM.Constants.termline); FusionCore.DSASM.Operand op = buildOperand(t); emitPop(op); //if (isReturn) //{ // emit("ret" + FusionCore.DSASM.Constants.termline); // emitReturn(); // functionindex = (int)FusionCore.DSASM.Constants.kGlobalScope; //} } } else { emit("pop " + FusionCore.DSASM.kw.regBX + FusionCore.DSASM.Constants.termline); FusionCore.DSASM.Operand opBX; opBX.optype = FusionCore.DSASM.AddressType.Register; opBX.opdata = (int)FusionCore.DSASM.Registers.BX; emitPop(opBX); emit("pop " + FusionCore.DSASM.kw.regAX + FusionCore.DSASM.Constants.termline); FusionCore.DSASM.Operand opAX; opAX.optype = FusionCore.DSASM.AddressType.Register; opAX.opdata = (int)FusionCore.DSASM.Registers.AX; emitPop(opAX); string op = getOperator(b.Operator); emit(op + " " + FusionCore.DSASM.kw.regAX + ", " + FusionCore.DSASM.kw.regBX + FusionCore.DSASM.Constants.termline); emitBinary(getOpCode(b.Operator), opAX, opBX); emit("push " + FusionCore.DSASM.kw.regAX + FusionCore.DSASM.Constants.termline); FusionCore.DSASM.Operand opRes; opRes.optype = FusionCore.DSASM.AddressType.Register; opRes.opdata = (int)FusionCore.DSASM.Registers.AX; emitPush(opRes); } } } } }
namespace android.view.inputmethod { [global::MonoJavaBridge.JavaClass()] public partial class BaseInputConnection : java.lang.Object, InputConnection { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static BaseInputConnection() { InitJNI(); } protected BaseInputConnection(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _setSelection10078; public virtual bool setSelection(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._setSelection10078, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._setSelection10078, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _beginBatchEdit10079; public virtual bool beginBatchEdit() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._beginBatchEdit10079); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._beginBatchEdit10079); } internal static global::MonoJavaBridge.MethodId _endBatchEdit10080; public virtual bool endBatchEdit() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._endBatchEdit10080); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._endBatchEdit10080); } internal static global::MonoJavaBridge.MethodId _getTextBeforeCursor10081; public virtual global::java.lang.CharSequence getTextBeforeCursor(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._getTextBeforeCursor10081, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._getTextBeforeCursor10081, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _getTextAfterCursor10082; public virtual global::java.lang.CharSequence getTextAfterCursor(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._getTextAfterCursor10082, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._getTextAfterCursor10082, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _getCursorCapsMode10083; public virtual int getCursorCapsMode(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._getCursorCapsMode10083, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._getCursorCapsMode10083, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getExtractedText10084; public virtual global::android.view.inputmethod.ExtractedText getExtractedText(android.view.inputmethod.ExtractedTextRequest arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._getExtractedText10084, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.view.inputmethod.ExtractedText; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._getExtractedText10084, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.view.inputmethod.ExtractedText; } internal static global::MonoJavaBridge.MethodId _deleteSurroundingText10085; public virtual bool deleteSurroundingText(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._deleteSurroundingText10085, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._deleteSurroundingText10085, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setComposingText10086; public virtual bool setComposingText(java.lang.CharSequence arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._setComposingText10086, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._setComposingText10086, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public bool setComposingText(string arg0, int arg1) { return setComposingText((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1); } internal static global::MonoJavaBridge.MethodId _finishComposingText10087; public virtual bool finishComposingText() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._finishComposingText10087); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._finishComposingText10087); } internal static global::MonoJavaBridge.MethodId _commitText10088; public virtual bool commitText(java.lang.CharSequence arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._commitText10088, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._commitText10088, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public bool commitText(string arg0, int arg1) { return commitText((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1); } internal static global::MonoJavaBridge.MethodId _commitCompletion10089; public virtual bool commitCompletion(android.view.inputmethod.CompletionInfo arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._commitCompletion10089, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._commitCompletion10089, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _performEditorAction10090; public virtual bool performEditorAction(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._performEditorAction10090, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._performEditorAction10090, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _performContextMenuAction10091; public virtual bool performContextMenuAction(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._performContextMenuAction10091, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._performContextMenuAction10091, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _sendKeyEvent10092; public virtual bool sendKeyEvent(android.view.KeyEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._sendKeyEvent10092, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._sendKeyEvent10092, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _clearMetaKeyStates10093; public virtual bool clearMetaKeyStates(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._clearMetaKeyStates10093, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._clearMetaKeyStates10093, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _reportFullscreenMode10094; public virtual bool reportFullscreenMode(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._reportFullscreenMode10094, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._reportFullscreenMode10094, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _performPrivateCommand10095; public virtual bool performPrivateCommand(java.lang.String arg0, android.os.Bundle arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._performPrivateCommand10095, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._performPrivateCommand10095, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _removeComposingSpans10096; public static void removeComposingSpans(android.text.Spannable arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; @__env.CallStaticVoidMethod(android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._removeComposingSpans10096, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setComposingSpans10097; public static void setComposingSpans(android.text.Spannable arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; @__env.CallStaticVoidMethod(android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._setComposingSpans10097, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getComposingSpanStart10098; public static int getComposingSpanStart(android.text.Spannable arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._getComposingSpanStart10098, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getComposingSpanEnd10099; public static int getComposingSpanEnd(android.text.Spannable arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._getComposingSpanEnd10099, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getEditable10100; public virtual global::android.text.Editable getEditable() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection._getEditable10100)) as android.text.Editable; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._getEditable10100)) as android.text.Editable; } internal static global::MonoJavaBridge.MethodId _BaseInputConnection10101; public BaseInputConnection(android.view.View arg0, bool arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.inputmethod.BaseInputConnection.staticClass, global::android.view.inputmethod.BaseInputConnection._BaseInputConnection10101, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.inputmethod.BaseInputConnection.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/inputmethod/BaseInputConnection")); global::android.view.inputmethod.BaseInputConnection._setSelection10078 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "setSelection", "(II)Z"); global::android.view.inputmethod.BaseInputConnection._beginBatchEdit10079 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "beginBatchEdit", "()Z"); global::android.view.inputmethod.BaseInputConnection._endBatchEdit10080 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "endBatchEdit", "()Z"); global::android.view.inputmethod.BaseInputConnection._getTextBeforeCursor10081 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "getTextBeforeCursor", "(II)Ljava/lang/CharSequence;"); global::android.view.inputmethod.BaseInputConnection._getTextAfterCursor10082 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "getTextAfterCursor", "(II)Ljava/lang/CharSequence;"); global::android.view.inputmethod.BaseInputConnection._getCursorCapsMode10083 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "getCursorCapsMode", "(I)I"); global::android.view.inputmethod.BaseInputConnection._getExtractedText10084 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "getExtractedText", "(Landroid/view/inputmethod/ExtractedTextRequest;I)Landroid/view/inputmethod/ExtractedText;"); global::android.view.inputmethod.BaseInputConnection._deleteSurroundingText10085 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "deleteSurroundingText", "(II)Z"); global::android.view.inputmethod.BaseInputConnection._setComposingText10086 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "setComposingText", "(Ljava/lang/CharSequence;I)Z"); global::android.view.inputmethod.BaseInputConnection._finishComposingText10087 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "finishComposingText", "()Z"); global::android.view.inputmethod.BaseInputConnection._commitText10088 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "commitText", "(Ljava/lang/CharSequence;I)Z"); global::android.view.inputmethod.BaseInputConnection._commitCompletion10089 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "commitCompletion", "(Landroid/view/inputmethod/CompletionInfo;)Z"); global::android.view.inputmethod.BaseInputConnection._performEditorAction10090 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "performEditorAction", "(I)Z"); global::android.view.inputmethod.BaseInputConnection._performContextMenuAction10091 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "performContextMenuAction", "(I)Z"); global::android.view.inputmethod.BaseInputConnection._sendKeyEvent10092 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "sendKeyEvent", "(Landroid/view/KeyEvent;)Z"); global::android.view.inputmethod.BaseInputConnection._clearMetaKeyStates10093 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "clearMetaKeyStates", "(I)Z"); global::android.view.inputmethod.BaseInputConnection._reportFullscreenMode10094 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "reportFullscreenMode", "(Z)Z"); global::android.view.inputmethod.BaseInputConnection._performPrivateCommand10095 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "performPrivateCommand", "(Ljava/lang/String;Landroid/os/Bundle;)Z"); global::android.view.inputmethod.BaseInputConnection._removeComposingSpans10096 = @__env.GetStaticMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "removeComposingSpans", "(Landroid/text/Spannable;)V"); global::android.view.inputmethod.BaseInputConnection._setComposingSpans10097 = @__env.GetStaticMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "setComposingSpans", "(Landroid/text/Spannable;)V"); global::android.view.inputmethod.BaseInputConnection._getComposingSpanStart10098 = @__env.GetStaticMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "getComposingSpanStart", "(Landroid/text/Spannable;)I"); global::android.view.inputmethod.BaseInputConnection._getComposingSpanEnd10099 = @__env.GetStaticMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "getComposingSpanEnd", "(Landroid/text/Spannable;)I"); global::android.view.inputmethod.BaseInputConnection._getEditable10100 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "getEditable", "()Landroid/text/Editable;"); global::android.view.inputmethod.BaseInputConnection._BaseInputConnection10101 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.BaseInputConnection.staticClass, "<init>", "(Landroid/view/View;Z)V"); } } }
using System; using System.Collections.Generic; using System.Text; using FileHelpers.Dynamic; using System.IO; namespace FileHelpers.Detection { /// <summary> /// Utility class used to auto detect the record format, /// the number of fields, the type, etc. /// </summary> public sealed class SmartFormatDetector { /// <summary> /// Initializes a new instance of the <see cref="SmartFormatDetector"/> class. /// </summary> public SmartFormatDetector() { QuotedChar = '"'; } #region " Constants " private const int MinSampleData = 10; private const double MinDelimitedDeviation = 0.30001; #endregion #region " Properties " private FormatHint mFormatHint; /// <summary> /// Provides a suggestion to the <see cref="SmartFormatDetector"/> /// about the records in the file /// </summary> public FormatHint FormatHint { get { return mFormatHint; } set { mFormatHint = value; } } private int mMaxSampleLines = 300; /// <summary> /// The number of lines of each file to be used as sample data. /// </summary> public int MaxSampleLines { get { return mMaxSampleLines; } set { mMaxSampleLines = value; } } private Encoding mEncoding = Encoding.GetEncoding(0); /// <summary>The encoding to Read and Write the streams.</summary> /// <remarks>Default is the system's current ANSI code page.</remarks> public Encoding Encoding { get { return mEncoding; } set { mEncoding = value; } } private double mFixedLengthDeviationTolerance = 0.01; ///<summary> ///Indicates if the sample file has headers ///</summary> public bool? FileHasHeaders { get; set; } /// <summary> /// Used to calculate when a file has fixed length records. /// Between 0.0 - 1.0 (Default 0.01) /// </summary> public double FixedLengthDeviationTolerance { get { return mFixedLengthDeviationTolerance; } set { mFixedLengthDeviationTolerance = value; } } #endregion #region " Public Methods " /// <summary> /// Tries to detect the possible formats of the file using the <see cref="FormatHint"/> /// </summary> /// <param name="file">The file to be used as sample data</param> /// <returns>The possible <see cref="RecordFormatInfo"/> of the file.</returns> public RecordFormatInfo[] DetectFileFormat(string file) { return DetectFileFormat(new string[] {file}); } /// <summary> /// Tries to detect the possible formats of the file using the <see cref="FormatHint"/> /// </summary> /// <param name="files">The files to be used as sample data</param> /// <returns>The possible <see cref="RecordFormatInfo"/> of the file.</returns> public RecordFormatInfo[] DetectFileFormat(IEnumerable<string> files) { var readers = new List<TextReader>(); foreach (var file in files) { readers.Add(new StreamReader(file, Encoding)); } var res = DetectFileFormat(readers); foreach (var reader in readers) { reader.Close(); } return res; } /// <summary> /// Tries to detect the possible formats of the file using the <see cref="FormatHint"/> /// </summary> /// <param name="files">The files to be used as sample data</param> /// <returns>The possible <see cref="RecordFormatInfo"/> of the file.</returns> public RecordFormatInfo[] DetectFileFormat(IEnumerable<TextReader> files) { var res = new List<RecordFormatInfo>(); string[][] sampleData = GetSampleLines(files, MaxSampleLines); switch (mFormatHint) { case FormatHint.Unknown: CreateMixedOptions(sampleData, res); break; case FormatHint.FixedLength: CreateFixedLengthOptions(sampleData, res); break; case FormatHint.Delimited: CreateDelimiterOptions(sampleData, res); break; case FormatHint.DelimitedByTab: CreateDelimiterOptions(sampleData, res, '\t'); break; case FormatHint.DelimitedByComma: CreateDelimiterOptions(sampleData, res, ','); break; case FormatHint.DelimitedBySemicolon: CreateDelimiterOptions(sampleData, res, ';'); break; default: throw new InvalidOperationException("Unsuported FormatHint value."); } foreach (var option in res) { DetectOptionals(option, sampleData); DetectTypes(option, sampleData); DetectQuoted(option, sampleData); } // Sort by confidence res.Sort( delegate(RecordFormatInfo x, RecordFormatInfo y) { return -1*x.Confidence.CompareTo(y.Confidence); }); return res.ToArray(); } #endregion #region " Fields Properties Methods " private void DetectQuoted(RecordFormatInfo format, string[][] data) { if (format.ClassBuilder is FixedLengthClassBuilder) return; // TODO: Add FieldQuoted } private void DetectTypes(RecordFormatInfo format, string[][] data) { // TODO: Try to detect posible formats (mostly numbers or dates) } private void DetectOptionals(RecordFormatInfo option, string[][] data) { // TODO: Try to detect optional fields } #endregion #region " Create Options Methods " // UNKNOWN private void CreateMixedOptions(string[][] data, List<RecordFormatInfo> res) { var stats = Indicators.CalculateAsFixedSize (data); if (stats.Deviation / stats.Avg <= FixedLengthDeviationTolerance * Math.Min (1, NumberOfLines (data) / MinSampleData)) CreateFixedLengthOptions(data, res); CreateDelimiterOptions(data, res); //if (deviation > average * 0.01 && // deviation < average * 0.05) // CreateFixedLengthOptions(data, res); } // FIXED LENGTH private void CreateFixedLengthOptions(string[][] data, List<RecordFormatInfo> res) { var format = new RecordFormatInfo(); var stats = Indicators.CalculateAsFixedSize (data); format.mConfidence = (int)(Math.Max (0, 1 - stats.Deviation / stats.Avg) * 100); var builder = new FixedLengthClassBuilder("AutoDetectedClass"); CreateFixedLengthFields(data, builder); format.mClassBuilder = builder; res.Add(format); } /// <summary> /// start and length of fixed length column /// </summary> private class FixedColumnInfo { /// <summary> /// start position of column /// </summary> public int Start; /// <summary> /// Length of column /// </summary> public int Length; } private void CreateFixedLengthFields(string[][] data, FixedLengthClassBuilder builder) { List<FixedColumnInfo> res = null; foreach (var dataFile in data) { List<FixedColumnInfo> candidates = CreateFixedLengthCandidates(dataFile); res = JoinFixedColCandidates(res, candidates); } for (int i = 0; i < res.Count; i++) { FixedColumnInfo col = res[i]; builder.AddField("Field" + i.ToString().PadLeft(4, '0'), col.Length, typeof (string)); } } private List<FixedColumnInfo> CreateFixedLengthCandidates(string[] lines) { List<FixedColumnInfo> res = null; foreach (var line in lines) { var candidates = new List<FixedColumnInfo>(); int blanks = 0; FixedColumnInfo col = null; for (int i = 1; i < line.Length; i++) { if (char.IsWhiteSpace(line[i])) blanks += 1; else { if (blanks > 2) { if (col == null) { col = new FixedColumnInfo { Start = 0, Length = i }; } else { FixedColumnInfo prevCol = col; col = new FixedColumnInfo { Start = prevCol.Start + prevCol.Length }; col.Length = i - col.Start; } candidates.Add(col); blanks = 0; } } } if (col == null) { col = new FixedColumnInfo { Start = 0, Length = line.Length }; } else { FixedColumnInfo prevCol = col; col = new FixedColumnInfo { Start = prevCol.Start + prevCol.Length }; col.Length = line.Length - col.Start; } candidates.Add(col); res = JoinFixedColCandidates(res, candidates); } return res; } private List<FixedColumnInfo> JoinFixedColCandidates(List<FixedColumnInfo> cand1, List<FixedColumnInfo> cand2) { if (cand1 == null) return cand2; if (cand2 == null) return cand1; // Merge the result based on confidence return cand1; } bool HeadersInData (DelimiterInfo info, string[] headerValues, string[] rows) { var duplicate = 0; var first = true; foreach (var row in rows) { if (first) { first = false; continue; } var values = row.Split (new char[]{ info.Delimiter }); if (values.Length != headerValues.Length) continue; for (int i = 0; i < values.Length; i++) { if (values [i] == headerValues [i]) duplicate++; } } return duplicate >= rows.Length * 0.25; } bool DetectIfContainsHeaders (DelimiterInfo info, string[][] sampleData) { if (sampleData.Length >= 2) { return SameFirstLine (info, sampleData); } if (sampleData.Length >= 1) { var firstLine = sampleData [0] [0].Split (new char[]{ info.Delimiter }); var res = AreAllHeaders (firstLine); if (res == false) return false; // if has headers that starts with numbers so near sure are data and no header is present if (HeadersInData(info, firstLine, sampleData[0])) return false; return true; } return false; } bool SameFirstLine (DelimiterInfo info, string[][] sampleData) { for (int i = 1; i < sampleData.Length; i++) { if (!SameHeaders (info, sampleData [0][0], sampleData [i][0])) return false; } return true; } bool SameHeaders (DelimiterInfo info, string line1, string line2) { return line1.Replace (info.Delimiter.ToString (), "").Trim () == line2.Replace (info.Delimiter.ToString (), "").Trim (); } bool AreAllHeaders ( string[] rowData) { foreach (var item in rowData) { var fieldData = item.Trim (); if (fieldData.Length == 0) return false; if (char.IsDigit (fieldData [0])) return false; } return true; } // DELIMITED private void CreateDelimiterOptions(string[][] sampleData, List<RecordFormatInfo> res, char delimiter = '\0') { var delimiters = new List<DelimiterInfo>(); if (delimiter == '\0') delimiters = GetDelimiters(sampleData); else delimiters.Add(GetDelimiterInfo(sampleData, delimiter)); foreach (var info in delimiters) { var format = new RecordFormatInfo { mConfidence = (int) ((1 - info.Deviation)*100) }; AdjustConfidence(format, info); var fileHasHeaders = false; if (FileHasHeaders.HasValue) fileHasHeaders = FileHasHeaders.Value; else { fileHasHeaders = DetectIfContainsHeaders (info, sampleData) ; } var builder = new DelimitedClassBuilder("AutoDetectedClass", info.Delimiter.ToString()) { IgnoreFirstLines = fileHasHeaders ? 1 : 0 }; var firstLineSplitted = sampleData[0][0].Split(info.Delimiter); for (int i = 0; i < info.Max + 1; i++) { string name = "Field " + (i + 1).ToString().PadLeft(3, '0'); if (fileHasHeaders && i < firstLineSplitted.Length) name = firstLineSplitted[i]; var f = builder.AddField(StringHelper.ToValidIdentifier(name)); if (i > info.Min) f.FieldOptional = true; } format.mClassBuilder = builder; res.Add(format); } } private void AdjustConfidence(RecordFormatInfo format, DelimiterInfo info) { switch (info.Delimiter) { case '"': // Avoid the quote identifier case '\'': // Avoid the quote identifier format.mConfidence = (int) (format.Confidence*0.2); break; case '/': // Avoid the date delimiters and url to be selected case '.': // Avoid the decimal separator to be selected format.mConfidence = (int) (format.Confidence*0.4); break; case '@': // Avoid the mails separator to be selected case '&': // Avoid this is near a letter and URLS case '=': // Avoid because URLS contains it case ':': // Avoid because URLS contains it format.mConfidence = (int) (format.Confidence*0.6); break; case '-': // Avoid this other date separator format.mConfidence = (int) (format.Confidence*0.7); break; case ',': // Help the , ; tab | to be confident case ';': case '\t': case '|': format.mConfidence = (int) Math.Min(100, format.Confidence*1.15); break; } } #endregion #region " Helper & Utility Methods " private string[][] GetSampleLines(IEnumerable<string> files, int nroOfLines) { var res = new List<string[]>(); foreach (var file in files) res.Add(CommonEngine.RawReadFirstLinesArray(file, nroOfLines, mEncoding)); return res.ToArray(); } private string[][] GetSampleLines(IEnumerable<TextReader> files, int nroOfLines) { var res = new List<string[]>(); foreach (var file in files) res.Add(CommonEngine.RawReadFirstLinesArray(file, nroOfLines, mEncoding)); return res.ToArray(); } private int NumberOfLines(string[][] data) { int lines = 0; foreach (var fileData in data) lines += fileData.Length; return lines; } /// <summary> /// Calculate statistics based on sample data for the delimitter supplied /// </summary> /// <param name="data"></param> /// <param name="delimiter"></param> /// <returns></returns> private DelimiterInfo GetDelimiterInfo(string[][] data, char delimiter) { var indicators = Indicators.CalculateByDelimiter (delimiter, data, QuotedChar); return new DelimiterInfo (delimiter, indicators.Avg, indicators.Max, indicators.Min, indicators.Deviation); } private List<DelimiterInfo> GetDelimiters(string[][] data) { var frequency = new Dictionary<char, int>(); int lines = 0; for (int i = 0; i < data.Length; i++) { for (int j = 0; j < data[i].Length; j++) { // Ignore Header Line (if any) if (j == 0) continue; // ignore empty lines string line = data[i][j]; if (string.IsNullOrEmpty (line)) continue; // analyse line lines++; for (int ci = 0; ci < line.Length; ci++) { char c = line[ci]; if (char.IsLetterOrDigit(c) || c == ' ') continue; int count; if (frequency.TryGetValue(c, out count)) { count++; frequency[c] = count; } else frequency.Add(c, 1); } } } var candidates = new List<DelimiterInfo>(); // sanity check if (lines == 0) return candidates; // remove delimiters with low occurrence count var delimiters = new List<char> (frequency.Count); foreach (var pair in frequency) { if (pair.Value >= lines) delimiters.Add (pair.Key); } // calculate foreach (var key in delimiters) { var indicators = Indicators.CalculateByDelimiter (key, data, QuotedChar); // Adjust based on the number of lines if (lines < MinSampleData) indicators.Deviation = indicators.Deviation * Math.Min (1, ((double)lines) / MinSampleData); if (indicators.Avg > 1 && indicators.Deviation < MinDelimitedDeviation) candidates.Add (new DelimiterInfo (key, indicators.Avg, indicators.Max, indicators.Min, indicators.Deviation)); } return candidates; } #endregion /// <summary> /// Gets or sets the quoted char. /// </summary> /// <value>The quoted char.</value> private char QuotedChar { get; set; } #region " Statistics Functions " /// <summary> /// Collection of statistics about fields found /// </summary> private class Indicators { /// <summary> /// Maximum number of fields found /// </summary> public int Max = int.MinValue; /// <summary> /// Mimumim number of fields found /// </summary> public int Min = int.MaxValue; /// <summary> /// Average number of delimiters foudn per line /// </summary> public double Avg = 0; /// <summary> /// Calculated deviation /// </summary> public double Deviation = 0; /// <summary> /// Total analysed lines /// </summary> public int Lines = 0; private static double CalculateDeviation (IList<int> values, double avg) { double sum = 0; for (int i = 0; i < values.Count; i++) { sum += Math.Pow (values[i] - avg, 2); } return Math.Sqrt (sum / values.Count); } private static int CountNumberOfDelimiters (string line, char delimiter) { int count = 0; char c; for (int i = 0; i < line.Length; i++) { c = line[i]; if (c == ' ' || char.IsLetterOrDigit (c)) continue; count++; } return count; } public static Indicators CalculateByDelimiter (char delimiter, string[][] data, char? quotedChar) { var res = new Indicators (); int totalDelimiters = 0; int lines = 0; List<int> delimiterPerLine = new List<int> (100); foreach (var fileData in data) { foreach (var line in fileData) { if (string.IsNullOrEmpty (line)) continue; lines++; var delimiterInLine = 0; if (quotedChar.HasValue) delimiterInLine = QuoteHelper.CountNumberOfDelimiters (line, delimiter, quotedChar.Value); else delimiterInLine = CountNumberOfDelimiters (line, delimiter); // add count for deviation analysis delimiterPerLine.Add (delimiterInLine); if (delimiterInLine > res.Max) res.Max = delimiterInLine; if (delimiterInLine < res.Min) res.Min = delimiterInLine; totalDelimiters += delimiterInLine; } } res.Avg = totalDelimiters / (double)lines; // calculate deviation res.Deviation = CalculateDeviation (delimiterPerLine, res.Avg); return res; } public static Indicators CalculateAsFixedSize (string[][] data) { var res = new Indicators (); double sum = 0; int lines = 0; List<int> sizePerLine = new List<int> (100); foreach (var fileData in data) { foreach (var line in fileData) { if (string.IsNullOrEmpty (line)) continue; lines++; sum += line.Length; sizePerLine.Add (line.Length); if (line.Length > res.Max) res.Max = line.Length; if (line.Length < res.Min) res.Min = line.Length; } } res.Avg = sum / (double)lines; // calculate deviation res.Deviation = CalculateDeviation (sizePerLine, res.Avg); return res; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class MaxTests { // Get a set of ranges from 0 to each count, having an extra parameter describing the maximum (count - 1) public static IEnumerable<object[]> MaxData(int[] counts) { Func<int, int> max = x => x - 1; foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), max)) { yield return results; } } // // Max // [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Int(Labeled<ParallelQuery<int>> labeled, int count, int max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Max()); Assert.Equal(max, query.Select(x => (int?)x).Max()); Assert.Equal(0, query.Max(x => -x)); Assert.Equal(0, query.Max(x => -(int?)x)); } [Theory] [OuterLoop] [MemberData(nameof(MaxData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Max_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int max) { Max_Int(labeled, count, max); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Select(x => x >= count / 2 ? (int?)x : null).Max()); Assert.Equal(-count / 2, query.Max(x => x >= count / 2 ? -(int?)x : null)); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int max) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (int?)null).Max()); Assert.Null(query.Max(x => (int?)null)); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Long(Labeled<ParallelQuery<int>> labeled, int count, long max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Select(x => (long)x).Max()); Assert.Equal(max, query.Select(x => (long?)x).Max()); Assert.Equal(0, query.Max(x => -(long)x)); Assert.Equal(0, query.Max(x => -(long?)x)); } [Theory] [OuterLoop] [MemberData(nameof(MaxData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Max_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, long max) { Max_Long(labeled, count, max); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, long max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Select(x => x >= count / 2 ? (long?)x : null).Max()); Assert.Equal(-count / 2, query.Max(x => x >= count / 2 ? -(long?)x : null)); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, long max) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (long?)null).Max()); Assert.Null(query.Max(x => (long?)null)); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Float(Labeled<ParallelQuery<int>> labeled, int count, float max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Select(x => (float)x).Max()); Assert.Equal(max, query.Select(x => (float?)x).Max()); Assert.Equal(0, query.Max(x => -(float)x)); Assert.Equal(0, query.Max(x => -(float?)x)); Assert.Equal(float.PositiveInfinity, query.Select(x => x == count / 2 ? float.PositiveInfinity : x).Max()); Assert.Equal(float.PositiveInfinity, query.Select(x => x == count / 2 ? (float?)float.PositiveInfinity : x).Max()); } [Theory] [OuterLoop] [MemberData(nameof(MaxData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Max_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float max) { Max_Float(labeled, count, max); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Select(x => x >= count / 2 ? (float?)x : null).Max()); Assert.Equal(-count / 2, query.Max(x => x >= count / 2 ? -(float?)x : null)); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float max) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (float?)null).Max()); Assert.Null(query.Max(x => (float?)null)); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Double(Labeled<ParallelQuery<int>> labeled, int count, double max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Select(x => (double)x).Max()); Assert.Equal(max, query.Select(x => (double?)x).Max()); Assert.Equal(0, query.Max(x => -(double)x)); Assert.Equal(0, query.Max(x => -(double?)x)); Assert.Equal(double.PositiveInfinity, query.Select(x => x == count / 2 ? double.PositiveInfinity : x).Max()); Assert.Equal(double.PositiveInfinity, query.Select(x => x == count / 2 ? (double?)double.PositiveInfinity : x).Max()); } [Theory] [OuterLoop] [MemberData(nameof(MaxData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Max_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double max) { Max_Double(labeled, count, max); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Select(x => x >= count / 2 ? (double?)x : null).Max()); Assert.Equal(-count / 2, query.Max(x => x >= count / 2 ? -(double?)x : null)); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double max) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (double?)null).Max()); Assert.Null(query.Max(x => (double?)null)); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Select(x => (decimal)x).Max()); Assert.Equal(max, query.Select(x => (decimal?)x).Max()); Assert.Equal(0, query.Max(x => -(decimal)x)); Assert.Equal(0, query.Max(x => -(decimal?)x)); } [Theory] [OuterLoop] [MemberData(nameof(MaxData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Max_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal max) { Max_Decimal(labeled, count, max); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Select(x => x >= count / 2 ? (decimal?)x : null).Max()); Assert.Equal(-count / 2, query.Max(x => x >= count / 2 ? -(decimal?)x : null)); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal max) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (decimal?)null).Max()); Assert.Null(query.Max(x => (decimal?)null)); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Other(Labeled<ParallelQuery<int>> labeled, int count, int max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Select(x => DelgatedComparable.Delegate(x, Comparer<int>.Default)).Max().Value); Assert.Equal(0, query.Select(x => DelgatedComparable.Delegate(x, ReverseComparer.Instance)).Max().Value); } [Theory] [OuterLoop] [MemberData(nameof(MaxData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Max_Other_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int max) { Max_Other(labeled, count, max); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, }))] public static void Max_NotComparable(Labeled<ParallelQuery<int>> labeled, int count, int max) { NotComparable a = new NotComparable(0); Assert.Equal(a, labeled.Item.Max(x => a)); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Other_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int max) { ParallelQuery<int> query = labeled.Item; Assert.Equal(max, query.Max(x => x >= count / 2 ? DelgatedComparable.Delegate(x, Comparer<int>.Default) : null).Value); Assert.Equal(count / 2, query.Max(x => x >= count / 2 ? DelgatedComparable.Delegate(x, ReverseComparer.Instance) : null).Value); } [Theory] [MemberData(nameof(MaxData), (object)(new int[] { 1, 2, 16 }))] public static void Max_Other_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int max) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (string)null).Max()); Assert.Null(query.Max(x => (string)null)); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0 }), MemberType = typeof(UnorderedSources))] public static void Max_EmptyNullable(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Null(labeled.Item.Max(x => (int?)x)); Assert.Null(labeled.Item.Max(x => (long?)x)); Assert.Null(labeled.Item.Max(x => (float?)x)); Assert.Null(labeled.Item.Max(x => (double?)x)); Assert.Null(labeled.Item.Max(x => (decimal?)x)); Assert.Null(labeled.Item.Max(x => new object())); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0 }), MemberType = typeof(UnorderedSources))] public static void Max_InvalidOperationException(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Throws<InvalidOperationException>(() => labeled.Item.Max()); Assert.Throws<InvalidOperationException>(() => labeled.Item.Max(x => (long)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Max(x => (float)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Max(x => (double)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Max(x => (decimal)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Max(x => new NotComparable(x))); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void Max_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Max(x => x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Max(x => (int?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Max(x => (long)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Max(x => (long?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Max(x => (float)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Max(x => (float?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Max(x => (double)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Max(x => (double?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Max(x => (decimal)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Max(x => (decimal?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Max(x => new NotComparable(x))); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void Max_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Max((Func<int, int>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Max((Func<int, int?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Max((Func<int, long>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Max((Func<int, long?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Max((Func<int, float>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Max((Func<int, float?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Max((Func<int, double>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Max((Func<int, double?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Max((Func<int, decimal>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Max((Func<int, decimal?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Max((Func<int, NotComparable>)(x => { throw new DeliberateTestException(); }))); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Max_AggregateException_NotComparable(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<ArgumentException>(() => labeled.Item.Max(x => new NotComparable(x))); } [Fact] public static void Max_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Max((Func<int?, int?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Max((Func<long, long>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Max((Func<long?, long?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Max((Func<float, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Max((Func<float?, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Max((Func<double, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Max((Func<double?, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Max((Func<decimal, decimal>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Max((Func<decimal?, decimal>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<NotComparable>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Max((Func<int, NotComparable>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<object>)null).Max()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(new object(), 1).Max((Func<object, object>)null)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Services { using System; using System.Collections.Generic; using System.Threading.Tasks; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Services; /// <summary> /// Services async wrapper to simplify testing. /// </summary> public class ServicesAsyncWrapper : IServices { /** Wrapped async services. */ private readonly IServices _services; /// <summary> /// Initializes a new instance of the <see cref="ServicesAsyncWrapper"/> class. /// </summary> /// <param name="services">Services to wrap.</param> public ServicesAsyncWrapper(IServices services) { _services = services; } /** <inheritDoc /> */ public IClusterGroup ClusterGroup { get { return _services.ClusterGroup; } } /** <inheritDoc /> */ public void DeployClusterSingleton(string name, IService service) { _services.DeployClusterSingletonAsync(name, service).Wait(); } /** <inheritDoc /> */ public Task DeployClusterSingletonAsync(string name, IService service) { return _services.DeployClusterSingletonAsync(name, service); } /** <inheritDoc /> */ public void DeployNodeSingleton(string name, IService service) { _services.DeployNodeSingletonAsync(name, service).Wait(); } /** <inheritDoc /> */ public Task DeployNodeSingletonAsync(string name, IService service) { return _services.DeployNodeSingletonAsync(name, service); } /** <inheritDoc /> */ public void DeployKeyAffinitySingleton<TK>(string name, IService service, string cacheName, TK affinityKey) { _services.DeployKeyAffinitySingletonAsync(name, service, cacheName, affinityKey).Wait(); } /** <inheritDoc /> */ public Task DeployKeyAffinitySingletonAsync<TK>(string name, IService service, string cacheName, TK affinityKey) { return _services.DeployKeyAffinitySingletonAsync(name, service, cacheName, affinityKey); } /** <inheritDoc /> */ public void DeployMultiple(string name, IService service, int totalCount, int maxPerNodeCount) { try { _services.DeployMultipleAsync(name, service, totalCount, maxPerNodeCount).Wait(); } catch (AggregateException ex) { throw ex.InnerException ?? ex; } } /** <inheritDoc /> */ public Task DeployMultipleAsync(string name, IService service, int totalCount, int maxPerNodeCount) { return _services.DeployMultipleAsync(name, service, totalCount, maxPerNodeCount); } /** <inheritDoc /> */ public void Deploy(ServiceConfiguration configuration) { try { _services.DeployAsync(configuration).Wait(); } catch (AggregateException ex) { throw ex.InnerException ?? ex; } } /** <inheritDoc /> */ public Task DeployAsync(ServiceConfiguration configuration) { return _services.DeployAsync(configuration); } /** <inheritDoc /> */ public void DeployAll(IEnumerable<ServiceConfiguration> configurations) { try { _services.DeployAllAsync(configurations).Wait(); } catch (AggregateException ex) { throw ex.InnerException ?? ex; } } /** <inheritDoc /> */ public Task DeployAllAsync(IEnumerable<ServiceConfiguration> configurations) { return _services.DeployAllAsync(configurations); } /** <inheritDoc /> */ public void Cancel(string name) { _services.CancelAsync(name).Wait(); } /** <inheritDoc /> */ public Task CancelAsync(string name) { return _services.CancelAsync(name); } /** <inheritDoc /> */ public void CancelAll() { _services.CancelAllAsync().Wait(); } /** <inheritDoc /> */ public Task CancelAllAsync() { return _services.CancelAllAsync(); } /** <inheritDoc /> */ public ICollection<IServiceDescriptor> GetServiceDescriptors() { return _services.GetServiceDescriptors(); } /** <inheritDoc /> */ public T GetService<T>(string name) { return _services.GetService<T>(name); } /** <inheritDoc /> */ public ICollection<T> GetServices<T>(string name) { return _services.GetServices<T>(name); } /** <inheritDoc /> */ public T GetServiceProxy<T>(string name) where T : class { return _services.GetServiceProxy<T>(name); } /** <inheritDoc /> */ public T GetServiceProxy<T>(string name, bool sticky) where T : class { return _services.GetServiceProxy<T>(name, sticky); } /** <inheritDoc /> */ public T GetServiceProxy<T>(string name, bool sticky, IServiceCallContext callCtx) where T : class { return _services.GetServiceProxy<T>(name, sticky, callCtx); } /** <inheritDoc /> */ public dynamic GetDynamicServiceProxy(string name) { return _services.GetDynamicServiceProxy(name); } /** <inheritDoc /> */ public dynamic GetDynamicServiceProxy(string name, bool sticky) { return _services.GetDynamicServiceProxy(name, sticky); } /** <inheritDoc /> */ public dynamic GetDynamicServiceProxy(string name, bool sticky, IServiceCallContext callCtx) { return _services.GetDynamicServiceProxy(name, sticky, callCtx); } /** <inheritDoc /> */ public IServices WithKeepBinary() { return new ServicesAsyncWrapper(_services.WithKeepBinary()); } /** <inheritDoc /> */ public IServices WithServerKeepBinary() { return new ServicesAsyncWrapper(_services.WithServerKeepBinary()); } } }
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace Lucene.Net.Store { /* * 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 CodecUtil = Lucene.Net.Codecs.CodecUtil; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IOUtils = Lucene.Net.Util.IOUtils; /// <summary> /// Combines multiple files into a single compound file. /// <para/> /// @lucene.internal /// </summary> /// <seealso cref="CompoundFileDirectory"/> internal sealed class CompoundFileWriter : IDisposable { private sealed class FileEntry { /// <summary> /// source file </summary> internal string File { get; set; } internal long Length { get; set; } /// <summary> /// temporary holder for the start of this file's data section </summary> internal long Offset { get; set; } /// <summary> /// the directory which contains the file. </summary> internal Directory Dir { get; set; } } // Before versioning started. internal const int FORMAT_PRE_VERSION = 0; // Segment name is not written in the file names. internal const int FORMAT_NO_SEGMENT_PREFIX = -1; // versioning for the .cfs file internal const string DATA_CODEC = "CompoundFileWriterData"; internal const int VERSION_START = 0; internal const int VERSION_CHECKSUM = 1; internal const int VERSION_CURRENT = VERSION_CHECKSUM; // versioning for the .cfe file internal const string ENTRY_CODEC = "CompoundFileWriterEntries"; private readonly Directory directory; private readonly IDictionary<string, FileEntry> entries = new Dictionary<string, FileEntry>(); private readonly ISet<string> seenIDs = new HashSet<string>(); // all entries that are written to a sep. file but not yet moved into CFS private readonly LinkedList<FileEntry> pendingEntries = new LinkedList<FileEntry>(); private bool closed = false; private IndexOutput dataOut; private readonly AtomicBoolean outputTaken = new AtomicBoolean(false); internal readonly string entryTableName; internal readonly string dataFileName; /// <summary> /// Create the compound stream in the specified file. The file name is the /// entire name (no extensions are added). /// </summary> /// <exception cref="ArgumentNullException"> /// if <paramref name="dir"/> or <paramref name="name"/> is <c>null</c> </exception> internal CompoundFileWriter(Directory dir, string name) { if (dir == null) { throw new ArgumentNullException("directory cannot be null"); } if (name == null) { throw new ArgumentNullException("name cannot be null"); } directory = dir; entryTableName = IndexFileNames.SegmentFileName(IndexFileNames.StripExtension(name), "", IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION); dataFileName = name; } private IndexOutput GetOutput() { lock (this) { if (dataOut == null) { bool success = false; try { dataOut = directory.CreateOutput(dataFileName, IOContext.DEFAULT); CodecUtil.WriteHeader(dataOut, DATA_CODEC, VERSION_CURRENT); success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(dataOut); } } } return dataOut; } } /// <summary> /// Returns the directory of the compound file. </summary> internal Directory Directory { get { return directory; } } /// <summary> /// Returns the name of the compound file. </summary> internal string Name { get { return dataFileName; } } /// <summary> /// Disposes all resources and writes the entry table /// </summary> /// <exception cref="InvalidOperationException"> /// if <see cref="Dispose"/> had been called before or if no file has been added to /// this object </exception> public void Dispose() { if (closed) { return; } IOException priorException = null; IndexOutput entryTableOut = null; // TODO this code should clean up after itself // (remove partial .cfs/.cfe) try { if (pendingEntries.Count > 0 || outputTaken.Get()) { throw new InvalidOperationException("CFS has pending open files"); } closed = true; // open the compound stream GetOutput(); Debug.Assert(dataOut != null); CodecUtil.WriteFooter(dataOut); } catch (IOException e) { priorException = e; } finally { IOUtils.DisposeWhileHandlingException(priorException, dataOut); } try { entryTableOut = directory.CreateOutput(entryTableName, IOContext.DEFAULT); WriteEntryTable(entries.Values, entryTableOut); } catch (IOException e) { priorException = e; } finally { IOUtils.DisposeWhileHandlingException(priorException, entryTableOut); } } private void EnsureOpen() { if (closed) { throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, "CFS Directory is already closed"); } } /// <summary> /// Copy the contents of the file with specified extension into the provided /// output stream. /// </summary> private long CopyFileEntry(IndexOutput dataOut, FileEntry fileEntry) { IndexInput @is = fileEntry.Dir.OpenInput(fileEntry.File, IOContext.READ_ONCE); bool success = false; try { long startPtr = dataOut.GetFilePointer(); long length = fileEntry.Length; dataOut.CopyBytes(@is, length); // Verify that the output length diff is equal to original file long endPtr = dataOut.GetFilePointer(); long diff = endPtr - startPtr; if (diff != length) { throw new IOException("Difference in the output file offsets " + diff + " does not match the original file length " + length); } fileEntry.Offset = startPtr; success = true; return length; } finally { if (success) { IOUtils.Dispose(@is); // copy successful - delete file fileEntry.Dir.DeleteFile(fileEntry.File); } else { IOUtils.DisposeWhileHandlingException(@is); } } } private void WriteEntryTable(ICollection<FileEntry> entries, IndexOutput entryOut) { CodecUtil.WriteHeader(entryOut, ENTRY_CODEC, VERSION_CURRENT); entryOut.WriteVInt32(entries.Count); foreach (FileEntry fe in entries) { entryOut.WriteString(IndexFileNames.StripSegmentName(fe.File)); entryOut.WriteInt64(fe.Offset); entryOut.WriteInt64(fe.Length); } CodecUtil.WriteFooter(entryOut); } internal IndexOutput CreateOutput(string name, IOContext context) { EnsureOpen(); bool success = false; bool outputLocked = false; try { Debug.Assert(name != null, "name must not be null"); if (entries.ContainsKey(name)) { throw new ArgumentException("File " + name + " already exists"); } FileEntry entry = new FileEntry(); entry.File = name; entries[name] = entry; string id = IndexFileNames.StripSegmentName(name); Debug.Assert(!seenIDs.Contains(id), "file=\"" + name + "\" maps to id=\"" + id + "\", which was already written"); seenIDs.Add(id); DirectCFSIndexOutput @out; if ((outputLocked = outputTaken.CompareAndSet(false, true))) { @out = new DirectCFSIndexOutput(this, GetOutput(), entry, false); } else { entry.Dir = this.directory; @out = new DirectCFSIndexOutput(this, directory.CreateOutput(name, context), entry, true); } success = true; return @out; } finally { if (!success) { entries.Remove(name); if (outputLocked) // release the output lock if not successful { Debug.Assert(outputTaken.Get()); ReleaseOutputLock(); } } } } internal void ReleaseOutputLock() { outputTaken.CompareAndSet(true, false); } private void PrunePendingEntries() { // claim the output and copy all pending files in if (outputTaken.CompareAndSet(false, true)) { try { while (pendingEntries.Count > 0) { FileEntry entry = pendingEntries.First.Value; pendingEntries.Remove(entry); ; CopyFileEntry(GetOutput(), entry); entries[entry.File] = entry; } } finally { bool compareAndSet = outputTaken.CompareAndSet(true, false); Debug.Assert(compareAndSet); } } } internal long FileLength(string name) { FileEntry fileEntry = entries[name]; if (fileEntry == null) { throw new FileNotFoundException(name + " does not exist"); } return fileEntry.Length; } internal bool FileExists(string name) { return entries.ContainsKey(name); } internal string[] ListAll() { return entries.Keys.ToArray(); } private sealed class DirectCFSIndexOutput : IndexOutput { private readonly CompoundFileWriter outerInstance; private readonly IndexOutput @delegate; private readonly long offset; private bool closed; private FileEntry entry; private long writtenBytes; private readonly bool isSeparate; internal DirectCFSIndexOutput(CompoundFileWriter outerInstance, IndexOutput @delegate, FileEntry entry, bool isSeparate) : base() { this.outerInstance = outerInstance; this.@delegate = @delegate; this.entry = entry; entry.Offset = offset = @delegate.GetFilePointer(); this.isSeparate = isSeparate; } [MethodImpl(MethodImplOptions.NoInlining)] public override void Flush() { @delegate.Flush(); } protected override void Dispose(bool disposing) { if (disposing && !closed) { closed = true; entry.Length = writtenBytes; if (isSeparate) { @delegate.Dispose(); // we are a separate file - push into the pending entries outerInstance.pendingEntries.AddLast(entry); } else { // we have been written into the CFS directly - release the lock outerInstance.ReleaseOutputLock(); } // now prune all pending entries and push them into the CFS outerInstance.PrunePendingEntries(); } } public override long GetFilePointer() { return @delegate.GetFilePointer() - offset; } [Obsolete("(4.1) this method will be removed in Lucene 5.0")] public override void Seek(long pos) { Debug.Assert(!closed); @delegate.Seek(offset + pos); } public override long Length { get { Debug.Assert(!closed); return @delegate.Length - offset; } } public override void WriteByte(byte b) { Debug.Assert(!closed); writtenBytes++; @delegate.WriteByte(b); } public override void WriteBytes(byte[] b, int offset, int length) { Debug.Assert(!closed); writtenBytes += length; @delegate.WriteBytes(b, offset, length); } public override long Checksum { get { return @delegate.Checksum; } } } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr 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.Linq; using System.Text; using System.Windows.Controls; using SpatialAnalysis.Geometry; using System.Windows.Shapes; using SpatialAnalysis.CellularEnvironment; using System.Windows; using System.Windows.Input; using System.Windows.Media; using SpatialAnalysis.IsovistUtility; using System.Threading.Tasks; using System.Windows.Threading; using System.Threading; using System.Windows.Media.Imaging; using SpatialAnalysis.Agents.Visualization.AgentModel; using System.Windows.Data; using SpatialAnalysis.Data.Visualization; using SpatialAnalysis.Miscellaneous; using SpatialAnalysis.Interoperability; namespace SpatialAnalysis.Events { /// <summary> /// Class VisualEventVisualHost. /// </summary> /// <seealso cref="System.Windows.Controls.Canvas" /> internal class VisualEventVisualHost: Canvas { private static Color[] AreaColors =new Color[2]{Colors.Green, Colors.DarkBlue}; /// <summary> /// Gets the color through interpolation. /// </summary> /// <param name="count">The count.</param> /// <param name="max">The maximum.</param> /// <param name="alpha">The alpha.</param> /// <returns>Color.</returns> public static Color GetColor(int count, int max, byte alpha) { float w1 = ((float)count)/max; Color color = Color.Add(Color.Multiply(AreaColors[0], w1), Color.Multiply(AreaColors[1], 1.0f-w1)); color.A = alpha; return color; } private OSMDocument _host { get; set; } private VisualEventSettings _settings { get; set; } private MenuItem _showVisibleArea { get; set; } private MenuItem _reportVisibilityDetails { get; set; } private MenuItem _setEvents { get; set; } private MenuItem _eventMenu { get; set; } private MenuItem _generateData { get; set; } private double _stroke_thickness; /// <summary> /// Initializes a new instance of the <see cref="VisualEventVisualHost"/> class. /// </summary> public VisualEventVisualHost() { this._eventMenu = new MenuItem { Header = "Visual Events" }; this._setEvents = new MenuItem { Header = "Set Event" }; this._showVisibleArea = new MenuItem { Header = "Show Visible Area" }; this._reportVisibilityDetails = new MenuItem { Header = "Report Visibility Details" }; this._eventMenu.Items.Add(this._setEvents); this._eventMenu.Items.Add(this._reportVisibilityDetails); this._eventMenu.Items.Add(this._showVisibleArea); this._setEvents.Click += _setEvents_Click; this._reportVisibilityDetails.Click += _reportVisibilityDetails_Click; this._showVisibleArea.Click += _showVisibleArea_Click; this._generateData = new MenuItem { Header = "Visibility Method" }; this._generateData.Click += _generateData_Click; this._stroke_thickness = 0.1d; } private void _reportVisibilityDetails_Click(object sender, RoutedEventArgs e) { int allVisibleCells = this._host.VisualEventSettings.AllVisibleCells.Count; int vantageCells = this._host.VisualEventSettings.VantageCells.Count; int field = 0, visualBarriers = 0; foreach (Cell item in this._host.cellularFloor.Cells) { if (item.FieldOverlapState == OverlapState.Inside) { field++; } if (item.VisualOverlapState == OverlapState.Outside) { visualBarriers++; } } StringBuilder sb = new StringBuilder(); sb.AppendLine("Number of Visible Cells: \t" + allVisibleCells.ToString()); double cellArea = this._host.cellularFloor.CellSize * this._host.cellularFloor.CellSize; sb.AppendLine("Area of Visible Cells: \t\t" + (allVisibleCells * cellArea).ToString("0.00000")); sb.AppendLine(""); sb.AppendLine("All of the vantage cells are also included in the 'Visible Cells'."); MessageBox.Show(sb.ToString(), "Visibility Report".ToUpper()); sb.Clear(); sb = null; } void _generateData_Click(object sender, RoutedEventArgs e) { this._barriers = new List<SpatialAnalysis.Geometry.BarrierPolygon>(); this._destinations = new HashSet<Cell>(); this._settings = new VisualEventSettings(this._host.cellularFloor, true); this._settings.Owner = this._host; this._settings._addVisibilityArea.Click += _addVisibilityArea_Click; this._settings._addVisibilityPoints.Click += _addVisibilityPoints_Click; this._settings.Closing += new System.ComponentModel.CancelEventHandler(_settings_Closing); this._settings._close.Click += new RoutedEventHandler(_generateDataTermination_Click); this._settings._title.Text = "Visibility to Spatial Data"; this._settings.ShowDialog(); } void _showVisibleArea_Click(object sender, RoutedEventArgs e) { if (this._host.agentVisiblArea.Source==null) { MessageBox.Show("Visibility area was not defined for event capturing"); return; } string title = ((MenuItem)sender).Header as string; switch (title) { case "Hide Visible Area": this._host.agentVisiblArea.Visibility = System.Windows.Visibility.Collapsed; this._showVisibleArea.Header = "Show Visible Area"; break; case "Show Visible Area": this._host.agentVisiblArea.Visibility = System.Windows.Visibility.Visible; this._showVisibleArea.Header = "Hide Visible Area"; break; } } /// <summary> /// Sets the visual events. /// </summary> /// <param name="routedEventHandler">The routed event handler.</param> public void SetVisualEvents(EventHandler routedEventHandler) { this._barriers = new List<SpatialAnalysis.Geometry.BarrierPolygon>(); this._destinations = new HashSet<Cell>(); this._settings = new VisualEventSettings(this._host.cellularFloor, false); this._settings.Owner = this._host; this._settings._addVisibilityArea.Click += _addVisibilityArea_Click; this._settings._addVisibilityPoints.Click += _addVisibilityPoints_Click; this._settings.Closing += new System.ComponentModel.CancelEventHandler(_settings_Closing); this._settings.Closed += routedEventHandler; this._settings._close.Click += new RoutedEventHandler(_close_Click); this._settings.ShowDialog(); } void _setEvents_Click(object sender, RoutedEventArgs e) { this._barriers = new List<SpatialAnalysis.Geometry.BarrierPolygon>(); this._destinations = new HashSet<Cell>(); this._settings = new VisualEventSettings(this._host.cellularFloor, false); this._settings.Owner = this._host; this._settings._addVisibilityArea.Click += _addVisibilityArea_Click; this._settings._addVisibilityPoints.Click += _addVisibilityPoints_Click; this._settings.Closing += new System.ComponentModel.CancelEventHandler(_settings_Closing); this._settings._close.Click += new RoutedEventHandler(_close_Click); this._settings.ShowDialog(); } void _close_Click(object sender, RoutedEventArgs e) { HashSet<Index> allIndices = new HashSet<Index>(); foreach (SpatialAnalysis.Geometry.BarrierPolygon item in this._barriers) { allIndices.UnionWith(this._host.cellularFloor.GetIndicesInsideBarrier(item, 0.0000001)); } var visibleCells = new HashSet<int>(); foreach (Index item in allIndices) { if (this._host.cellularFloor.ContainsCell(item) && this._host.cellularFloor.Cells[item.I, item.J].VisualOverlapState == OverlapState.Outside) { visibleCells.Add(this._host.cellularFloor.Cells[item.I, item.J].ID); } } allIndices.Clear(); allIndices = null; foreach (Cell item in this._destinations) { if (item.VisualOverlapState == OverlapState.Outside) { visibleCells.Add(item.ID); } } if (visibleCells.Count==0) { MessageBox.Show("Cannot Proceed without Setting Visibility Targets!"); return; } this._settings._panel1.Visibility = this._settings._panel2.Visibility = System.Windows.Visibility.Collapsed; this._settings._panel4.Visibility = System.Windows.Visibility.Visible; var cellsOnEdge = CellUtility.GetEdgeOfField(this._host.cellularFloor, visibleCells); List<Isovist> isovists = new List<Isovist>(cellsOnEdge.Count); this._settings.progressBar.Maximum = cellsOnEdge.Count; this._settings.progressBar.Minimum = 0; double depth = this._host.cellularFloor.Origin.DistanceTo(this._host.cellularFloor.TopRight)+1; foreach (int item in cellsOnEdge) { isovists.Add(new Isovist(this._host.cellularFloor.FindCell(item))); } var timer = new System.Diagnostics.Stopwatch(); timer.Start(); Parallel.ForEach(isovists, (a)=> { a.Compute(depth, BarrierType.Visual,this._host.cellularFloor,0.0000001); Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { double val = this._settings.progressBar.Value + 1; this._settings.progressBar.SetValue(ProgressBar.ValueProperty, val); } , null); Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { double x = this._settings.progressBar.Value / this._settings.progressBar.Maximum; int percent = (int)(x * 100); int minutes = (int)Math.Floor(timer.Elapsed.TotalMinutes); int seconds = (int)(timer.Elapsed.Seconds); string message = string.Format("{0} minutes and {1} seconds\n%{2} completed", minutes.ToString(), seconds.ToString(), percent.ToString()); this._settings.IsovistPrgressReport.SetValue(TextBlock.TextProperty, message); } , null); Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() => { })).Wait(TimeSpan.FromMilliseconds(1)); }); var t = timer.Elapsed.TotalMilliseconds; timer.Stop(); HashSet<int> visibleArea = new HashSet<int>(); foreach (Isovist item in isovists) { visibleArea.UnionWith(item.VisibleCells); } foreach (Cell item in this._destinations) { UV p1 = item; UV p2 = item + this._host.cellularFloor.CellSize * UV.UBase; UV p3 = item + this._host.cellularFloor.CellSize * (UV.UBase + UV.VBase); UV p4 = item + this._host.cellularFloor.CellSize * UV.VBase; var polygon = new SpatialAnalysis.Geometry.BarrierPolygon(new UV[4] { p1, p2, p3, p4 }); this._barriers.Add(polygon); } this._host.VisualEventSettings = new VisibilityTarget(visibleArea, isovists, this._barriers.ToArray()); #region visualization double _h = ((UIElement)this.Parent).RenderSize.Height; double _w = ((UIElement)this.Parent).RenderSize.Width; this._host.agentVisiblArea.Source = null; WriteableBitmap _view = BitmapFactory.New((int)_w, (int)_h); this._host.agentVisiblArea.Source = _view; this._host.agentVisiblArea.Visibility = System.Windows.Visibility.Visible; this._showVisibleArea.Header = "Hide Visible Area"; switch (this._settings._colorCode.IsChecked.Value) { case true: using (_view.GetBitmapContext()) { int max = int.MinValue; foreach (var item in this._host.VisualEventSettings.ReferencedVantageCells.Values) { if (max < item.Count) max = item.Count; } byte alpha = (byte)(255 * 0.4); Color yellow = Color.Add(Colors.Yellow, Color.Multiply(Colors.Red, 4.0f)); yellow.ScA = 0.7f; foreach (int cellID in visibleArea) { Cell item = this._host.cellularFloor.FindCell(cellID); Point p1 = this._host.Transform(item); Point p2 = this._host.Transform(item + new UV(this._host.cellularFloor.CellSize, this._host.cellularFloor.CellSize)); _view.FillRectangle((int)p1.X, (int)p1.Y, (int)p2.X, (int)p2.Y, GetColor(this._host.VisualEventSettings.ReferencedVantageCells[cellID].Count, max, alpha)); } foreach (int cellID in visibleCells) { Cell item = this._host.cellularFloor.FindCell(cellID); Point p1 = this._host.Transform(item); Point p2 = this._host.Transform(item + new UV(this._host.cellularFloor.CellSize, this._host.cellularFloor.CellSize)); _view.FillRectangle((int)p1.X, (int)p1.Y, (int)p2.X, (int)p2.Y, yellow); } } break; case false: using (_view.GetBitmapContext()) { Color green = Colors.GreenYellow; green.ScA = 0.4f; Color yellow = Color.Add(Colors.Yellow, Color.Multiply(Colors.Red, 4.0f)); yellow.ScA = 0.7f; foreach (int cellID in visibleArea) { Cell item = this._host.cellularFloor.FindCell(cellID); Point p1 = this._host.Transform(item); Point p2 = this._host.Transform(item + new UV(this._host.cellularFloor.CellSize, this._host.cellularFloor.CellSize)); _view.FillRectangle((int)p1.X, (int)p1.Y, (int)p2.X, (int)p2.Y, green); } foreach (int cellID in visibleCells) { Cell item = this._host.cellularFloor.FindCell(cellID); Point p1 = this._host.Transform(item); Point p2 = this._host.Transform(item + new UV(this._host.cellularFloor.CellSize, this._host.cellularFloor.CellSize)); _view.FillRectangle((int)p1.X, (int)p1.Y, (int)p2.X, (int)p2.Y, yellow); } } break; } #endregion //cleanup isovists.Clear(); isovists = null; this._settings.Close(); } void _generateDataTermination_Click(object sender, RoutedEventArgs e) { #region Input validation if (string.IsNullOrEmpty(this._settings._dataName.Text)) { MessageBox.Show("Enter Data Field Name"); return; } if (this._host.cellularFloor.AllSpatialDataFields.ContainsKey(this._settings._dataName.Text)) { MessageBox.Show("The Data Field Name Exists. Try a Different Name..."); return; } double _in = 0, _out = 0, _on = 0; if (!double.TryParse(this._settings._valueOfVantageCells.Text, out _on)) { MessageBox.Show("Value of visibility vantage areas is invalid!"); return; } if (!double.TryParse(this._settings._valueOutside.Text, out _out)) { MessageBox.Show("Value of not visible areas is invalid!"); return; } if (!this._settings._interpolationMethod.IsChecked.Value && !double.TryParse(this._settings._constantValue.Text, out _in)) { MessageBox.Show("Value of visible areas is invalid!"); return; } if (this._settings._interpolationMethod.IsChecked.Value) { //test the interpolation function if (!this._settings.LoadFunction()) { return; } } #endregion #region get the vantage Cells HashSet<Index> allIndices = new HashSet<Index>(); foreach (SpatialAnalysis.Geometry.BarrierPolygon item in this._barriers) { allIndices.UnionWith(this._host.cellularFloor.GetIndicesInsideBarrier(item, OSMDocument.AbsoluteTolerance)); } var vantageCells = new HashSet<int>(); foreach (Index item in allIndices) { if (this._host.cellularFloor.ContainsCell(item) && this._host.cellularFloor.Cells[item.I, item.J].VisualOverlapState == OverlapState.Outside) { vantageCells.Add(this._host.cellularFloor.Cells[item.I, item.J].ID); } } allIndices.Clear(); allIndices = null; foreach (Cell item in this._destinations) { if (item.VisualOverlapState == OverlapState.Outside) { vantageCells.Add(item.ID); } } if (vantageCells.Count == 0) { MessageBox.Show("Cannot Proceed without Setting Visibility Targets!"); return; } #endregion this._settings._panel1.Visibility = this._settings._panel2.Visibility = System.Windows.Visibility.Collapsed; this._settings._panel4.Visibility = System.Windows.Visibility.Visible; var cellsOnEdge = CellUtility.GetEdgeOfField(this._host.cellularFloor, vantageCells); List<Isovist> isovists = new List<Isovist>(cellsOnEdge.Count); this._settings.progressBar.Maximum = cellsOnEdge.Count; this._settings.progressBar.Minimum = 0; double depth = this._host.cellularFloor.Origin.DistanceTo(this._host.cellularFloor.TopRight) + 1; foreach (int item in cellsOnEdge) { isovists.Add(new Isovist(this._host.cellularFloor.FindCell(item))); } var timer = new System.Diagnostics.Stopwatch(); timer.Start(); Parallel.ForEach(isovists, (a) => { a.Compute(depth, BarrierType.Visual, this._host.cellularFloor, 0.0000001); Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { double val = this._settings.progressBar.Value + 1; this._settings.progressBar.SetValue(ProgressBar.ValueProperty, val); } , null); Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { double x = this._settings.progressBar.Value / this._settings.progressBar.Maximum; int percent = (int)(x * 100); int minutes = (int)Math.Floor(timer.Elapsed.TotalMinutes); int seconds = (int)(timer.Elapsed.Seconds); string message = string.Format("{0} minutes and {1} seconds\n%{2} completed", minutes.ToString(), seconds.ToString(), percent.ToString()); this._settings.IsovistPrgressReport.SetValue(TextBlock.TextProperty, message); } , null); Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() => { })).Wait(TimeSpan.FromMilliseconds(1)); }); var t = timer.Elapsed.TotalMilliseconds; timer.Stop(); HashSet<int> visibleArea = new HashSet<int>(); foreach (Isovist item in isovists) { visibleArea.UnionWith(item.VisibleCells); } if (this._settings._interpolationMethod.IsChecked.Value) { //HashSet<int> notVisibleCellIds = new HashSet<int>(); //foreach (var item in this._host.cellularFloor.Cells) //{ // if (item.FieldOverlapState != OverlapState.Outside) // { // if (!vantageCells.Contains(item.ID) && !visibleArea.Contains(item.ID)) // { // notVisibleCellIds.Add(item.ID); // } // } //} //var newData = this._host.FieldGenerator.GetSpatialDataField(vantageCells, _on, notVisibleCellIds, _out, this._settings._dataName.Text, this._settings.InterpolationFunction); //this._host.cellularFloor.AddSpatialDataField(newData); Dictionary<Cell, double> data = new Dictionary<Cell, double>(); foreach (var item in this._host.cellularFloor.Cells) { if (item.FieldOverlapState != OverlapState.Outside) { if (vantageCells.Contains(item.ID)) { data.Add(item, _on); } else { if (visibleArea.Contains(item.ID)) { UV visiblePoint = this._host.cellularFloor.FindCell(item.ID); double dist = double.PositiveInfinity; foreach (var id in cellsOnEdge) { var cell = this._host.cellularFloor.FindCell(id); dist = Math.Min(UV.GetLengthSquared(cell, visiblePoint), dist); } double value = _on + this._settings.InterpolationFunction(Math.Sqrt(dist)); data.Add(item, Math.Max(value, _out)); } else { data.Add(item, _out); } } } } Data.SpatialDataField newData = new Data.SpatialDataField(this._settings._dataName.Text, data); this._host.cellularFloor.AddSpatialDataField(newData); } else { Dictionary<Cell, double> data = new Dictionary<Cell, double>(); foreach (var item in this._host.cellularFloor.Cells) { if (item.FieldOverlapState != OverlapState.Outside) { if (vantageCells.Contains(item.ID)) { data.Add(item, _on); } else { if (visibleArea.Contains(item.ID)) { data.Add(item, _in); } else { data.Add(item, _out); } } } } Data.SpatialDataField newData = new Data.SpatialDataField(this._settings._dataName.Text, data); this._host.cellularFloor.AddSpatialDataField(newData); } this._settings.Close(); } void _settings_Closing(object sender, System.ComponentModel.CancelEventArgs e) { this._barriers.Clear(); this._barriers = null; this._destinations.Clear(); this._destinations = null; //set events this._settings._addVisibilityArea.Click -= _addVisibilityArea_Click; this._settings._addVisibilityPoints.Click -= _addVisibilityPoints_Click; this.Children.Clear(); } #region Areas that are checked for visibility private List<UV> _pnts { get; set; } private Line _line { get; set; } private Polyline _polyline { get; set; } private List<SpatialAnalysis.Geometry.BarrierPolygon> _barriers { get; set; } private HashSet<Cell> _destinations { get; set; } #region Add area private void _addVisibilityArea_Click(object sender, RoutedEventArgs e) { this._settings.Hide(); this._host.Menues.IsEnabled = false; this._host.UIMessage.Text = "Click to draw a region"; this._host.UIMessage.Visibility = System.Windows.Visibility.Visible; this._host.Cursor = Cursors.Pen; this._host.FloorScene.MouseLeftButtonDown += getStartpoint; } private void getStartpoint(object sender, MouseButtonEventArgs e) { this._host.FloorScene.MouseLeftButtonDown -= getStartpoint; var point = this._host.InverseRenderTransform.Transform(Mouse.GetPosition(this._host.FloorScene)); UV p = new UV(point.X, point.Y); Cell cell = this._host.cellularFloor.FindCell(p); if (cell == null) { MessageBox.Show("Pick a point on the walkable field and try again!\n"); this._host.Menues.IsEnabled = true; this._host.UIMessage.Visibility = System.Windows.Visibility.Collapsed; this._host.Cursor = Cursors.Arrow; this._settings.ShowDialog(); return; } this._pnts = new List<UV>() { p }; this._line = new Line() { X1 = p.U, Y1 = p.V, StrokeThickness = this._stroke_thickness, Stroke = System.Windows.Media.Brushes.Green, }; this.Children.Add(this._line); this._polyline = new Polyline() { Stroke = System.Windows.Media.Brushes.DarkGreen, StrokeThickness = this._line.StrokeThickness }; this._polyline.Points = new PointCollection() { point }; this.Children.Add(this._polyline); this.registerRegionGenerationEvents(); } private void terminateRegionGeneration_Enter() { this.unregisterRegionGenerationEvents(); if (this._pnts.Count > 1) { Polygon polygon = new Polygon(); polygon.Points = this._polyline.Points.CloneCurrentValue(); polygon.Stroke = Brushes.Black; polygon.StrokeThickness = this._stroke_thickness; polygon.StrokeMiterLimit = 0; Brush brush = Brushes.LightBlue.Clone(); brush.Opacity = .3; polygon.Fill = brush; this.Children.Add(polygon); this._barriers.Add(new SpatialAnalysis.Geometry.BarrierPolygon(this._pnts.ToArray())); } this.Children.Remove(this._polyline); this.Children.Remove(this._line); this._polyline.Points.Clear(); this._polyline = null; this._line = null; this._host.Menues.IsEnabled = true; this._host.UIMessage.Visibility = System.Windows.Visibility.Collapsed; this._host.Cursor = Cursors.Arrow; this._settings.ShowDialog(); } private void terminateRegionGeneration_Cancel() { this.unregisterRegionGenerationEvents(); this.Children.Remove(this._polyline); this.Children.Remove(this._line); this._polyline.Points.Clear(); this._polyline = null; this._line = null; this._host.Menues.IsEnabled = true; this._host.UIMessage.Visibility = System.Windows.Visibility.Collapsed; this._host.Cursor = Cursors.Arrow; this._settings.ShowDialog(); } private void registerRegionGenerationEvents() { this._host.MouseBtn.MouseDown += MouseBtn_MouseDown; this._host.KeyDown += regionTermination_KeyDown; this._host.FloorScene.MouseMove += FloorScene_MouseMove; this._host.FloorScene.MouseLeftButtonDown += getNextRegionPoint; } private void unregisterRegionGenerationEvents() { this._host.MouseBtn.MouseDown -= MouseBtn_MouseDown; this._host.KeyDown -= regionTermination_KeyDown; this._host.FloorScene.MouseMove -= FloorScene_MouseMove; this._host.FloorScene.MouseLeftButtonDown -= getNextRegionPoint; } private void MouseBtn_MouseDown(object sender, MouseButtonEventArgs e) { this.terminateRegionGeneration_Enter(); } private void regionTermination_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { this.terminateRegionGeneration_Enter(); } if (e.Key == Key.Escape) { this.terminateRegionGeneration_Cancel(); } } private void FloorScene_MouseMove(object sender, MouseEventArgs e) { var point = this._host.InverseRenderTransform.Transform(Mouse.GetPosition(this._host.FloorScene)); this._line.X2 = point.X; this._line.Y2 = point.Y; } private void getNextRegionPoint(object sender, MouseButtonEventArgs e) { var point = this._host.InverseRenderTransform.Transform(Mouse.GetPosition(this._host.FloorScene)); UV p = new UV(point.X, point.Y); Cell cell = this._host.cellularFloor.FindCell(p); if (cell == null) { MessageBox.Show("Pick a point on the walkable field and try again!\n"); return; } this._host.UIMessage.Text = "Click to continue; Press enter to close the region; Press escape to abort the region"; this._line.X1 = point.X; this._line.Y1 = point.Y; this._pnts.Add(p); this._polyline.Points.Add(point); } #endregion #region Add cell void _addVisibilityPoints_Click(object sender, RoutedEventArgs e) { this._settings.Hide(); this._host.Menues.IsEnabled = false; this._host.UIMessage.Text = "Click to pick a cell"; this._host.UIMessage.Visibility = System.Windows.Visibility.Visible; this._host.Cursor = Cursors.Pen; this._host.FloorScene.MouseLeftButtonDown += pickCell; } private void pickCell(object sender, MouseButtonEventArgs e) { this._host.FloorScene.MouseLeftButtonDown -= pickCell; var point = this._host.InverseRenderTransform.Transform(Mouse.GetPosition(this._host.FloorScene)); UV p = new UV(point.X, point.Y); Cell cell = this._host.cellularFloor.FindCell(p); if (cell == null) { MessageBox.Show("Pick a point on the floor territory and try again!\n"); } else { this._destinations.Add(cell); var lines = cell.ToUVLines(this._host.cellularFloor.CellSize); Polygon polygon = new Polygon(); polygon.Stroke = Brushes.Black; polygon.StrokeThickness = this._stroke_thickness; polygon.StrokeMiterLimit = 0; Brush brush = Brushes.LightBlue.Clone(); brush.Opacity = .3; polygon.Fill = brush; polygon.Points.Add(new Point(cell.U, cell.V)); polygon.Points.Add(new Point(cell.U + this._host.cellularFloor.CellSize, cell.V)); polygon.Points.Add(new Point(cell.U + this._host.cellularFloor.CellSize, cell.V + this._host.cellularFloor.CellSize)); polygon.Points.Add(new Point(cell.U, cell.V + this._host.cellularFloor.CellSize)); this.Children.Add(polygon); } this._host.Menues.IsEnabled = true; this._host.UIMessage.Visibility = System.Windows.Visibility.Collapsed; this._host.Cursor = Cursors.Arrow; this._settings.ShowDialog(); } #endregion #endregion /// <summary> /// Sets the main document to which this control belongs. /// </summary> /// <param name="host">The host.</param> public void SetHost(OSMDocument host) { this._host = host; this.RenderTransform = this._host.RenderTransformation; this._stroke_thickness = UnitConversion.Convert(0.1d, Length_Unit_Types.FEET, this._host.BIM_To_OSM.UnitType); this._host.Menues.Items.Insert(5, this._eventMenu); this._host._createNewSpatialDataField.Items.Add(this._generateData); var bindConvector = new ValueToBoolConverter(); Binding bind = new Binding("VisualEventSettings"); bind.Source = this._host; bind.Converter = bindConvector; bind.Mode = BindingMode.OneWay; this._reportVisibilityDetails.SetBinding(MenuItem.IsEnabledProperty, bind); } } }
//----------------------------------------------------------------------- // <copyright file="ActorRefBackpressureSinkSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using Akka.Actor; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Dsl { public class ActorRefBackpressureSinkSpec : AkkaSpec { #region internal classes private sealed class TriggerAckMessage { public static readonly TriggerAckMessage Instance = new TriggerAckMessage(); private TriggerAckMessage() { } } private sealed class Fw : ReceiveActor { public Fw(IActorRef aref) { Receive<string>(s => s == InitMessage, s => { Sender.Tell(AckMessage); aref.Forward(InitMessage); }); Receive<string>(s => s == CompleteMessage, s => aref.Forward(CompleteMessage)); Receive<int>(i => { Sender.Tell(AckMessage); aref.Forward(i); }); } } private sealed class Fw2 : ReceiveActor { public Fw2(IActorRef aref) { var actorRef = ActorRefs.NoSender; Receive<TriggerAckMessage>(_ => actorRef.Tell(AckMessage)); ReceiveAny(msg => { actorRef = Sender; aref.Forward(msg); }); } } #endregion private const string InitMessage = "start"; private const string CompleteMessage = "complete"; private const string AckMessage = "ack"; private ActorMaterializer Materializer { get; } public ActorRefBackpressureSinkSpec(ITestOutputHelper output) : base(output) { Materializer = ActorMaterializer.Create(Sys); } private IActorRef CreateActor<T>() => Sys.ActorOf(Props.Create(typeof(T), TestActor).WithDispatcher("akka.test.stream-dispatcher")); [Fact] public void ActorBackpressureSink_should_send_the_elements_to_the_ActorRef() { this.AssertAllStagesStopped(() => { var fw = CreateActor<Fw>(); Source.From(Enumerable.Range(1, 3)) .RunWith(Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage), Materializer); ExpectMsg("start"); ExpectMsg(1); ExpectMsg(2); ExpectMsg(3); ExpectMsg(CompleteMessage); }, Materializer); } [Fact] public void ActorBackpressureSink_should_send_the_elements_to_the_ActorRef2() { this.AssertAllStagesStopped(() => { var fw = CreateActor<Fw>(); var probe = this.SourceProbe<int>() .To(Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage)) .Run(Materializer); probe.SendNext(1); ExpectMsg("start"); ExpectMsg(1); probe.SendNext(2); ExpectMsg(2); probe.SendNext(3); ExpectMsg(3); probe.SendComplete(); ExpectMsg(CompleteMessage); }, Materializer); } [Fact] public void ActorBackpressureSink_should_cancel_stream_when_actor_terminates() { this.AssertAllStagesStopped(() => { var fw = CreateActor<Fw>(); var publisher = this.SourceProbe<int>() .To(Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage)) .Run(Materializer); publisher.SendNext(1); ExpectMsg(InitMessage); ExpectMsg(1); Sys.Stop(fw); publisher.ExpectCancellation(); }, Materializer); } [Fact] public void ActorBackpressureSink_should_send_message_only_when_backpressure_received() { this.AssertAllStagesStopped(() => { var fw = CreateActor<Fw2>(); var publisher = this.SourceProbe<int>() .To(Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage)) .Run(Materializer); ExpectMsg(InitMessage); publisher.SendNext(1); ExpectNoMsg(); fw.Tell(TriggerAckMessage.Instance); ExpectMsg(1); publisher.SendNext(2); publisher.SendNext(3); publisher.SendComplete(); fw.Tell(TriggerAckMessage.Instance); ExpectMsg(2); fw.Tell(TriggerAckMessage.Instance); ExpectMsg(3); ExpectMsg(CompleteMessage); }, Materializer); } [Fact] public void ActorBackpressureSink_should_keep_on_sending_even_after_the_buffer_has_been_full() { this.AssertAllStagesStopped(() => { var bufferSize = 16; var streamElementCount = bufferSize + 4; var fw = CreateActor<Fw2>(); var sink = Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage) .WithAttributes(Attributes.CreateInputBuffer(bufferSize, bufferSize)); var probe = Source.From(Enumerable.Range(1, streamElementCount)) .AlsoToMaterialized( Flow.Create<int>().Take(bufferSize).WatchTermination(Keep.Right).To(Sink.Ignore<int>()), Keep.Right) .To(sink) .Run(Materializer); probe.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); probe.IsCompleted.Should().BeTrue(); ExpectMsg(InitMessage); fw.Tell(TriggerAckMessage.Instance); for (var i = 1; i <= streamElementCount; i++) { ExpectMsg(i); fw.Tell(TriggerAckMessage.Instance); } ExpectMsg(CompleteMessage); }, Materializer); } [Fact] public void ActorBackpressureSink_should_work_with_one_element_buffer() { this.AssertAllStagesStopped(() => { var fw = CreateActor<Fw2>(); var publisher = RunnableGraph.FromGraph( this.SourceProbe<int>() .To(Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage)) .WithAttributes(Attributes.CreateInputBuffer(1, 1))).Run(Materializer); ExpectMsg(InitMessage); fw.Tell(TriggerAckMessage.Instance); publisher.SendNext(1); ExpectMsg(1); fw.Tell(TriggerAckMessage.Instance); ExpectNoMsg(); // Ack received but buffer empty publisher.SendNext(2); // Buffer this value fw.Tell(TriggerAckMessage.Instance); ExpectMsg(2); publisher.SendComplete(); ExpectMsg(CompleteMessage); }, Materializer); } [Fact] public void ActorBackpressurSink_should_fail_to_materialize_with_zero_sized_input_buffer() { var fw = CreateActor<Fw>(); var badSink = Sink.ActorRefWithAck<int>(fw, InitMessage, AckMessage, CompleteMessage) .WithAttributes(Attributes.CreateInputBuffer(0, 0)); Source.Single(1).Invoking(s => s.RunWith(badSink, Materializer)).ShouldThrow<ArgumentException>(); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Security; using ASC.Common.Security; using ASC.Common.Security.Authorizing; using ASC.Core; using ASC.Core.Users; using ASC.CRM.Core.Dao; using ASC.CRM.Core.Entities; using ASC.Files.Core; using ASC.Files.Core.Security; using ASC.Web.Core; using ASC.Web.CRM.Classes; using ASC.Web.CRM.Configuration; using ASC.Web.CRM.Core; using ASC.Web.CRM.Core.Enums; using ASC.Web.CRM.Resources; using Autofac; using Action = ASC.Common.Security.Authorizing.Action; using Constants = ASC.Core.Users.Constants; using SecurityContext = ASC.Core.SecurityContext; namespace ASC.CRM.Core { public static class CRMSecurity { #region Members public static readonly IAction _actionRead = new Action(new Guid("{6F05C382-8BCA-4469-9424-C807A98C40D7}"), "", true, false); #endregion #region Check Permissions private static ISecurityObjectProvider GetCRMSecurityProvider() { return new CRMSecurityObjectProvider(); } public static bool IsPrivate(ISecurityObjectId entity) { return GetAccessSubjectTo(entity).Any(); } public static bool CanAccessTo(ISecurityObjectId entity) { return CanAccessTo(entity, SecurityContext.CurrentAccount.ID); } public static bool CanAccessTo(ISecurityObjectId entity, Guid userId) { return IsAdministrator(userId) || SecurityContext.CheckPermissions(entity, GetCRMSecurityProvider(), _actionRead); } public static void MakePublic(ISecurityObjectId entity) { SetAccessTo(entity, new List<Guid>()); } public static IEnumerable<int> GetPrivateItems(Type objectType) { if (IsAdmin) return new List<int>(); return GetPrivateItems(objectType, Guid.Empty, true); } private static IEnumerable<int> GetPrivateItems(Type objectType, Guid userId, bool withoutUser) { var query = CoreContext.AuthorizationManager .GetAces(userId, _actionRead.ID) .Where( item => !String.IsNullOrEmpty(item.ObjectId) && item.ObjectId.StartsWith(objectType.FullName)) .GroupBy(item => item.ObjectId, item => item.SubjectId); if (withoutUser) { if (userId != Guid.Empty) query = query.Where(item => !item.Contains(userId)); else query = query.Where(item => !item.Contains(SecurityContext.CurrentAccount.ID)); } return query.Select(item => Convert.ToInt32(item.Key.Split(new[] { '|' })[1])); } public static IEnumerable<int> GetContactsIdByManager(Guid userId) { return GetPrivateItems(typeof(Company), userId, false) .Union(GetPrivateItems(typeof(Person), userId, false)); } public static int GetPrivateItemsCount(Type objectType) { if (IsAdmin) return 0; return GetPrivateItems(objectType).Count(); } private static Dictionary<Guid, String> GetAccessSubjectTo(ISecurityObjectId entity, EmployeeStatus employeeStatus) { var allAces = CoreContext.AuthorizationManager.GetAcesWithInherits(Guid.Empty, _actionRead.ID, entity, GetCRMSecurityProvider()) .Where(item => item.SubjectId != Constants.GroupEveryone.ID); var result = new Dictionary<Guid, String>(); foreach (var azRecord in allAces) { if (!result.ContainsKey(azRecord.SubjectId)) { var userInfo = CoreContext.UserManager.GetUsers(azRecord.SubjectId); var displayName = employeeStatus == EmployeeStatus.All || userInfo.Status == employeeStatus ? userInfo.DisplayUserName() : Constants.LostUser.DisplayUserName(); result.Add(azRecord.SubjectId, displayName); } } return result; } public static Dictionary<Guid, String> GetAccessSubjectTo(ISecurityObjectId entity) { return GetAccessSubjectTo(entity, EmployeeStatus.All); } public static List<Guid> GetAccessSubjectGuidsTo(ISecurityObjectId entity) { var allAces = CoreContext.AuthorizationManager.GetAcesWithInherits(Guid.Empty, _actionRead.ID, entity, GetCRMSecurityProvider()) .Where(item => item.SubjectId != Constants.GroupEveryone.ID); var result = new List<Guid>(); foreach (var azRecord in allAces) { if (!result.Contains(azRecord.SubjectId)) result.Add(azRecord.SubjectId); } return result; } public static void SetAccessTo(ISecurityObjectId entity, List<Guid> subjectID) { if (subjectID.Count == 0) { CoreContext.AuthorizationManager.RemoveAllAces(entity); return; } var aces = CoreContext.AuthorizationManager.GetAcesWithInherits(Guid.Empty, _actionRead.ID, entity, GetCRMSecurityProvider()); foreach (var r in aces) { if (!subjectID.Contains(r.SubjectId) && (r.SubjectId != Constants.GroupEveryone.ID || r.Reaction != AceType.Allow)) { CoreContext.AuthorizationManager.RemoveAce(r); } } var oldSubjects = aces.Select(r => r.SubjectId).ToList(); foreach (var s in subjectID) { if (!oldSubjects.Contains(s)) { CoreContext.AuthorizationManager.AddAce(new AzRecord(s, _actionRead.ID, AceType.Allow, entity)); } } CoreContext.AuthorizationManager.AddAce(new AzRecord(Constants.GroupEveryone.ID, _actionRead.ID, AceType.Deny, entity)); } #endregion #region SetAccessTo public static void SetAccessTo(File file) { if (IsAdmin || file.CreateBy == SecurityContext.CurrentAccount.ID || file.ModifiedBy == SecurityContext.CurrentAccount.ID) file.Access = FileShare.None; else file.Access = FileShare.Read; } public static void SetAccessTo(Deal deal, List<Guid> subjectID) { if (IsAdmin || deal.CreateBy == SecurityContext.CurrentAccount.ID) { SetAccessTo((ISecurityObjectId)deal, subjectID); } } public static void SetAccessTo(Cases cases, List<Guid> subjectID) { if (IsAdmin || cases.CreateBy == SecurityContext.CurrentAccount.ID) { SetAccessTo((ISecurityObjectId)cases, subjectID); } } #endregion #region CanAccessTo public static bool CanAccessTo(RelationshipEvent relationshipEvent) { return CanAccessTo(relationshipEvent, SecurityContext.CurrentAccount.ID); } public static bool CanAccessTo(RelationshipEvent relationshipEvent, Guid userId) { if (IsAdministrator(userId)) return true; using (var scope = DIHelper.Resolve()) { var daoFactory = scope.Resolve<DaoFactory>(); if (relationshipEvent.ContactID > 0) { var contactObj = daoFactory.ContactDao.GetByID(relationshipEvent.ContactID); if (contactObj != null) return CanAccessTo(contactObj, userId); } if (relationshipEvent.EntityType == EntityType.Case) { var caseObj = daoFactory.CasesDao.GetByID(relationshipEvent.EntityID); if (caseObj != null) return CanAccessTo(caseObj, userId); } if (relationshipEvent.EntityType == EntityType.Opportunity) { var dealObj = daoFactory.DealDao.GetByID(relationshipEvent.EntityID); if (dealObj != null) return CanAccessTo(dealObj, userId); } return false; } } public static bool CanAccessTo(Contact contact) { return CanAccessTo(contact, SecurityContext.CurrentAccount.ID); } public static bool CanAccessTo(Contact contact, Guid userId) { return contact.ShareType == ShareType.Read || contact.ShareType == ShareType.ReadWrite || IsAdministrator(userId) || GetAccessSubjectTo(contact).ContainsKey(userId); } public static bool CanAccessTo(int contactID, EntityType entityType, ShareType? shareType, int companyID) { if (shareType.HasValue && (shareType.Value == ShareType.Read || shareType.Value == ShareType.ReadWrite) || IsAdmin) { return true; } if (entityType == EntityType.Company) { var fakeContact = new Company() { ID = contactID }; return GetAccessSubjectTo(fakeContact).ContainsKey(SecurityContext.CurrentAccount.ID); } else if (entityType == EntityType.Person) { var fakeContact = new Person() { ID = contactID, CompanyID = companyID }; return GetAccessSubjectTo(fakeContact).ContainsKey(SecurityContext.CurrentAccount.ID); } return false; } public static bool CanAccessTo(Task task) { return CanAccessTo(task, SecurityContext.CurrentAccount.ID); } public static bool CanAccessTo(Task task, Guid userId) { if (IsAdministrator(userId) || task.ResponsibleID == userId || (task.ContactID == 0 && task.EntityID == 0) || task.CreateBy == userId) return true; using (var scope = DIHelper.Resolve()) { var daoFactory = scope.Resolve<DaoFactory>(); if (task.ContactID > 0) { var contactObj = daoFactory.ContactDao.GetByID(task.ContactID); if (contactObj != null) return CanAccessTo(contactObj, userId); } if (task.EntityType == EntityType.Case) { var caseObj = daoFactory.CasesDao.GetByID(task.EntityID); if (caseObj != null) return CanAccessTo(caseObj, userId); } if (task.EntityType == EntityType.Opportunity) { var dealObj = daoFactory.DealDao.GetByID(task.EntityID); if (dealObj != null) return CanAccessTo(dealObj, userId); } return false; } } public static bool CanAccessTo(Invoice invoice) { return CanAccessTo(invoice, SecurityContext.CurrentAccount.ID); } public static bool CanAccessTo(Invoice invoice, Guid userId) { if (IsAdministrator(userId) || invoice.CreateBy == userId) return true; using (var scope = DIHelper.Resolve()) { var daoFactory = scope.Resolve<DaoFactory>(); if (invoice.ContactID > 0) return CanAccessTo(daoFactory.ContactDao.GetByID(invoice.ContactID), userId); if (invoice.EntityType == EntityType.Opportunity) return CanAccessTo(daoFactory.DealDao.GetByID(invoice.EntityID), userId); return false; } } public static bool CanAccessTo(InvoiceTax invoiceTax) { return CanAccessTo(invoiceTax, SecurityContext.CurrentAccount.ID); } public static bool CanAccessTo(InvoiceTax invoiceTax, Guid userId) { if (IsAdministrator(userId) || invoiceTax.CreateBy == userId) return true; return false; } #endregion #region CanEdit public static bool CanEdit(File file) { if (!(IsAdmin || file.CreateBy == SecurityContext.CurrentAccount.ID || file.ModifiedBy == SecurityContext.CurrentAccount.ID)) return false; if ((file.FileStatus & FileStatus.IsEditing) == FileStatus.IsEditing) return false; return true; } public static bool CanEdit(Deal deal) { return (IsAdmin || deal.ResponsibleID == SecurityContext.CurrentAccount.ID || deal.CreateBy == SecurityContext.CurrentAccount.ID || !CRMSecurity.IsPrivate(deal) || GetAccessSubjectTo(deal).ContainsKey(SecurityContext.CurrentAccount.ID)); } public static bool CanEdit(RelationshipEvent relationshipEvent) { var userId = SecurityContext.CurrentAccount.ID; if (IsAdmin) return true; using (var scope = DIHelper.Resolve()) { var daoFactory = scope.Resolve<DaoFactory>(); if (relationshipEvent.ContactID > 0) { var contactObj = daoFactory.ContactDao.GetByID(relationshipEvent.ContactID); if (contactObj != null) { if (CanEdit(contactObj)) return true; return CanAccessTo(contactObj, userId) && relationshipEvent.CreateBy == userId; } } if (relationshipEvent.EntityType == EntityType.Case) { var caseObj = daoFactory.CasesDao.GetByID(relationshipEvent.EntityID); if (caseObj != null) { if (CanEdit(caseObj)) return true; return CanAccessTo(caseObj, userId) && relationshipEvent.CreateBy == userId; } } if (relationshipEvent.EntityType == EntityType.Opportunity) { var dealObj = daoFactory.DealDao.GetByID(relationshipEvent.EntityID); if (dealObj != null) { if (CanEdit(dealObj)) return true; return CanAccessTo(dealObj, userId) && relationshipEvent.CreateBy == userId; } } return false; } } public static bool CanEdit(Contact contact) { return contact.ShareType == ShareType.ReadWrite || IsAdmin || GetAccessSubjectTo(contact).ContainsKey(SecurityContext.CurrentAccount.ID); } public static bool CanEdit(Task task) { return (IsAdmin || task.ResponsibleID == SecurityContext.CurrentAccount.ID || task.CreateBy == SecurityContext.CurrentAccount.ID); } public static bool CanEdit(Cases cases) { return (IsAdmin || cases.CreateBy == SecurityContext.CurrentAccount.ID || !CRMSecurity.IsPrivate(cases) || GetAccessSubjectTo(cases).ContainsKey(SecurityContext.CurrentAccount.ID)); } public static bool CanEdit(Invoice invoice) { return (IsAdmin || invoice.CreateBy == SecurityContext.CurrentAccount.ID) && invoice.Status == InvoiceStatus.Draft; } public static bool CanEdit(InvoiceTax invoiceTax) { return IsAdmin; } public static bool CanEdit(InvoiceItem invoiceItem) { return IsAdmin; } #endregion #region CanDelete public static bool CanDelete(Contact contact) { using (var scope = DIHelper.Resolve()) { return CanEdit(contact) && scope.Resolve<DaoFactory>().ContactDao.CanDelete(contact.ID); } } public static bool CanDelete(Invoice invoice) { return (IsAdmin || invoice.CreateBy == SecurityContext.CurrentAccount.ID); } public static bool CanDelete(InvoiceItem invoiceItem) { using (var scope = DIHelper.Resolve()) { return CanEdit(invoiceItem) && scope.Resolve<DaoFactory>().InvoiceItemDao.CanDelete(invoiceItem.ID); } } public static bool CanDelete(InvoiceTax invoiceTax) { using (var scope = DIHelper.Resolve()) { return CanEdit(invoiceTax) && scope.Resolve<DaoFactory>().InvoiceTaxDao.CanDelete(invoiceTax.ID); } } public static bool CanDelete(Deal deal) { return CanEdit(deal); } public static bool CanDelete(Cases cases) { return CanEdit(cases); } public static bool CanDelete(RelationshipEvent relationshipEvent) { return CanEdit(relationshipEvent); } #endregion #region IsPrivate public static bool IsPrivate(Contact contact) { return contact.ShareType == ShareType.None; } #endregion #region DemandAccessTo public static void DemandAccessTo(File file) { // if (!CanAccessTo((File)file)) CreateSecurityException(); } public static void DemandAccessTo(Deal deal) { if (!CanAccessTo(deal)) throw CreateSecurityException(); } public static void DemandAccessTo(RelationshipEvent relationshipEvent) { if (!CanAccessTo(relationshipEvent)) throw CreateSecurityException(); } public static void DemandAccessTo(Contact contact) { if (!CanAccessTo(contact)) throw CreateSecurityException(); } public static void DemandAccessTo(Task task) { if (!CanAccessTo(task)) throw CreateSecurityException(); } public static void DemandAccessTo(Cases cases) { if (!CanAccessTo(cases)) throw CreateSecurityException(); } public static void DemandAccessTo(Invoice invoice) { if (!CanAccessTo(invoice)) throw CreateSecurityException(); } public static void DemandAccessTo(InvoiceTax invoiceTax) { if (!CanAccessTo(invoiceTax)) throw CreateSecurityException(); } #endregion #region DemandEdit public static void DemandEdit(File file) { if (!CanEdit(file)) throw CreateSecurityException(); } public static void DemandEdit(Deal deal) { if (!CanEdit(deal)) throw CreateSecurityException(); } public static void DemandEdit(RelationshipEvent relationshipEvent) { if (!CanEdit(relationshipEvent)) throw CreateSecurityException(); } public static void DemandEdit(Contact contact) { if (!CanEdit(contact)) throw CreateSecurityException(); } public static void DemandEdit(Task task) { if (!CanEdit(task)) throw CreateSecurityException(); } public static void DemandEdit(Cases cases) { if (!CanEdit(cases)) throw CreateSecurityException(); } public static void DemandEdit(Invoice invoice) { if (!CanEdit(invoice)) throw CreateSecurityException(); } public static void DemandEdit(InvoiceTax invoiceTax) { if (!CanEdit(invoiceTax)) throw CreateSecurityException(); } public static void DemandEdit(InvoiceItem invoiceItem) { if (!CanEdit(invoiceItem)) throw CreateSecurityException(); } #endregion #region DemandDelete public static void DemandDelete(File file) { if (!CanEdit(file)) throw CreateSecurityException(); } public static void DemandDelete(Contact contact) { if (!CanDelete(contact)) throw CreateSecurityException(); } public static void DemandDelete(Invoice invoice) { if (!CanDelete(invoice)) throw CreateSecurityException(); } public static void DemandDelete(Deal deal) { if (!CanDelete(deal)) throw CreateSecurityException(); } public static void DemandDelete(Cases cases) { if (!CanDelete(cases)) throw CreateSecurityException(); } public static void DemandDelete(InvoiceItem invoiceItem) { if (!CanDelete(invoiceItem)) throw CreateSecurityException(); } public static void DemandDelete(InvoiceTax invoiceTax) { if (!CanDelete(invoiceTax)) throw CreateSecurityException(); } public static void DemandDelete(RelationshipEvent relationshipEvent) { if (!CanDelete(relationshipEvent)) throw CreateSecurityException(); } #endregion #region DemandCreateOrUpdate public static void DemandCreateOrUpdate(RelationshipEvent relationshipEvent) { if (String.IsNullOrEmpty(relationshipEvent.Content) || relationshipEvent.CategoryID == 0 || (relationshipEvent.ContactID == 0 && relationshipEvent.EntityID == 0)) throw new ArgumentException(); if (relationshipEvent.EntityID > 0 && relationshipEvent.EntityType != EntityType.Opportunity && relationshipEvent.EntityType != EntityType.Case) throw new ArgumentException(); if (relationshipEvent.Content.Length > Global.MaxHistoryEventCharacters) throw new ArgumentException(CRMErrorsResource.HistoryEventDataTooLong); if (!CanAccessTo(relationshipEvent)) throw CreateSecurityException(); } public static void DemandCreateOrUpdate(Deal deal) { if (string.IsNullOrEmpty(deal.Title) || deal.ResponsibleID == Guid.Empty || deal.DealMilestoneID <= 0 || string.IsNullOrEmpty(deal.BidCurrency)) throw new ArgumentException(); using (var scope = DIHelper.Resolve()) { var daoFactory = scope.Resolve<DaoFactory>(); var listItem = daoFactory.DealMilestoneDao.GetByID(deal.DealMilestoneID); if (listItem == null) throw new ArgumentException(CRMErrorsResource.DealMilestoneNotFound); if (deal.ContactID != 0) { var contact = daoFactory.ContactDao.GetByID(deal.ContactID); if (contact == null) throw new ArgumentException(); if (!CanAccessTo(contact)) throw new SecurityException(CRMErrorsResource.AccessDenied); } } if (string.IsNullOrEmpty(deal.BidCurrency)) { throw new ArgumentException(); } else { if (CurrencyProvider.Get(deal.BidCurrency.ToUpper()) == null) { throw new ArgumentException(); } } } public static void DemandCreateOrUpdate(InvoiceLine line, Invoice targetInvoice) { if (line.InvoiceID <= 0 || line.InvoiceItemID <= 0 || line.Quantity < 0 || line.Price < 0 || line.Discount < 0 || line.Discount > 100 || line.InvoiceTax1ID < 0 || line.InvoiceTax2ID < 0) throw new ArgumentException(); if (targetInvoice == null || targetInvoice.ID != line.InvoiceID) throw new ArgumentException(); if (!CRMSecurity.CanEdit(targetInvoice)) throw CRMSecurity.CreateSecurityException(); using (var scope = DIHelper.Resolve()) { var daoFactory = scope.Resolve<DaoFactory>(); if (!daoFactory.InvoiceItemDao.IsExist(line.InvoiceItemID)) throw new ArgumentException(); if (line.InvoiceTax1ID > 0 && !daoFactory.InvoiceTaxDao.IsExist(line.InvoiceTax1ID)) throw new ArgumentException(); if (line.InvoiceTax2ID > 0 && !daoFactory.InvoiceTaxDao.IsExist(line.InvoiceTax2ID)) throw new ArgumentException(); } } public static void DemandCreateOrUpdate(Invoice invoice) { if (invoice.IssueDate == DateTime.MinValue || invoice.ContactID <= 0 || invoice.DueDate == DateTime.MinValue || String.IsNullOrEmpty(invoice.Currency) || invoice.ExchangeRate <= 0 || String.IsNullOrEmpty(invoice.Terms)) throw new ArgumentException(); using (var scope = DIHelper.Resolve()) { var daoFactory = scope.Resolve<DaoFactory>(); var contact = daoFactory.ContactDao.GetByID(invoice.ContactID); if (contact == null) throw new ArgumentException(); if (!CanAccessTo(contact)) throw new SecurityException(CRMErrorsResource.AccessDenied); if (invoice.ConsigneeID != 0 && invoice.ConsigneeID != invoice.ContactID) { var consignee = daoFactory.ContactDao.GetByID(invoice.ConsigneeID); if (consignee == null) throw new ArgumentException(); if (!CanAccessTo(consignee)) throw new SecurityException(CRMErrorsResource.AccessDenied); } if (invoice.EntityID != 0) { var deal = daoFactory.DealDao.GetByID(invoice.EntityID); if (deal == null) throw new ArgumentException(); if (!CanAccessTo(deal)) throw new SecurityException(CRMErrorsResource.AccessDenied); var dealMembers = daoFactory.DealDao.GetMembers(invoice.EntityID); if (!dealMembers.Contains(invoice.ContactID)) throw new ArgumentException(); } } if (CurrencyProvider.Get(invoice.Currency.ToUpper()) == null) { throw new ArgumentException(); } } #endregion public static Exception CreateSecurityException() { throw new SecurityException(CRMErrorsResource.AccessDenied); } public static bool IsAdmin { get { return IsAdministrator(SecurityContext.CurrentAccount.ID); } } public static bool IsAdministrator(Guid userId) { return WebItemSecurity.IsProductAdministrator(ProductEntryPoint.ID, userId); } public static bool IsAvailableForUser(Guid userId) { return WebItemSecurity.IsAvailableForUser(WebItemManager.CRMProductID, userId); } public static IEnumerable<Task> FilterRead(IEnumerable<Task> tasks) { if (tasks == null || !tasks.Any()) return new List<Task>(); if (IsAdmin) return tasks; var result = tasks.ToList(); var contactIDs = result .Where(x => x.ResponsibleID != SecurityContext.CurrentAccount.ID) .Select(x => x.ContactID) .Distinct() .ToList(); using (var scope = DIHelper.Resolve()) { var daoFactory = scope.Resolve<DaoFactory>(); if (contactIDs.Any()) { contactIDs = daoFactory.ContactDao .GetContacts(contactIDs.ToArray()) .Select(x => x.ID) .ToList(); result = result.Where(x => x.ContactID == 0 || contactIDs.Contains(x.ContactID) || x.ResponsibleID == SecurityContext.CurrentAccount.ID).ToList(); if (!result.Any()) return Enumerable.Empty<Task>(); } var casesIds = result.Where(x => x.EntityType == EntityType.Case && x.ResponsibleID != SecurityContext.CurrentAccount.ID) .Select(x => x.EntityID) .Distinct() .ToList(); if (casesIds.Any()) { casesIds = daoFactory.CasesDao .GetCases(casesIds.ToArray()) .Select(x => x.ID) .ToList(); result = result.Where(x => x.EntityID == 0 || casesIds.Contains(x.EntityID) || x.ResponsibleID == SecurityContext.CurrentAccount.ID).ToList(); if (!result.Any()) return Enumerable.Empty<Task>(); } var dealsIds = result.Where(x => x.EntityType == EntityType.Opportunity && x.ResponsibleID != SecurityContext.CurrentAccount.ID) .Select(x => x.EntityID) .Distinct() .ToList(); if (dealsIds.Any()) { dealsIds = daoFactory.DealDao .GetDeals(dealsIds.ToArray()) .Select(x => x.ID) .ToList(); result = result .Where(x => x.EntityID == 0 || dealsIds.Contains(x.EntityID) || x.ResponsibleID == SecurityContext.CurrentAccount.ID) .ToList(); if (!result.Any()) return Enumerable.Empty<Task>(); } return result; } } public static IEnumerable<Invoice> FilterRead(IEnumerable<Invoice> invoices) { if (invoices == null || !invoices.Any()) return new List<Invoice>(); if (IsAdmin) return invoices; var result = invoices.ToList(); var contactIDs = result.Select(x => x.ContactID).Distinct().ToList(); using (var scope = DIHelper.Resolve()) { var daoFactory = scope.Resolve<DaoFactory>(); if (contactIDs.Any()) { contactIDs = daoFactory.ContactDao .GetContacts(contactIDs.ToArray()) .Select(x => x.ID) .ToList(); result = result.Where(x => x.ContactID == 0 || contactIDs.Contains(x.ContactID)).ToList(); if (!result.Any()) return Enumerable.Empty<Invoice>(); } } return result; } public static bool CanGoToFeed(Task task) { return IsAdmin || task.ResponsibleID == SecurityContext.CurrentAccount.ID || task.CreateBy == SecurityContext.CurrentAccount.ID; } } }
// 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 Xunit.Abstractions; using System; using System.IO; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using XmlCoreTest.Common; namespace System.Xml.Tests { public class CSameInstanceXsltArgTestCase2 : XsltApiTestCaseBase2 { // Variables from init string protected string _strPath; // Path of the data files // Other global variables public XsltArgumentList xsltArg1; // Shared XsltArgumentList for same instance testing private ITestOutputHelper _output; public CSameInstanceXsltArgTestCase2(ITestOutputHelper output) : base(output) { _output = output; Init(null); } public /*override*/ new void Init(object objParam) { // Get parameter info _strPath = Path.Combine(@"TestFiles\", FilePathUtil.GetTestDataPath(), @"XsltApiV2\"); xsltArg1 = new XsltArgumentList(); MyObject obj1 = new MyObject(1, _output); MyObject obj2 = new MyObject(2, _output); MyObject obj3 = new MyObject(3, _output); MyObject obj4 = new MyObject(4, _output); MyObject obj5 = new MyObject(5, _output); xsltArg1.AddExtensionObject("urn:my-obj1", obj1); xsltArg1.AddExtensionObject("urn:my-obj2", obj2); xsltArg1.AddExtensionObject("urn:my-obj3", obj3); xsltArg1.AddExtensionObject("urn:my-obj4", obj4); xsltArg1.AddExtensionObject("urn:my-obj5", obj5); xsltArg1.AddParam("myArg1", szEmpty, "Test1"); xsltArg1.AddParam("myArg2", szEmpty, "Test2"); xsltArg1.AddParam("myArg3", szEmpty, "Test3"); xsltArg1.AddParam("myArg4", szEmpty, "Test4"); xsltArg1.AddParam("myArg5", szEmpty, "Test5"); return; } } //[TestCase(Name = "Same instance testing: XsltArgList - GetParam", Desc = "GetParam test cases")] public class CSameInstanceXsltArgumentListGetParam : CSameInstanceXsltArgTestCase2 { private ITestOutputHelper _output; public CSameInstanceXsltArgumentListGetParam(ITestOutputHelper output) : base(output) { _output = output; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple GetParam() over same ArgumentList //////////////////////////////////////////////////////////////// public int GetParam1(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetParam(((object[])args)[1].ToString(), szEmpty); _output.WriteLine("GetParam: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tAdded Value: {0}\tRetrieved Value:{1}\n", "Test1", retObj.ToString()); if (retObj.ToString() != "Test1") { _output.WriteLine("ERROR!!!"); return 0; } } return 1; } public int GetParam2(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetParam(((object[])args)[1].ToString(), szEmpty); string expected = "Test" + ((object[])args)[0]; _output.WriteLine("GetParam: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tAdded Value: {0}\tRetrieved Value:{1}\n", expected, retObj.ToString()); if (retObj.ToString() != expected) { _output.WriteLine("ERROR!!!"); return 0; } } return 1; } //[Variation("Multiple GetParam for same parameter name")] [InlineData()] [Theory] public void proc1() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 1, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 2, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 3, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 4, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 5, "myArg1" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple GetParam for different parameter name")] [InlineData()] [Theory] public void proc2() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 1, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 2, "myArg2" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 3, "myArg3" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 4, "myArg4" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 5, "myArg5" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } } //[TestCase(Name = "Same instance testing: XsltArgList - GetExtensionObject", Desc = "GetExtensionObject test cases")] public class CSameInstanceXsltArgumentListGetExtnObject : CSameInstanceXsltArgTestCase2 { private ITestOutputHelper _output; public CSameInstanceXsltArgumentListGetExtnObject(ITestOutputHelper output) : base(output) { _output = output; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple GetExtensionObject() over same ArgumentList //////////////////////////////////////////////////////////////// public int GetExtnObject1(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetExtensionObject(((object[])args)[1].ToString()); _output.WriteLine("GetExtensionObject: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tValue returned: " + ((MyObject)retObj).MyValue()); if (((MyObject)retObj).MyValue() != 1) { _output.WriteLine("ERROR!!! Set and retrieved value appear to be different"); return 0; } } return 1; } public int GetExtnObject2(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetExtensionObject(((object[])args)[1].ToString()); _output.WriteLine("GetExtensionObject: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tValue returned: " + ((MyObject)retObj).MyValue()); if (((MyObject)retObj).MyValue() != (int)((object[])args)[0]) { _output.WriteLine("ERROR!!! Set and retrieved value appear to be different"); return 0; } } return 1; } //[Variation("Multiple GetExtensionObject for same namespace System.Xml.Tests")] [InlineData()] [Theory] public void proc1() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 1, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 2, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 3, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 4, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 5, "urn:my-obj1" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple GetExtensionObject for different namespace System.Xml.Tests")] [InlineData()] [Theory] public void proc2() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 1, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 2, "urn:my-obj2" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 3, "urn:my-obj3" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 4, "urn:my-obj4" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 5, "urn:my-obj5" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } } //[TestCase(Name = "Same instance testing: XsltArgList - Transform", Desc = "Multiple transforms")] public class CSameInstanceXsltArgumentListTransform : CSameInstanceXsltArgTestCase2 { private ITestOutputHelper _output; public CSameInstanceXsltArgumentListTransform(ITestOutputHelper output) : base(output) { _output = output; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple Transform() using shared ArgumentList //////////////////////////////////////////////////////////////// public int SharedArgList(object args) { string _strXslFile = ((object[])args)[1].ToString(); string _strXmlFile = ((object[])args)[2].ToString(); if (_strXslFile.Substring(0, 5) != "http:") _strXslFile = _strPath + _strXslFile; if (_strXmlFile.Substring(0, 5) != "http:") _strXmlFile = _strPath + _strXmlFile; XmlReader xrData = XmlReader.Create(_strXmlFile); XPathDocument xd = new XPathDocument(xrData, XmlSpace.Preserve); xrData.Dispose(); XslCompiledTransform xslt = new XslCompiledTransform(); XmlReaderSettings xrs = new XmlReaderSettings(); #pragma warning disable 0618 xrs.ProhibitDtd = false; #pragma warning restore 0618 XmlReader xrTemp = XmlReader.Create(_strXslFile); xslt.Load(xrTemp); StringWriter sw = new StringWriter(); for (int i = 1; i <= 100; i++) { xslt.Transform(xd, xsltArg1, sw); _output.WriteLine("SharedArgumentList: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tDone with transform..."); } return 1; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple Transform() using shared ArgumentList //////////////////////////////////////////////////////////////// //[Variation("Multiple transforms using shared ArgumentList")] [InlineData()] [Theory] public void proc1() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 1, "xsltarg_multithreading1.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 2, "xsltarg_multithreading2.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 3, "xsltarg_multithreading3.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 4, "xsltarg_multithreading4.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 5, "xsltarg_multithreading5.xsl", "foo.xml" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; using System.Security; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: This is the implementation of the DataCollector /// functionality. To enable safe access to the DataCollector from /// untrusted code, there is one thread-local instance of this structure /// per thread. The instance must be Enabled before any data is written to /// it. The instance must be Finished before the data is passed to /// EventWrite. The instance must be Disabled before the arrays referenced /// by the pointers are freed or unpinned. /// </summary> [SecurityCritical] internal unsafe struct DataCollector { [ThreadStatic] internal static DataCollector ThreadInstance; private byte* scratchEnd; private EventSource.EventData* datasEnd; private GCHandle* pinsEnd; private EventSource.EventData* datasStart; private byte* scratch; private EventSource.EventData* datas; private GCHandle* pins; private byte[] buffer; private int bufferPos; private int bufferNesting; // We may merge many fields int a single blob. If we are doing this we increment this. private bool writingScalars; internal void Enable( byte* scratch, int scratchSize, EventSource.EventData* datas, int dataCount, GCHandle* pins, int pinCount) { this.datasStart = datas; this.scratchEnd = scratch + scratchSize; this.datasEnd = datas + dataCount; this.pinsEnd = pins + pinCount; this.scratch = scratch; this.datas = datas; this.pins = pins; this.writingScalars = false; } internal void Disable() { this = new DataCollector(); } /// <summary> /// Completes the list of scalars. Finish must be called before the data /// descriptor array is passed to EventWrite. /// </summary> /// <returns> /// A pointer to the next unused data descriptor, or datasEnd if they were /// all used. (Descriptors may be unused if a string or array was null.) /// </returns> internal EventSource.EventData* Finish() { this.ScalarsEnd(); return this.datas; } internal void AddScalar(void* value, int size) { var pb = (byte*)value; if (this.bufferNesting == 0) { var scratchOld = this.scratch; var scratchNew = scratchOld + size; if (this.scratchEnd < scratchNew) { throw new IndexOutOfRangeException(Environment.GetResourceString("EventSource_AddScalarOutOfRange")); } this.ScalarsBegin(); this.scratch = scratchNew; for (int i = 0; i != size; i++) { scratchOld[i] = pb[i]; } } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); for (int i = 0; i != size; i++, oldPos++) { this.buffer[oldPos] = pb[i]; } } } internal void AddBinary(string value, int size) { if (size > ushort.MaxValue) { size = ushort.MaxValue - 1; } if (this.bufferNesting != 0) { this.EnsureBuffer(size + 2); } this.AddScalar(&size, 2); if (size != 0) { if (this.bufferNesting == 0) { this.ScalarsEnd(); this.PinArray(value, size); } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); fixed (void* p = value) { Marshal.Copy((IntPtr)p, this.buffer, oldPos, size); } } } } internal void AddBinary(Array value, int size) { this.AddArray(value, size, 1); } internal void AddArray(Array value, int length, int itemSize) { if (length > ushort.MaxValue) { length = ushort.MaxValue; } var size = length * itemSize; if (this.bufferNesting != 0) { this.EnsureBuffer(size + 2); } this.AddScalar(&length, 2); if (length != 0) { if (this.bufferNesting == 0) { this.ScalarsEnd(); this.PinArray(value, size); } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); Buffer.BlockCopy(value, 0, this.buffer, oldPos, size); } } } /// <summary> /// Marks the start of a non-blittable array or enumerable. /// </summary> /// <returns>Bookmark to be passed to EndBufferedArray.</returns> internal int BeginBufferedArray() { this.BeginBuffered(); this.bufferPos += 2; // Reserve space for the array length (filled in by EndEnumerable) return this.bufferPos; } /// <summary> /// Marks the end of a non-blittable array or enumerable. /// </summary> /// <param name="bookmark">The value returned by BeginBufferedArray.</param> /// <param name="count">The number of items in the array.</param> internal void EndBufferedArray(int bookmark, int count) { this.EnsureBuffer(); this.buffer[bookmark - 2] = unchecked((byte)count); this.buffer[bookmark - 1] = unchecked((byte)(count >> 8)); this.EndBuffered(); } /// <summary> /// Marks the start of dynamically-buffered data. /// </summary> internal void BeginBuffered() { this.ScalarsEnd(); this.bufferNesting += 1; } /// <summary> /// Marks the end of dynamically-buffered data. /// </summary> internal void EndBuffered() { this.bufferNesting -= 1; if (this.bufferNesting == 0) { this.EnsureBuffer(); this.PinArray(this.buffer, this.bufferPos); this.buffer = null; this.bufferPos = 0; } } private void EnsureBuffer() { var required = this.bufferPos; if (this.buffer == null || this.buffer.Length < required) { this.GrowBuffer(required); } } private void EnsureBuffer(int additionalSize) { var required = this.bufferPos + additionalSize; if (this.buffer == null || this.buffer.Length < required) { this.GrowBuffer(required); } } private void GrowBuffer(int required) { var newSize = this.buffer == null ? 64 : this.buffer.Length; do { newSize *= 2; } while (newSize < required); Array.Resize(ref this.buffer, newSize); } private void PinArray(object value, int size) { var pinsTemp = this.pins; if (this.pinsEnd <= pinsTemp) { throw new IndexOutOfRangeException(Environment.GetResourceString("EventSource_PinArrayOutOfRange")); } var datasTemp = this.datas; if (this.datasEnd <= datasTemp) { throw new IndexOutOfRangeException(Environment.GetResourceString("EventSource_DataDescriptorsOutOfRange")); } this.pins = pinsTemp + 1; this.datas = datasTemp + 1; *pinsTemp = GCHandle.Alloc(value, GCHandleType.Pinned); datasTemp->m_Ptr = (long)(ulong)(UIntPtr)(void*)pinsTemp->AddrOfPinnedObject(); datasTemp->m_Size = size; } private void ScalarsBegin() { if (!this.writingScalars) { var datasTemp = this.datas; if (this.datasEnd <= datasTemp) { throw new IndexOutOfRangeException(Environment.GetResourceString("EventSource_DataDescriptorsOutOfRange")); } datasTemp->m_Ptr = (long)(ulong)(UIntPtr)this.scratch; this.writingScalars = true; } } private void ScalarsEnd() { if (this.writingScalars) { var datasTemp = this.datas; datasTemp->m_Size = checked((int)(this.scratch - (byte*)datasTemp->m_Ptr)); this.datas = datasTemp + 1; this.writingScalars = false; } } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Runtime.InteropServices; namespace ListViewEx { /// <summary> /// Event Handler for SubItem events /// </summary> public delegate void SubItemEventHandler(object sender, SubItemEventArgs e); /// <summary> /// Event Handler for SubItemEndEditing events /// </summary> public delegate void SubItemEndEditingEventHandler(object sender, SubItemEndEditingEventArgs e); /// <summary> /// Event Args for SubItemClicked event /// </summary> public class SubItemEventArgs : EventArgs { public SubItemEventArgs(ListViewItem item, int subItem) { _subItemIndex = subItem; _item = item; } private int _subItemIndex = -1; private ListViewItem _item = null; public int SubItem { get { return _subItemIndex; } } public ListViewItem Item { get { return _item; } } } /// <summary> /// Event Args for SubItemEndEditingClicked event /// </summary> public class SubItemEndEditingEventArgs : SubItemEventArgs { private string _text = string.Empty; private bool _cancel = true; public SubItemEndEditingEventArgs(ListViewItem item, int subItem, string display, bool cancel) : base(item, subItem) { _text = display; _cancel = cancel; } public string DisplayText { get { return _text; } set { _text = value; } } public bool Cancel { get { return _cancel; } set { _cancel = value; } } } /// <summary> /// Inherited ListView to allow in-place editing of subitems /// </summary> public class ListViewEx : System.Windows.Forms.ListView { #region Interop structs, imports and constants /// <summary> /// MessageHeader for WM_NOTIFY /// </summary> private struct NMHDR { public IntPtr hwndFrom; public Int32 idFrom; public Int32 code; } [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wPar, IntPtr lPar); [DllImport("user32.dll", CharSet=CharSet.Ansi)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, int len, ref int [] order); // ListView messages private const int LVM_FIRST = 0x1000; private const int LVM_GETCOLUMNORDERARRAY = (LVM_FIRST + 59); // Windows Messages that will abort editing private const int WM_HSCROLL = 0x114; private const int WM_VSCROLL = 0x115; private const int WM_SIZE = 0x05; private const int WM_NOTIFY = 0x4E; private const int HDN_FIRST = -300; private const int HDN_BEGINDRAG = (HDN_FIRST-10); private const int HDN_ITEMCHANGINGA = (HDN_FIRST-0); private const int HDN_ITEMCHANGINGW = (HDN_FIRST-20); #endregion /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public event SubItemEventHandler SubItemClicked; public event SubItemEventHandler SubItemBeginEditing; public event SubItemEndEditingEventHandler SubItemEndEditing; public ListViewEx() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); base.FullRowSelect = true; base.View = View.Details; base.AllowColumnReorder = true; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if( components != null ) components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion private bool _doubleClickActivation = false; /// <summary> /// Is a double click required to start editing a cell? /// </summary> public bool DoubleClickActivation { get { return _doubleClickActivation; } set { _doubleClickActivation = value; } } /// <summary> /// Retrieve the order in which columns appear /// </summary> /// <returns>Current display order of column indices</returns> public int[] GetColumnOrder() { IntPtr lPar = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Columns.Count); IntPtr res = SendMessage(Handle, LVM_GETCOLUMNORDERARRAY, new IntPtr(Columns.Count), lPar); if (res.ToInt32() == 0) // Something went wrong { Marshal.FreeHGlobal(lPar); return null; } int [] order = new int[Columns.Count]; Marshal.Copy(lPar, order, 0, Columns.Count); Marshal.FreeHGlobal(lPar); return order; } /// <summary> /// Find ListViewItem and SubItem Index at position (x,y) /// </summary> /// <param name="x">relative to ListView</param> /// <param name="y">relative to ListView</param> /// <param name="item">Item at position (x,y)</param> /// <returns>SubItem index</returns> public int GetSubItemAt(int x, int y, out ListViewItem item) { item = this.GetItemAt(x, y); if (item != null) { int[] order = GetColumnOrder(); Rectangle lviBounds; int subItemX; lviBounds = item.GetBounds(ItemBoundsPortion.Entire); subItemX = lviBounds.Left; for (int i=0; i<order.Length; i++) { ColumnHeader h = this.Columns[order[i]]; if (x < subItemX+h.Width) { return h.Index; } subItemX += h.Width; } } return -1; } /// <summary> /// Get bounds for a SubItem /// </summary> /// <param name="Item">Target ListViewItem</param> /// <param name="SubItem">Target SubItem index</param> /// <returns>Bounds of SubItem (relative to ListView)</returns> public Rectangle GetSubItemBounds(ListViewItem Item, int SubItem) { int[] order = GetColumnOrder(); Rectangle subItemRect = Rectangle.Empty; if (SubItem >= order.Length) throw new IndexOutOfRangeException("SubItem "+SubItem+" out of range"); if (Item == null) throw new ArgumentNullException("Item"); Rectangle lviBounds = Item.GetBounds(ItemBoundsPortion.Entire); int subItemX = lviBounds.Left; ColumnHeader col; int i; for (i=0; i<order.Length; i++) { col = this.Columns[order[i]]; if (col.Index == SubItem) break; subItemX += col.Width; } subItemRect = new Rectangle(subItemX, lviBounds.Top, this.Columns[order[i]].Width, lviBounds.Height); return subItemRect; } protected override void WndProc(ref Message msg) { switch (msg.Msg) { // Look for WM_VSCROLL,WM_HSCROLL or WM_SIZE messages. case WM_VSCROLL: case WM_HSCROLL: case WM_SIZE: EndEditing(false); break; case WM_NOTIFY: // Look for WM_NOTIFY of events that might also change the // editor's position/size: Column reordering or resizing NMHDR h = (NMHDR)Marshal.PtrToStructure(msg.LParam, typeof(NMHDR)); if (h.code == HDN_BEGINDRAG || h.code == HDN_ITEMCHANGINGA || h.code == HDN_ITEMCHANGINGW) EndEditing(false); break; } base.WndProc(ref msg); } #region Initialize editing depending of DoubleClickActivation property protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e) { base.OnMouseUp(e); if (DoubleClickActivation) { return; } EditSubitemAt(new Point(e.X, e.Y)); } protected override void OnDoubleClick(EventArgs e) { base.OnDoubleClick (e); if (!DoubleClickActivation) { return; } Point pt = this.PointToClient(Cursor.Position); EditSubitemAt(pt); } ///<summary> /// Fire SubItemClicked ///</summary> ///<param name="p">Point of click/doubleclick</param> private void EditSubitemAt(Point p) { ListViewItem item; int idx = GetSubItemAt(p.X, p.Y, out item); if (idx >= 0) { OnSubItemClicked(new SubItemEventArgs(item, idx)); } } #endregion #region In-place editing functions // The control performing the actual editing private Control _editingControl; // The LVI being edited private ListViewItem _editItem; // The SubItem being edited private int _editSubItem; protected void OnSubItemBeginEditing(SubItemEventArgs e) { if (SubItemBeginEditing != null) SubItemBeginEditing(this, e); } protected void OnSubItemEndEditing(SubItemEndEditingEventArgs e) { if (SubItemEndEditing != null) SubItemEndEditing(this, e); } protected void OnSubItemClicked(SubItemEventArgs e) { if (SubItemClicked != null) SubItemClicked(this, e); } /// <summary> /// Begin in-place editing of given cell /// </summary> /// <param name="c">Control used as cell editor</param> /// <param name="Item">ListViewItem to edit</param> /// <param name="SubItem">SubItem index to edit</param> public void StartEditing(Control c, ListViewItem Item, int SubItem) { OnSubItemBeginEditing(new SubItemEventArgs(Item, SubItem)); Rectangle rcSubItem = GetSubItemBounds(Item, SubItem); if (rcSubItem.X < 0) { // Left edge of SubItem not visible - adjust rectangle position and width rcSubItem.Width += rcSubItem.X; rcSubItem.X=0; } if (rcSubItem.X+rcSubItem.Width > this.Width) { // Right edge of SubItem not visible - adjust rectangle width rcSubItem.Width = this.Width-rcSubItem.Left; } // Subitem bounds are relative to the location of the ListView! rcSubItem.Offset(Left, Top); // In case the editing control and the listview are on different parents, // account for different origins Point origin = new Point(0,0); Point lvOrigin = this.Parent.PointToScreen(origin); Point ctlOrigin = c.Parent.PointToScreen(origin); rcSubItem.Offset(lvOrigin.X-ctlOrigin.X, lvOrigin.Y-ctlOrigin.Y); // Position and show editor c.Bounds = rcSubItem; c.Text = Item.SubItems[SubItem].Text; c.Visible = true; c.BringToFront(); c.Focus(); _editingControl = c; _editingControl.Leave += new EventHandler(_editControl_Leave); _editingControl.KeyPress += new KeyPressEventHandler(_editControl_KeyPress); _editItem = Item; _editSubItem = SubItem; } private void _editControl_Leave(object sender, EventArgs e) { // cell editor losing focus EndEditing(true); } private void _editControl_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { switch (e.KeyChar) { case (char)(int)Keys.Escape: { EndEditing(false); break; } case (char)(int)Keys.Enter: { EndEditing(true); break; } } } /// <summary> /// Accept or discard current value of cell editor control /// </summary> /// <param name="AcceptChanges">Use the _editingControl's Text as new SubItem text or discard changes?</param> public void EndEditing(bool AcceptChanges) { if (_editingControl == null) return; SubItemEndEditingEventArgs e = new SubItemEndEditingEventArgs( _editItem, // The item being edited _editSubItem, // The subitem index being edited AcceptChanges ? _editingControl.Text : // Use editControl text if changes are accepted _editItem.SubItems[_editSubItem].Text, // or the original subitem's text, if changes are discarded !AcceptChanges // Cancel? ); OnSubItemEndEditing(e); _editItem.SubItems[_editSubItem].Text = e.DisplayText; _editingControl.Leave -= new EventHandler(_editControl_Leave); _editingControl.KeyPress -= new KeyPressEventHandler(_editControl_KeyPress); _editingControl.Visible = false; _editingControl = null; _editItem = null; _editSubItem = -1; } #endregion } }
// // 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.Generic; using System.Linq; using System.Threading.Tasks; using Cassandra.Data.Linq; using Cassandra.IntegrationTests.Linq.Structures; using Cassandra.IntegrationTests.TestBase; using Cassandra.Mapping; using Cassandra.Tests; using Cassandra.Tests.Mapping.Pocos; using NUnit.Framework; namespace Cassandra.IntegrationTests.Linq { /// <summary> /// No support for paging state and traces in simulacron yet. Also haven't implemented an abstraction to prime UDTs yet. /// </summary> [Category(TestCategory.Short), Category(TestCategory.RealCluster)] public class LinqRealClusterTests : SharedClusterTest { private ISession _session; private readonly string _tableName = TestUtils.GetUniqueTableName().ToLower(); private readonly string _tableNameAlbum = TestUtils.GetUniqueTableName().ToLower(); private readonly MappingConfiguration _mappingConfig = new MappingConfiguration().Define(new Map<Song>().PartitionKey(s => s.Id)); private Table<Movie> _movieTable; private const int TotalRows = 100; private readonly List<Movie> _movieList = Movie.GetDefaultMovieList(); private readonly string _udtName = $"udt_song_{Randomm.RandomAlphaNum(12)}"; private readonly Guid _sampleId = Guid.NewGuid(); private Table<Song> GetTable() { return new Table<Song>(_session, _mappingConfig, _tableName, KeyspaceName); } public override void OneTimeSetUp() { base.OneTimeSetUp(); _session = Session; var table = GetTable(); table.Create(); var tasks = new List<Task>(); for (var i = 0; i < LinqRealClusterTests.TotalRows; i++) { tasks.Add(table.Insert(new Song { Id = Guid.NewGuid(), Artist = "Artist " + i, Title = "Title " + i, ReleaseDate = DateTimeOffset.Now }).ExecuteAsync()); } Assert.True(Task.WaitAll(tasks.ToArray(), 10000)); var movieMappingConfig = new MappingConfiguration(); _movieTable = new Table<Movie>(_session, movieMappingConfig); _movieTable.Create(); //Insert some data foreach (var movie in _movieList) _movieTable.Insert(movie).Execute(); } [SetUp] public void SetUp() { Session.Execute($"CREATE TYPE IF NOT EXISTS {_udtName} (id uuid, title text, artist text)"); Session.UserDefinedTypes.Define(UdtMap.For<Song2>(_udtName)); Session.Execute($"CREATE TABLE IF NOT EXISTS {_tableNameAlbum} (id uuid primary key, name text, songs list<frozen<{_udtName}>>, publishingdate timestamp)"); } [Test] public void ExecutePaged_Fetches_Only_PageSize() { const int pageSize = 10; var table = GetTable(); var page = table.SetPageSize(pageSize).ExecutePaged(); Assert.AreEqual(pageSize, page.Count); Assert.AreEqual(pageSize, page.Count()); } /// <summary> /// Checks that while retrieving all the following pages it will get the full original list (unique ids). /// </summary> [Test] public async Task ExecutePaged_Fetches_Following_Pages() { const int pageSize = 5; var table = GetTable(); var fullList = new HashSet<Guid>(); var page = await table.SetPageSize(pageSize).ExecutePagedAsync().ConfigureAwait(false); Assert.AreEqual(pageSize, page.Count); foreach (var s in page) { fullList.Add(s.Id); } var safeCounter = 0; while (page.PagingState != null && safeCounter++ < LinqRealClusterTests.TotalRows) { page = table.SetPagingState(page.PagingState).ExecutePaged(); Assert.LessOrEqual(page.Count, pageSize); foreach (var s in page) { fullList.Add(s.Id); } } Assert.AreEqual(LinqRealClusterTests.TotalRows, fullList.Count); } [Test] public void ExecutePaged_Where_Fetches_Only_PageSize() { const int pageSize = 10; var table = GetTable(); var page = table.Where(s => CqlFunction.Token(s.Id) > long.MinValue).SetPageSize(pageSize).ExecutePaged(); Assert.AreEqual(pageSize, page.Count); Assert.AreEqual(pageSize, page.Count()); } [Test] public void ExecutePaged_Where_Fetches_Following_Pages() { const int pageSize = 5; var table = GetTable(); var fullList = new HashSet<Guid>(); var page = table.Where(s => CqlFunction.Token(s.Id) > long.MinValue).SetPageSize(pageSize).ExecutePaged(); Assert.AreEqual(pageSize, page.Count); foreach (var s in page) { fullList.Add(s.Id); } var safeCounter = 0; while (page.PagingState != null && safeCounter++ < LinqRealClusterTests.TotalRows) { page = table.Where(s => CqlFunction.Token(s.Id) > long.MinValue).SetPageSize(pageSize).SetPagingState(page.PagingState).ExecutePaged(); Assert.LessOrEqual(page.Count, pageSize); foreach (var s in page) { fullList.Add(s.Id); } } Assert.AreEqual(LinqRealClusterTests.TotalRows, fullList.Count); } [Test] public void LinqWhere_ExecuteSync_Trace() { var expectedMovie = _movieList.First(); // test var linqWhere = _movieTable.Where(m => m.Title == expectedMovie.Title && m.MovieMaker == expectedMovie.MovieMaker); linqWhere.EnableTracing(); var movies = linqWhere.Execute().ToList(); Assert.AreEqual(1, movies.Count); var actualMovie = movies.First(); Movie.AssertEquals(expectedMovie, actualMovie); var trace = linqWhere.QueryTrace; Assert.NotNull(trace); Assert.AreEqual(TestCluster.InitialContactPoint, trace.Coordinator.ToString()); } [Test, TestCassandraVersion(2, 1)] public void CreateTable_With_Frozen_Udt() { var config = new MappingConfiguration().Define(new Map<UdtAndTuplePoco>() .PartitionKey(p => p.Id1) .Column(p => p.Id1) .Column(p => p.Udt1, cm => cm.WithName("u").AsFrozen()) .TableName("tbl_frozen_udt") .ExplicitColumns()); Session.Execute("CREATE TYPE IF NOT EXISTS song (title text, releasedate timestamp, artist text)"); Session.UserDefinedTypes.Define(UdtMap.For<Song>()); var table = new Table<UdtAndTuplePoco>(Session, config); table.Create(); var tableMeta = Cluster.Metadata.GetTable(KeyspaceName, "tbl_frozen_udt"); Assert.AreEqual(2, tableMeta.TableColumns.Length); var column = tableMeta.ColumnsByName["u"]; Assert.AreEqual(ColumnTypeCode.Udt, column.TypeCode); } [Test, TestCassandraVersion(2, 1)] public void CreateTable_With_Frozen_Key() { var config = new MappingConfiguration().Define(new Map<UdtAndTuplePoco>() .PartitionKey(p => p.Id1) .Column(p => p.Id1) .Column(p => p.UdtSet1, cm => cm.WithFrozenKey().WithName("s")) .Column(p => p.TupleMapKey1, cm => cm.WithFrozenKey().WithName("m")) .TableName("tbl_frozen_key") .ExplicitColumns()); Session.Execute("CREATE TYPE IF NOT EXISTS song (title text, releasedate timestamp, artist text)"); Session.UserDefinedTypes.Define(UdtMap.For<Song>()); var table = new Table<UdtAndTuplePoco>(Session, config); table.Create(); var tableMeta = Cluster.Metadata.GetTable(KeyspaceName, "tbl_frozen_key"); Assert.AreEqual(3, tableMeta.TableColumns.Length); var column = tableMeta.ColumnsByName["s"]; Assert.AreEqual(ColumnTypeCode.Set, column.TypeCode); column = tableMeta.ColumnsByName["m"]; Assert.AreEqual(ColumnTypeCode.Map, column.TypeCode); } [Test, TestCassandraVersion(2, 1)] public void CreateTable_With_Frozen_Value() { var config = new MappingConfiguration().Define(new Map<UdtAndTuplePoco>() .PartitionKey(p => p.Id1) .Column(p => p.Id1) .Column(p => p.ListMapValue1, cm => cm.WithFrozenValue().WithName("m")) .Column(p => p.UdtList1, cm => cm.WithFrozenValue().WithName("l")) .TableName("tbl_frozen_value") .ExplicitColumns()); Session.Execute("CREATE TYPE IF NOT EXISTS song (title text, releasedate timestamp, artist text)"); Session.UserDefinedTypes.Define(UdtMap.For<Song>()); var table = new Table<UdtAndTuplePoco>(Session, config); table.Create(); var tableMeta = Cluster.Metadata.GetTable(KeyspaceName, "tbl_frozen_value"); Assert.AreEqual(3, tableMeta.TableColumns.Length); var column = tableMeta.ColumnsByName["l"]; Assert.AreEqual(ColumnTypeCode.List, column.TypeCode); column = tableMeta.ColumnsByName["m"]; Assert.AreEqual(ColumnTypeCode.Map, column.TypeCode); } [Test, TestCassandraVersion(2, 1, 0)] public void LinqUdt_Select() { // Avoid interfering with other tests Session.Execute( new SimpleStatement( $"INSERT INTO {_tableNameAlbum} (id, name, songs) VALUES (?, 'Legend', [{{id: uuid(), title: 'Africa Unite', artist: 'Bob Marley'}}])", _sampleId)); var table = GetAlbumTable(); var album = table.Select(a => new Album { Id = a.Id, Name = a.Name, Songs = a.Songs }) .Where(a => a.Id == _sampleId).Execute().First(); Assert.AreEqual(_sampleId, album.Id); Assert.AreEqual("Legend", album.Name); Assert.NotNull(album.Songs); Assert.AreEqual(1, album.Songs.Count); var song = album.Songs[0]; Assert.AreEqual("Africa Unite", song.Title); Assert.AreEqual("Bob Marley", song.Artist); } [Test, TestCassandraVersion(2,1,0)] public void LinqUdt_Insert() { // Avoid interfering with other tests var table = GetAlbumTable(); var id = Guid.NewGuid(); var album = new Album { Id = id, Name = "Mothership", PublishingDate = DateTimeOffset.Parse("2010-01-01"), Songs = new List<Song2> { new Song2 { Id = Guid.NewGuid(), Artist = "Led Zeppelin", Title = "Good Times Bad Times" }, new Song2 { Id = Guid.NewGuid(), Artist = "Led Zeppelin", Title = "Communication Breakdown" } } }; table.Insert(album).Execute(); //Check that the values exists using core driver var row = Session.Execute(new SimpleStatement($"SELECT * FROM {_tableNameAlbum} WHERE id = ?", id)).First(); Assert.AreEqual("Mothership", row.GetValue<object>("name")); var songs = row.GetValue<List<Song2>>("songs"); Assert.NotNull(songs); Assert.AreEqual(2, songs.Count); Assert.NotNull(songs.FirstOrDefault(s => s.Title == "Good Times Bad Times")); Assert.NotNull(songs.FirstOrDefault(s => s.Title == "Communication Breakdown")); } [Test, TestCassandraVersion(2,1,0)] public void LinqUdt_Where_Contains() { var songRecordsName = "song_records"; Session.Execute($"CREATE TABLE IF NOT EXISTS {songRecordsName} (id uuid, song frozen<{_udtName}>, broadcast int, primary key ((id), song))"); var table = new Table<SongRecords>(Session, new MappingConfiguration().Define(new Map<SongRecords>().TableName(songRecordsName))); var song = new Song2 { Id = Guid.NewGuid(), Artist = "Led Zeppelin", Title = "Good Times Bad Times" }; var songs = new List<Song2> {song, new Song2 {Id = Guid.NewGuid(), Artist = "Led Zeppelin", Title = "Whola Lotta Love"}}; var id = Guid.NewGuid(); var songRecord = new SongRecords() { Id = id, Song = song, Broadcast = 100 }; table.Insert(songRecord).Execute(); var records = table.Where(sr => sr.Id == id && songs.Contains(sr.Song)).Execute(); Assert.NotNull(records); var recordsArr = records.ToArray(); Assert.AreEqual(1, recordsArr.Length); Assert.NotNull(recordsArr[0].Song); Assert.AreEqual(song.Id, recordsArr[0].Song.Id); Assert.AreEqual(song.Artist, recordsArr[0].Song.Artist); Assert.AreEqual(song.Title, recordsArr[0].Song.Title); } private Table<Album> GetAlbumTable() { return new Table<Album>(Session, new MappingConfiguration().Define(new Map<Album>().TableName(_tableNameAlbum))); } internal class SongRecords { public Guid Id { get; set; } public Song2 Song { get; set; } public int Broadcast { get; set; } } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Foundation; using UIKit; using CoreGraphics; using CoreImage; using ObjCRuntime; using System.Linq; namespace StateRestoration { public partial class DetailViewController : UIViewController, IUIObjectRestoration { const string blurFilterKey = "kBlurFilterKey"; const string modifyFilterKey = "kModifyFilterKey"; const string imageIdentifierKey = "kImageIdentifierKey"; const string dataSourceKey = "kDataSourceKey"; const string barsHiddenKey = "kBarsHiddenKey"; const string imageFiltersKey = "kImageFiltersKey"; const float defaultScale = 1; UIImage image; nfloat lastScale; bool statusBarHidden; Dictionary<string,ImageFilter> filters; UITapGestureRecognizer tapGestureRecognizer; UITapGestureRecognizer doubleTapGestureRecognizer; UIPinchGestureRecognizer pinchGestureRecognizer; public string ImageIdentifier { get; set; } public DataSource DataSource { get; set; } public DetailViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); lastScale = defaultScale; imageView.UserInteractionEnabled = true; } public override bool PrefersStatusBarHidden () { return statusBarHidden; } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); UpdateImage (); TryAddDoubleTapGesture (); TryAddTapGetsture (); TryAddPinchGesture (); SetImageViewConstraints (UIApplication.SharedApplication.StatusBarOrientation); } void TryAddDoubleTapGesture () { if (doubleTapGestureRecognizer != null) return; doubleTapGestureRecognizer = new UITapGestureRecognizer (OnDoubleTapGesture) { NumberOfTapsRequired = 2 }; imageView.AddGestureRecognizer (doubleTapGestureRecognizer); } void TryAddTapGetsture () { if (tapGestureRecognizer != null) return; tapGestureRecognizer = new UITapGestureRecognizer (g => UpdateBars (0.25f)) { NumberOfTapsRequired = 1 }; tapGestureRecognizer.RequireGestureRecognizerToFail (doubleTapGestureRecognizer); imageView.AddGestureRecognizer (tapGestureRecognizer); } void TryAddPinchGesture () { if (pinchGestureRecognizer != null) return; pinchGestureRecognizer = new UIPinchGestureRecognizer (OnPinch); imageView.AddGestureRecognizer (pinchGestureRecognizer); } void OnPinch (UIPinchGestureRecognizer recognizer) { if (recognizer.State == UIGestureRecognizerState.Ended) { lastScale = defaultScale; return; } nfloat scale = recognizer.Scale / lastScale; var newTransform = imageView.Transform; newTransform.Scale (scale, scale); imageView.Transform = newTransform; lastScale = recognizer.Scale; } public override void WillRotate (UIInterfaceOrientation toInterfaceOrientation, double duration) { if (imageView.Transform.IsIdentity) SetImageViewConstraints (toInterfaceOrientation); if (toInterfaceOrientation.IsLandscape () && !statusBarHidden) UpdateBars (); else if (statusBarHidden) UpdateBars (); } public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { base.PrepareForSegue (segue, sender); string filterKey = MapToFilterKey (segue.Identifier); if (filterKey == null) return; var filterViewController = (FilterViewController)segue.DestinationViewController; filterViewController.filter = GetImageFilter (filterKey); } string MapToFilterKey (string segueIdentifier) { switch (segueIdentifier) { case "showBlurInfo": return blurFilterKey; case "showModifyInfo": return modifyFilterKey; default: return null; } } ImageFilter GetImageFilter (string key) { filters = filters ?? new Dictionary<string, ImageFilter> (); ImageFilter filter; if (!filters.TryGetValue (key, out filter)) { filter = CreateFilter (key, true); filters [key] = filter; } return filter; } static ImageFilter CreateFilter (string key, bool useDefault) { ImageFilter filter = CreateFilterFrom (key, useDefault); Register (filter, key); return filter; } static ImageFilter CreateFilterFrom (string key, bool useDefault) { switch (key) { case blurFilterKey: return new BlurFilter (useDefault); case modifyFilterKey: return new ModifyFilter (useDefault); default: throw new NotImplementedException (); } } static void Register (ImageFilter filter, string key) { UIApplication.RegisterObjectForStateRestoration (filter, key); filter.RestorationType = typeof(DetailViewController); } void OnDoubleTapGesture (UITapGestureRecognizer tapGesture) { UIView.Animate (1.0f, () => { if (imageView.Transform.IsIdentity) { imageView.Transform = CreateScaleTransform (imageView.Transform); } else { imageView.Transform = CGAffineTransform.MakeIdentity (); lastScale = defaultScale; SetImageViewConstraints (UIApplication.SharedApplication.StatusBarOrientation); } }); } CGAffineTransform CreateScaleTransform (CGAffineTransform currentTransform) { var flip = UIApplication.SharedApplication.StatusBarOrientation.IsLandscape (); var scale = flip ? 2.0f : 2.5f; currentTransform.Scale (scale, scale); return currentTransform; } void UpdateImage () { try { TryInitializeImage (); } catch (InvalidProgramException ex) { Console.WriteLine (ex); return; } if (filters == null) return; ApplyFilters (); } void TryInitializeImage () { // already initialized if (image != null) return; // we cant init img if (string.IsNullOrEmpty (ImageIdentifier)) throw new InvalidProgramException ("Warning: Called without an ImageIdentifier set"); // initialization Title = DataSource.GetTitle (ImageIdentifier); image = DataSource.GetFullImage (ImageIdentifier); imageView.Image = image; } void ApplyFilters () { var blurFilter = GetFilter<BlurFilter> (blurFilterKey); var modifyFilter = GetFilter<ModifyFilter> (modifyFilterKey); bool dirty = IsAnyDirty (blurFilter, modifyFilter); bool needBlur = blurFilter != null && blurFilter.Active && dirty; bool needModify = modifyFilter != null && modifyFilter.Active && dirty; CIImage filteredCIImage = null; var original = new CIImage (image.CGImage); if (needBlur) filteredCIImage = Apply (original, blurFilter); if (needModify) filteredCIImage = Apply (filteredCIImage ?? original, modifyFilter); if (filteredCIImage != null) imageView.Image = CreateImage (filteredCIImage); else if (dirty) imageView.Image = image; MarkAsNotDirty (blurFilter); MarkAsNotDirty (modifyFilter); } T GetFilter<T> (string key) where T : ImageFilter { ImageFilter f; filters.TryGetValue (key, out f); return (T)f; } bool IsAnyDirty (params ImageFilter[] filters) { return filters.Where (f => f != null).Any (f => f.Dirty); } CIImage Apply (CIImage input, BlurFilter filter) { var f = new CIGaussianBlur () { Image = input, Radius = filter.BlurRadius * 50, }; return f.OutputImage; } CIImage Apply (CIImage input, ModifyFilter filter) { var f = new CISepiaTone () { Image = input, Intensity = filter.Intensity }; return f.OutputImage; } UIImage CreateImage (CIImage img) { CIContext context = CreateContext (); CGImage cgImage = context.CreateCGImage (img, img.Extent); return new UIImage (cgImage); } CIContext CreateContext () { var options = new CIContextOptions { UseSoftwareRenderer = false }; return CIContext.FromOptions (options); } void MarkAsNotDirty (ImageFilter filter) { if (filter != null) filter.Dirty = false; } void UpdateBars (float animationDuration = 0) { bool visible = !toolBar.Hidden; if (visible && NavigationController.TopViewController != this) { Console.WriteLine ("Asked to hide bar, but not the top view controller, skipping update of bars"); return; } bool newHiddenValue = !toolBar.Hidden; AnimateBars (animationDuration, newHiddenValue); } void AnimateBars (float animationDuration, bool hidden) { UIView.Animate (animationDuration, () => { float alpha = hidden ? 0.0f : 1.0f; UIApplication.SharedApplication.SetStatusBarHidden (hidden, false); statusBarHidden = hidden; SetNeedsStatusBarAppearanceUpdate (); if (!hidden) { toolBar.Hidden = false; NavigationController.SetNavigationBarHidden (false, false); } toolBar.Alpha = alpha; NavigationController.NavigationBar.Alpha = alpha; }, () => { if (hidden) { toolBar.Hidden = true; NavigationController.SetNavigationBarHidden (true, false); } }); } void SetImageViewConstraints (UIInterfaceOrientation orientation) { bool flip = orientation.IsLandscape (); var bounds = UIScreen.MainScreen.Bounds; NSLayoutConstraint[] constraints = imageView.Constraints; foreach (var constraint in constraints) { if (constraint.FirstAttribute == NSLayoutAttribute.Height) constraint.Constant = flip ? bounds.Size.Width : bounds.Size.Height; else if (constraint.FirstAttribute == NSLayoutAttribute.Width) constraint.Constant = flip ? bounds.Size.Height : bounds.Size.Width; } imageView.SetNeedsUpdateConstraints (); } partial void Share (NSObject sender) { if (imageView.Image == null) return; var avc = new UIActivityViewController (new [] { imageView.Image }, null); avc.RestorationIdentifier = "Activity"; PresentViewController (avc, true, null); } // State Restoration [Export ("objectWithRestorationIdentifierPath:coder:")] public static UIStateRestoring GetStateRestorationObjectFromPath (string[] identifierComponents, NSCoder coder) { var key = identifierComponents [identifierComponents.Length - 1]; return CreateFilter (key, false); } public override void EncodeRestorableState (NSCoder coder) { base.EncodeRestorableState (coder); coder.Encode ((NSString)ImageIdentifier, imageIdentifierKey); coder.Encode (DataSource, dataSourceKey); TryEncodeFilters (coder); TryEncodeBarsVisibility (coder); } void TryEncodeFilters (NSCoder coder) { if (filters == null) return; var nativeDict = new NSMutableDictionary (); foreach (var key in filters.Keys) nativeDict [key] = filters [key]; coder.Encode (nativeDict, imageFiltersKey); } void TryEncodeBarsVisibility (NSCoder coder) { if (UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.Portrait) coder.Encode (toolBar.Hidden, barsHiddenKey); } public override void DecodeRestorableState (NSCoder coder) { base.DecodeRestorableState (coder); ImageIdentifier = (NSString)coder.DecodeObject (imageIdentifierKey); DataSource = (DataSource)coder.DecodeObject (dataSourceKey); TryDecodeFilters (coder); TryDecodeBarsVisibility (coder); } void TryDecodeFilters (NSCoder coder) { if (!coder.ContainsKey (imageFiltersKey)) return; var filtersNS = (NSMutableDictionary)coder.DecodeObject (imageFiltersKey); if (filtersNS == null) return; filters = new Dictionary<string, ImageFilter> (); var blurFilter = (ImageFilter)filtersNS [blurFilterKey]; if (blurFilter != null) filters [blurFilterKey] = blurFilter; var modifyFilter = (ImageFilter)filtersNS [modifyFilterKey]; if (modifyFilter != null) filters [modifyFilterKey] = modifyFilter; } void TryDecodeBarsVisibility (NSCoder coder) { bool hidden = coder.DecodeBool (barsHiddenKey); if (hidden) UpdateBars (); } public override void ApplicationFinishedRestoringState () { base.ApplicationFinishedRestoringState (); UpdateImage (); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Xml; namespace Orleans.Runtime.Configuration { /// <summary> /// Individual node-specific silo configuration parameters. /// </summary> [Serializable] public class NodeConfiguration :IStatisticsConfiguration { private readonly DateTime creationTimestamp; private string siloName; /// <summary> /// The name of this silo. /// </summary> public string SiloName { get { return siloName; } set { siloName = value; } } /// <summary> /// The DNS host name of this silo. /// This is a true host name, no IP address. It is NOT settable, equals Dns.GetHostName(). /// </summary> public string DNSHostName { get; private set; } /// <summary> /// The host name or IP address of this silo. /// This is a configurable IP address or Hostname. /// </summary> public string HostNameOrIPAddress { get; set; } private IPAddress Address { get { return ClusterConfiguration.ResolveIPAddress(HostNameOrIPAddress, Subnet, AddressType).GetResult(); } } /// <summary> /// The port this silo uses for silo-to-silo communication. /// </summary> public int Port { get; set; } /// <summary> /// The epoch generation number for this silo. /// </summary> public int Generation { get; set; } /// <summary> /// The IPEndPoint this silo uses for silo-to-silo communication. /// </summary> public IPEndPoint Endpoint { get { return new IPEndPoint(Address, Port); } } /// <summary> /// The AddressFamilyof the IP address of this silo. /// </summary> public AddressFamily AddressType { get; set; } /// <summary> /// The IPEndPoint this silo uses for (gateway) silo-to-client communication. /// </summary> public IPEndPoint ProxyGatewayEndpoint { get; set; } internal byte[] Subnet { get; set; } // from global /// <summary> /// Whether this is a primary silo (applies for dev settings only). /// </summary> public bool IsPrimaryNode { get; internal set; } /// <summary> /// Whether this is one of the seed silos (applies for dev settings only). /// </summary> public bool IsSeedNode { get; internal set; } /// <summary> /// Whether this is silo is a proxying gateway silo. /// </summary> public bool IsGatewayNode { get { return ProxyGatewayEndpoint != null; } } /// <summary> /// The MaxActiveThreads attribute specifies the maximum number of simultaneous active threads the scheduler will allow. /// Generally this number should be roughly equal to the number of cores on the node. /// Using a value of 0 will look at System.Environment.ProcessorCount to decide the number instead, which is only valid when set from xml config /// </summary> public int MaxActiveThreads { get; set; } /// <summary> /// The DelayWarningThreshold attribute specifies the work item queuing delay threshold, at which a warning log message is written. /// That is, if the delay between enqueuing the work item and executing the work item is greater than DelayWarningThreshold, a warning log is written. /// The default value is 10 seconds. /// </summary> public TimeSpan DelayWarningThreshold { get; set; } /// <summary> /// ActivationSchedulingQuantum is a soft time limit on the duration of activation macro-turn (a number of micro-turns). /// If a activation was running its micro-turns longer than this, we will give up the thread. /// If this is set to zero or a negative number, then the full work queue is drained (MaxWorkItemsPerTurn allowing). /// </summary> public TimeSpan ActivationSchedulingQuantum { get; set; } /// <summary> /// TurnWarningLengthThreshold is a soft time limit to generate trace warning when the micro-turn executes longer then this period in CPU. /// </summary> public TimeSpan TurnWarningLengthThreshold { get; set; } internal bool EnableWorkerThreadInjection { get; set; } /// <summary> /// The LoadShedding element specifies the gateway load shedding configuration for the node. /// If it does not appear, gateway load shedding is disabled. /// </summary> public bool LoadSheddingEnabled { get; set; } /// <summary> /// The LoadLimit attribute specifies the system load, in CPU%, at which load begins to be shed. /// Note that this value is in %, so valid values range from 1 to 100, and a reasonable value is /// typically between 80 and 95. /// This value is ignored if load shedding is disabled, which is the default. /// If load shedding is enabled and this attribute does not appear, then the default limit is 95%. /// </summary> public int LoadSheddingLimit { get; set; } /// <summary> /// The values for various silo limits. /// </summary> public LimitManager LimitManager { get; private set; } /// <summary> /// Whether Trace.CorrelationManager.ActivityId settings should be propagated into grain calls. /// </summary> public bool PropagateActivityId { get; set; } /// <summary> /// Specifies the name of the Startup class in the configuration file. /// </summary> public string StartupTypeName { get; set; } public string StatisticsProviderName { get; set; } /// <summary> /// The MetricsTableWriteInterval attribute specifies the frequency of updating the metrics in Azure table. /// The default is 30 seconds. /// </summary> public TimeSpan StatisticsMetricsTableWriteInterval { get; set; } /// <summary> /// The PerfCounterWriteInterval attribute specifies the frequency of updating the windows performance counters. /// The default is 30 seconds. /// </summary> public TimeSpan StatisticsPerfCountersWriteInterval { get; set; } /// <summary> /// The LogWriteInterval attribute specifies the frequency of updating the statistics in the log file. /// The default is 5 minutes. /// </summary> public TimeSpan StatisticsLogWriteInterval { get; set; } /// <summary> /// The WriteLogStatisticsToTable attribute specifies whether log statistics should also be written into a separate, special Azure table. /// The default is yes. /// </summary> public bool StatisticsWriteLogStatisticsToTable { get; set; } /// <summary> /// </summary> public StatisticsLevel StatisticsCollectionLevel { get; set; } /// <summary> /// </summary> public int MinDotNetThreadPoolSize { get; set; } /// <summary> /// </summary> public bool Expect100Continue { get; set; } /// <summary> /// </summary> public int DefaultConnectionLimit { get; set; } /// <summary> /// </summary> public bool UseNagleAlgorithm { get; set; } public TelemetryConfiguration TelemetryConfiguration { get; } = new TelemetryConfiguration(); public Dictionary<string, SearchOption> AdditionalAssemblyDirectories { get; set; } public List<string> ExcludedGrainTypes { get; set; } public string SiloShutdownEventName { get; set; } internal const string DEFAULT_NODE_NAME = "default"; private static readonly TimeSpan DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD = TimeSpan.FromSeconds(30); private static readonly TimeSpan DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD = TimeSpan.FromSeconds(30); private static readonly TimeSpan DEFAULT_STATS_LOG_WRITE_PERIOD = TimeSpan.FromMinutes(5); internal static readonly StatisticsLevel DEFAULT_STATS_COLLECTION_LEVEL = StatisticsLevel.Info; private static readonly int DEFAULT_MAX_ACTIVE_THREADS = Math.Max(4, System.Environment.ProcessorCount); private const int DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE = 200; private static readonly int DEFAULT_MIN_DOT_NET_CONNECTION_LIMIT = DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE; private static readonly TimeSpan DEFAULT_ACTIVATION_SCHEDULING_QUANTUM = TimeSpan.FromMilliseconds(100); internal const bool ENABLE_WORKER_THREAD_INJECTION = false; public NodeConfiguration() { creationTimestamp = DateTime.UtcNow; SiloName = ""; HostNameOrIPAddress = ""; DNSHostName = Dns.GetHostName(); Port = 0; Generation = 0; AddressType = AddressFamily.InterNetwork; ProxyGatewayEndpoint = null; MaxActiveThreads = DEFAULT_MAX_ACTIVE_THREADS; DelayWarningThreshold = TimeSpan.FromMilliseconds(10000); // 10,000 milliseconds ActivationSchedulingQuantum = DEFAULT_ACTIVATION_SCHEDULING_QUANTUM; TurnWarningLengthThreshold = TimeSpan.FromMilliseconds(200); EnableWorkerThreadInjection = ENABLE_WORKER_THREAD_INJECTION; LoadSheddingEnabled = false; LoadSheddingLimit = 95; PropagateActivityId = Constants.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID; StatisticsMetricsTableWriteInterval = DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD; StatisticsPerfCountersWriteInterval = DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD; StatisticsLogWriteInterval = DEFAULT_STATS_LOG_WRITE_PERIOD; StatisticsWriteLogStatisticsToTable = true; StatisticsCollectionLevel = DEFAULT_STATS_COLLECTION_LEVEL; LimitManager = new LimitManager(); MinDotNetThreadPoolSize = DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE; // .NET ServicePointManager settings / optimizations Expect100Continue = false; DefaultConnectionLimit = DEFAULT_MIN_DOT_NET_CONNECTION_LIMIT; UseNagleAlgorithm = false; AdditionalAssemblyDirectories = new Dictionary<string, SearchOption>(); ExcludedGrainTypes = new List<string>(); } public NodeConfiguration(NodeConfiguration other) { creationTimestamp = other.creationTimestamp; SiloName = other.SiloName; HostNameOrIPAddress = other.HostNameOrIPAddress; DNSHostName = other.DNSHostName; Port = other.Port; Generation = other.Generation; AddressType = other.AddressType; ProxyGatewayEndpoint = other.ProxyGatewayEndpoint; MaxActiveThreads = other.MaxActiveThreads; DelayWarningThreshold = other.DelayWarningThreshold; ActivationSchedulingQuantum = other.ActivationSchedulingQuantum; TurnWarningLengthThreshold = other.TurnWarningLengthThreshold; EnableWorkerThreadInjection = other.EnableWorkerThreadInjection; LoadSheddingEnabled = other.LoadSheddingEnabled; LoadSheddingLimit = other.LoadSheddingLimit; PropagateActivityId = other.PropagateActivityId; StatisticsProviderName = other.StatisticsProviderName; StatisticsMetricsTableWriteInterval = other.StatisticsMetricsTableWriteInterval; StatisticsPerfCountersWriteInterval = other.StatisticsPerfCountersWriteInterval; StatisticsLogWriteInterval = other.StatisticsLogWriteInterval; StatisticsWriteLogStatisticsToTable = other.StatisticsWriteLogStatisticsToTable; StatisticsCollectionLevel = other.StatisticsCollectionLevel; LimitManager = new LimitManager(other.LimitManager); // Shallow copy Subnet = other.Subnet; MinDotNetThreadPoolSize = other.MinDotNetThreadPoolSize; Expect100Continue = other.Expect100Continue; DefaultConnectionLimit = other.DefaultConnectionLimit; UseNagleAlgorithm = other.UseNagleAlgorithm; StartupTypeName = other.StartupTypeName; AdditionalAssemblyDirectories = new Dictionary<string, SearchOption>(other.AdditionalAssemblyDirectories); ExcludedGrainTypes = other.ExcludedGrainTypes.ToList(); TelemetryConfiguration = other.TelemetryConfiguration.Clone(); } public override string ToString() { var sb = new StringBuilder(); sb.Append(" Silo Name: ").AppendLine(SiloName); sb.Append(" Generation: ").Append(Generation).AppendLine(); sb.Append(" Host Name or IP Address: ").AppendLine(HostNameOrIPAddress); sb.Append(" DNS Host Name: ").AppendLine(DNSHostName); sb.Append(" Port: ").Append(Port).AppendLine(); sb.Append(" Subnet: ").Append(Subnet == null ? "" : Subnet.ToStrings(x => x.ToString(), ".")).AppendLine(); sb.Append(" Preferred Address Family: ").Append(AddressType).AppendLine(); if (IsGatewayNode) { sb.Append(" Proxy Gateway: ").Append(ProxyGatewayEndpoint.ToString()).AppendLine(); } else { sb.Append(" IsGatewayNode: ").Append(IsGatewayNode).AppendLine(); } sb.Append(" IsPrimaryNode: ").Append(IsPrimaryNode).AppendLine(); sb.Append(" Scheduler: ").AppendLine(); sb.Append(" ").Append(" Max Active Threads: ").Append(MaxActiveThreads).AppendLine(); sb.Append(" ").Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine(); sb.Append(" ").Append(" Delay Warning Threshold: ").Append(DelayWarningThreshold).AppendLine(); sb.Append(" ").Append(" Activation Scheduling Quantum: ").Append(ActivationSchedulingQuantum).AppendLine(); sb.Append(" ").Append(" Turn Warning Length Threshold: ").Append(TurnWarningLengthThreshold).AppendLine(); sb.Append(" ").Append(" Inject More Worker Threads: ").Append(EnableWorkerThreadInjection).AppendLine(); sb.Append(" ").Append(" MinDotNetThreadPoolSize: ").Append(MinDotNetThreadPoolSize).AppendLine(); int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); sb.Append(" ").AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); sb.Append(" ").AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); sb.Append(" ").AppendFormat(" .NET ServicePointManager - DefaultConnectionLimit={0} Expect100Continue={1} UseNagleAlgorithm={2}", DefaultConnectionLimit, Expect100Continue, UseNagleAlgorithm).AppendLine(); sb.Append(" Load Shedding Enabled: ").Append(LoadSheddingEnabled).AppendLine(); sb.Append(" Load Shedding Limit: ").Append(LoadSheddingLimit).AppendLine(); sb.Append(" SiloShutdownEventName: ").Append(SiloShutdownEventName).AppendLine(); sb.Append(" Debug: ").AppendLine(); sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this)); sb.Append(LimitManager); return sb.ToString(); } internal void Load(XmlElement root) { SiloName = root.LocalName.Equals("Override") ? root.GetAttribute("Node") : DEFAULT_NODE_NAME; foreach (XmlNode c in root.ChildNodes) { var child = c as XmlElement; if (child == null) continue; // Skip comment lines switch (child.LocalName) { case "Networking": if (child.HasAttribute("Address")) { HostNameOrIPAddress = child.GetAttribute("Address"); } if (child.HasAttribute("Port")) { Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"), "Non-numeric Port attribute value on Networking element for " + SiloName); } if (child.HasAttribute("PreferredFamily")) { AddressType = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"), "Invalid preferred address family on Networking node. Valid choices are 'InterNetwork' and 'InterNetworkV6'"); } break; case "ProxyingGateway": ProxyGatewayEndpoint = ConfigUtilities.ParseIPEndPoint(child, Subnet).GetResult(); break; case "Scheduler": if (child.HasAttribute("MaxActiveThreads")) { MaxActiveThreads = ConfigUtilities.ParseInt(child.GetAttribute("MaxActiveThreads"), "Non-numeric MaxActiveThreads attribute value on Scheduler element for " + SiloName); if (MaxActiveThreads < 1) { MaxActiveThreads = DEFAULT_MAX_ACTIVE_THREADS; } } if (child.HasAttribute("DelayWarningThreshold")) { DelayWarningThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DelayWarningThreshold"), "Non-numeric DelayWarningThreshold attribute value on Scheduler element for " + SiloName); } if (child.HasAttribute("ActivationSchedulingQuantum")) { ActivationSchedulingQuantum = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ActivationSchedulingQuantum"), "Non-numeric ActivationSchedulingQuantum attribute value on Scheduler element for " + SiloName); } if (child.HasAttribute("TurnWarningLengthThreshold")) { TurnWarningLengthThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("TurnWarningLengthThreshold"), "Non-numeric TurnWarningLengthThreshold attribute value on Scheduler element for " + SiloName); } if (child.HasAttribute("MinDotNetThreadPoolSize")) { MinDotNetThreadPoolSize = ConfigUtilities.ParseInt(child.GetAttribute("MinDotNetThreadPoolSize"), "Invalid ParseInt MinDotNetThreadPoolSize value on Scheduler element for " + SiloName); } if (child.HasAttribute("Expect100Continue")) { Expect100Continue = ConfigUtilities.ParseBool(child.GetAttribute("Expect100Continue"), "Invalid ParseBool Expect100Continue value on Scheduler element for " + SiloName); } if (child.HasAttribute("DefaultConnectionLimit")) { DefaultConnectionLimit = ConfigUtilities.ParseInt(child.GetAttribute("DefaultConnectionLimit"), "Invalid ParseInt DefaultConnectionLimit value on Scheduler element for " + SiloName); } if (child.HasAttribute("UseNagleAlgorithm ")) { UseNagleAlgorithm = ConfigUtilities.ParseBool(child.GetAttribute("UseNagleAlgorithm "), "Invalid ParseBool UseNagleAlgorithm value on Scheduler element for " + SiloName); } break; case "LoadShedding": if (child.HasAttribute("Enabled")) { LoadSheddingEnabled = ConfigUtilities.ParseBool(child.GetAttribute("Enabled"), "Invalid boolean value for Enabled attribute on LoadShedding attribute for " + SiloName); } if (child.HasAttribute("LoadLimit")) { LoadSheddingLimit = ConfigUtilities.ParseInt(child.GetAttribute("LoadLimit"), "Invalid integer value for LoadLimit attribute on LoadShedding attribute for " + SiloName); if (LoadSheddingLimit < 0) { LoadSheddingLimit = 0; } if (LoadSheddingLimit > 100) { LoadSheddingLimit = 100; } } break; case "Tracing": if (ConfigUtilities.TryParsePropagateActivityId(child, siloName, out var propagateActivityId)) this.PropagateActivityId = propagateActivityId; break; case "Statistics": ConfigUtilities.ParseStatistics(this, child, SiloName); break; case "Limits": ConfigUtilities.ParseLimitValues(LimitManager, child, SiloName); break; case "Startup": if (child.HasAttribute("Type")) { StartupTypeName = child.GetAttribute("Type"); } break; case "Telemetry": ConfigUtilities.ParseTelemetry(child, this.TelemetryConfiguration); break; case "AdditionalAssemblyDirectories": ConfigUtilities.ParseAdditionalAssemblyDirectories(AdditionalAssemblyDirectories, child); break; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Globalization; using System.IO; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.NewtonsoftJson; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; using Newtonsoft.Json; namespace Microsoft.AspNetCore.Mvc.Formatters { /// <summary> /// A <see cref="TextInputFormatter"/> for JSON content. /// </summary> public class NewtonsoftJsonInputFormatter : TextInputFormatter, IInputFormatterExceptionPolicy { private readonly IArrayPool<char> _charPool; private readonly ILogger _logger; private readonly ObjectPoolProvider _objectPoolProvider; private readonly MvcOptions _options; private readonly MvcNewtonsoftJsonOptions _jsonOptions; private ObjectPool<JsonSerializer>? _jsonSerializerPool; /// <summary> /// Initializes a new instance of <see cref="NewtonsoftJsonInputFormatter"/>. /// </summary> /// <param name="logger">The <see cref="ILogger"/>.</param> /// <param name="serializerSettings"> /// The <see cref="JsonSerializerSettings"/>. Should be either the application-wide settings /// (<see cref="MvcNewtonsoftJsonOptions.SerializerSettings"/>) or an instance /// <see cref="JsonSerializerSettingsProvider.CreateSerializerSettings"/> initially returned. /// </param> /// <param name="charPool">The <see cref="ArrayPool{Char}"/>.</param> /// <param name="objectPoolProvider">The <see cref="ObjectPoolProvider"/>.</param> /// <param name="options">The <see cref="MvcOptions"/>.</param> /// <param name="jsonOptions">The <see cref="MvcNewtonsoftJsonOptions"/>.</param> public NewtonsoftJsonInputFormatter( ILogger logger, JsonSerializerSettings serializerSettings, ArrayPool<char> charPool, ObjectPoolProvider objectPoolProvider, MvcOptions options, MvcNewtonsoftJsonOptions jsonOptions) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (serializerSettings == null) { throw new ArgumentNullException(nameof(serializerSettings)); } if (charPool == null) { throw new ArgumentNullException(nameof(charPool)); } if (objectPoolProvider == null) { throw new ArgumentNullException(nameof(objectPoolProvider)); } _logger = logger; SerializerSettings = serializerSettings; _charPool = new JsonArrayPool<char>(charPool); _objectPoolProvider = objectPoolProvider; _options = options; _jsonOptions = jsonOptions; SupportedEncodings.Add(UTF8EncodingWithoutBOM); SupportedEncodings.Add(UTF16EncodingLittleEndian); SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationJson); SupportedMediaTypes.Add(MediaTypeHeaderValues.TextJson); SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationAnyJsonSyntax); } /// <inheritdoc /> public virtual InputFormatterExceptionPolicy ExceptionPolicy { get { if (GetType() == typeof(NewtonsoftJsonInputFormatter)) { return InputFormatterExceptionPolicy.MalformedInputExceptions; } return InputFormatterExceptionPolicy.AllExceptions; } } /// <summary> /// Gets the <see cref="JsonSerializerSettings"/> used to configure the <see cref="JsonSerializer"/>. /// </summary> /// <remarks> /// Any modifications to the <see cref="JsonSerializerSettings"/> object after this /// <see cref="NewtonsoftJsonInputFormatter"/> has been used will have no effect. /// </remarks> protected JsonSerializerSettings SerializerSettings { get; } /// <inheritdoc /> public override async Task<InputFormatterResult> ReadRequestBodyAsync( InputFormatterContext context, Encoding encoding) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (encoding == null) { throw new ArgumentNullException(nameof(encoding)); } var httpContext = context.HttpContext; var request = httpContext.Request; var suppressInputFormatterBuffering = _options.SuppressInputFormatterBuffering; var readStream = request.Body; var disposeReadStream = false; if (readStream.CanSeek) { // The most common way of getting here is the user has request buffering on. // However, request buffering isn't eager, and consequently it will peform pass-thru synchronous // reads as part of the deserialization. // To avoid this, drain and reset the stream. var position = request.Body.Position; await readStream.DrainAsync(CancellationToken.None); readStream.Position = position; } else if (!suppressInputFormatterBuffering) { // JSON.Net does synchronous reads. In order to avoid blocking on the stream, we asynchronously // read everything into a buffer, and then seek back to the beginning. var memoryThreshold = _jsonOptions.InputFormatterMemoryBufferThreshold; var contentLength = request.ContentLength.GetValueOrDefault(); if (contentLength > 0 && contentLength < memoryThreshold) { // If the Content-Length is known and is smaller than the default buffer size, use it. memoryThreshold = (int)contentLength; } readStream = new FileBufferingReadStream(request.Body, memoryThreshold); // Ensure the file buffer stream is always disposed at the end of a request. httpContext.Response.RegisterForDispose(readStream); await readStream.DrainAsync(CancellationToken.None); readStream.Seek(0L, SeekOrigin.Begin); disposeReadStream = true; } var successful = true; Exception? exception = null; object? model; using (var streamReader = context.ReaderFactory(readStream, encoding)) { using var jsonReader = new JsonTextReader(streamReader); jsonReader.ArrayPool = _charPool; jsonReader.CloseInput = false; var type = context.ModelType; var jsonSerializer = CreateJsonSerializer(context); jsonSerializer.Error += ErrorHandler; if (_jsonOptions.ReadJsonWithRequestCulture) { jsonSerializer.Culture = CultureInfo.CurrentCulture; } try { model = jsonSerializer.Deserialize(jsonReader, type); } finally { // Clean up the error handler since CreateJsonSerializer() pools instances. jsonSerializer.Error -= ErrorHandler; ReleaseJsonSerializer(jsonSerializer); if (disposeReadStream) { await readStream.DisposeAsync(); } } } if (successful) { if (model == null && !context.TreatEmptyInputAsDefaultValue) { // Some nonempty inputs might deserialize as null, for example whitespace, // or the JSON-encoded value "null". The upstream BodyModelBinder needs to // be notified that we don't regard this as a real input so it can register // a model binding error. return InputFormatterResult.NoValue(); } else { return InputFormatterResult.Success(model); } } if (exception is not null && exception is not (JsonException or OverflowException or FormatException)) { // At this point we've already recorded all exceptions as an entry in the ModelStateDictionary. // We only need to rethrow an exception if we believe it needs to be handled by something further up // the stack. // JsonException, OverflowException, and FormatException are assumed to be only encountered when // parsing the JSON and are consequently "safe" to be exposed as part of ModelState. Everything else // needs to be rethrown. var exceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception); exceptionDispatchInfo.Throw(); } return InputFormatterResult.Failure(); void ErrorHandler(object? sender, Newtonsoft.Json.Serialization.ErrorEventArgs eventArgs) { successful = false; // When ErrorContext.Path does not include ErrorContext.Member, add Member to form full path. var path = eventArgs.ErrorContext.Path; var member = eventArgs.ErrorContext.Member?.ToString(); var addMember = !string.IsNullOrEmpty(member); if (addMember) { // Path.Member case (path.Length < member.Length) needs no further checks. if (path.Length == member!.Length) { // Add Member in Path.Memb case but not for Path.Path. addMember = !string.Equals(path, member, StringComparison.Ordinal); } else if (path.Length > member.Length) { // Finally, check whether Path already ends with Member. if (member[0] == '[') { addMember = !path.EndsWith(member, StringComparison.Ordinal); } else { addMember = !path.EndsWith("." + member, StringComparison.Ordinal) && !path.EndsWith("['" + member + "']", StringComparison.Ordinal) && !path.EndsWith("[" + member + "]", StringComparison.Ordinal); } } } if (addMember) { path = ModelNames.CreatePropertyModelName(path, member); } // Handle path combinations such as ""+"Property", "Parent"+"Property", or "Parent"+"[12]". var key = ModelNames.CreatePropertyModelName(context.ModelName, path); exception = eventArgs.ErrorContext.Error; var metadata = GetPathMetadata(context.Metadata, path); var modelStateException = WrapExceptionForModelState(exception); context.ModelState.TryAddModelError(key, modelStateException, metadata); _logger.JsonInputException(exception); // Error must always be marked as handled // Failure to do so can cause the exception to be rethrown at every recursive level and // overflow the stack for x64 CLR processes eventArgs.ErrorContext.Handled = true; } } /// <summary> /// Called during deserialization to get the <see cref="JsonSerializer"/>. The formatter context /// that is passed gives an ability to create serializer specific to the context. /// </summary> /// <returns>The <see cref="JsonSerializer"/> used during deserialization.</returns> /// <remarks> /// This method works in tandem with <see cref="ReleaseJsonSerializer(JsonSerializer)"/> to /// manage the lifetimes of <see cref="JsonSerializer"/> instances. /// </remarks> protected virtual JsonSerializer CreateJsonSerializer() { if (_jsonSerializerPool == null) { _jsonSerializerPool = _objectPoolProvider.Create(new JsonSerializerObjectPolicy(SerializerSettings)); } return _jsonSerializerPool.Get(); } /// <summary> /// Called during deserialization to get the <see cref="JsonSerializer"/>. The formatter context /// that is passed gives an ability to create serializer specific to the context. /// </summary> /// <param name="context">A context object used by an input formatter for deserializing the request body into an object.</param> /// <returns>The <see cref="JsonSerializer"/> used during deserialization.</returns> /// <remarks> /// This method works in tandem with <see cref="ReleaseJsonSerializer(JsonSerializer)"/> to /// manage the lifetimes of <see cref="JsonSerializer"/> instances. /// </remarks> protected virtual JsonSerializer CreateJsonSerializer(InputFormatterContext context) { return CreateJsonSerializer(); } /// <summary> /// Releases the <paramref name="serializer"/> instance. /// </summary> /// <param name="serializer">The <see cref="JsonSerializer"/> to release.</param> /// <remarks> /// This method works in tandem with <see cref="ReleaseJsonSerializer(JsonSerializer)"/> to /// manage the lifetimes of <see cref="JsonSerializer"/> instances. /// </remarks> protected virtual void ReleaseJsonSerializer(JsonSerializer serializer) => _jsonSerializerPool!.Return(serializer); private ModelMetadata GetPathMetadata(ModelMetadata metadata, string path) { var index = 0; while (index >= 0 && index < path.Length) { if (path[index] == '[') { // At start of "[0]". if (metadata.ElementMetadata == null) { // Odd case but don't throw just because ErrorContext had an odd-looking path. break; } metadata = metadata.ElementMetadata; index = path.IndexOf(']', index); } else if (path[index] == '.' || path[index] == ']') { // Skip '.' in "prefix.property" or "[0].property" or ']' in "[0]". index++; } else { // At start of "property", "property." or "property[0]". var endIndex = path.IndexOfAny(new[] { '.', '[' }, index); if (endIndex == -1) { endIndex = path.Length; } var propertyName = path.Substring(index, endIndex - index); var propertyMetadata = metadata.Properties[propertyName]; if (propertyMetadata is null) { // Odd case but don't throw just because ErrorContext had an odd-looking path. break; } metadata = propertyMetadata; index = endIndex; } } return metadata; } private Exception WrapExceptionForModelState(Exception exception) { // In 2.0 and earlier we always gave a generic error message for errors that come from JSON.NET // We only allow it in 2.1 and newer if the app opts-in. if (!_jsonOptions.AllowInputFormatterExceptionMessages) { // This app is not opted-in to JSON.NET messages, return the original exception. return exception; } // It's not known that Json.NET currently ever raises error events with exceptions // other than these two types, but we're being conservative and limiting which ones // we regard as having safe messages to expose to clients if (exception is JsonReaderException || exception is JsonSerializationException) { // InputFormatterException specifies that the message is safe to return to a client, it will // be added to model state. return new InputFormatterException(exception.Message, exception); } // Not a known exception type, so we're not going to assume that it's safe. return exception; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace System.ComponentModel.Design { /// <summary> /// This is a simple implementation of IServiceContainer. /// </summary> public class ServiceContainer : IServiceContainer, IDisposable { private ServiceCollection<object> _services; private readonly IServiceProvider _parentProvider; private static readonly Type[] s_defaultServices = new Type[] { typeof(IServiceContainer), typeof(ServiceContainer) }; /// <summary> /// Creates a new service object container. /// </summary> public ServiceContainer() { } /// <summary> /// Creates a new service object container. /// </summary> public ServiceContainer(IServiceProvider parentProvider) { _parentProvider = parentProvider; } /// <summary> /// Retrieves the parent service container, or null if there is no parent container. /// </summary> private IServiceContainer Container { get => _parentProvider?.GetService(typeof(IServiceContainer)) as IServiceContainer; } /// <summary> /// This property returns the default services that are implemented directly on this IServiceContainer. /// the default implementation of this property is to return the IServiceContainer and ServiceContainer /// types. You may override this property and return your own types, modifying the default behavior /// of GetService. /// </summary> protected virtual Type[] DefaultServices => s_defaultServices; /// <summary> /// Our collection of services. The service collection is demand /// created here. /// </summary> private ServiceCollection<object> Services => _services ?? (_services = new ServiceCollection<object>()); /// <summary> /// Adds the given service to the service container. /// </summary> public void AddService(Type serviceType, object serviceInstance) { AddService(serviceType, serviceInstance, false); } /// <summary> /// Adds the given service to the service container. /// </summary> public virtual void AddService(Type serviceType, object serviceInstance, bool promote) { if (promote) { IServiceContainer container = Container; if (container != null) { container.AddService(serviceType, serviceInstance, promote); return; } } // We're going to add this locally. Ensure that the service instance // is correct. // if (serviceType == null) throw new ArgumentNullException(nameof(serviceType)); if (serviceInstance == null) throw new ArgumentNullException(nameof(serviceInstance)); if (!(serviceInstance is ServiceCreatorCallback) && !serviceInstance.GetType().IsCOMObject && !serviceType.IsInstanceOfType(serviceInstance)) { throw new ArgumentException(SR.Format(SR.ErrorInvalidServiceInstance, serviceType.FullName)); } if (Services.ContainsKey(serviceType)) { throw new ArgumentException(SR.Format(SR.ErrorServiceExists, serviceType.FullName), nameof(serviceType)); } Services[serviceType] = serviceInstance; } /// <summary> /// Adds the given service to the service container. /// </summary> public void AddService(Type serviceType, ServiceCreatorCallback callback) { AddService(serviceType, callback, false); } /// <summary> /// Adds the given service to the service container. /// </summary> public virtual void AddService(Type serviceType, ServiceCreatorCallback callback, bool promote) { if (promote) { IServiceContainer container = Container; if (container != null) { container.AddService(serviceType, callback, promote); return; } } // We're going to add this locally. Ensure that the service instance // is correct. // if (serviceType == null) throw new ArgumentNullException(nameof(serviceType)); if (callback == null) throw new ArgumentNullException(nameof(callback)); if (Services.ContainsKey(serviceType)) { throw new ArgumentException(SR.Format(SR.ErrorServiceExists, serviceType.FullName), nameof(serviceType)); } Services[serviceType] = callback; } /// <summary> /// Disposes this service container. This also walks all instantiated services within the container /// and disposes any that implement IDisposable, and clears the service list. /// </summary> public void Dispose() { Dispose(true); } /// <summary> /// Disposes this service container. This also walks all instantiated services within the container /// and disposes any that implement IDisposable, and clears the service list. /// </summary> protected virtual void Dispose(bool disposing) { if (disposing) { ServiceCollection<object> serviceCollection = _services; _services = null; if (serviceCollection != null) { foreach (object o in serviceCollection.Values) { if (o is IDisposable) { ((IDisposable)o).Dispose(); } } } } } /// <summary> /// Retrieves the requested service. /// </summary> public virtual object GetService(Type serviceType) { object service = null; // Try locally. We first test for services we // implement and then look in our service collection. Type[] defaults = DefaultServices; for (int idx = 0; idx < defaults.Length; idx++) { if (serviceType != null && serviceType.IsEquivalentTo(defaults[idx])) { service = this; break; } } if (service == null && serviceType != null) { Services.TryGetValue(serviceType, out service); } // Is the service a creator delegate? if (service is ServiceCreatorCallback) { service = ((ServiceCreatorCallback)service)(this, serviceType); if (service != null && !service.GetType().IsCOMObject && !serviceType.IsInstanceOfType(service)) { // Callback passed us a bad service. NULL it, rather than throwing an exception. // Callers here do not need to be prepared to handle bad callback implemetations. service = null; } // And replace the callback with our new service. Services[serviceType] = service; } if (service == null && _parentProvider != null) { service = _parentProvider.GetService(serviceType); } return service; } /// <summary> /// Removes the given service type from the service container. /// </summary> public void RemoveService(Type serviceType) { RemoveService(serviceType, false); } /// <summary> /// Removes the given service type from the service container. /// </summary> public virtual void RemoveService(Type serviceType, bool promote) { if (promote) { IServiceContainer container = Container; if (container != null) { container.RemoveService(serviceType, promote); return; } } // We're going to remove this from our local list. if (serviceType == null) { throw new ArgumentNullException(nameof(serviceType)); } Services.Remove(serviceType); } /// <summary> /// Use this collection to store mapping from the Type of a service to the object that provides it in a way /// that is aware of embedded types. The comparer for this collection will call Type.IsEquivalentTo(...) /// instead of doing a reference comparison which will fail in type embedding scenarios. To speed the lookup /// performance we will use hash code of Type.FullName. /// </summary> /// <typeparam name="T"></typeparam> private sealed class ServiceCollection<T> : Dictionary<Type, T> { private static readonly EmbeddedTypeAwareTypeComparer s_serviceTypeComparer = new EmbeddedTypeAwareTypeComparer(); private sealed class EmbeddedTypeAwareTypeComparer : IEqualityComparer<Type> { public bool Equals(Type x, Type y) => x.IsEquivalentTo(y); public int GetHashCode(Type obj) => obj.FullName.GetHashCode(); } public ServiceCollection() : base(s_serviceTypeComparer) { } } } }
namespace Humidifier.OpsWorks { using System.Collections.Generic; using InstanceTypes; public class Instance : Humidifier.Resource { public static class Attributes { public static string AvailabilityZone = "AvailabilityZone" ; public static string PrivateDnsName = "PrivateDnsName" ; public static string PrivateIp = "PrivateIp" ; public static string PublicDnsName = "PublicDnsName" ; public static string PublicIp = "PublicIp" ; } public override string AWSTypeName { get { return @"AWS::OpsWorks::Instance"; } } /// <summary> /// AgentVersion /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-agentversion /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic AgentVersion { get; set; } /// <summary> /// AmiId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-amiid /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic AmiId { get; set; } /// <summary> /// Architecture /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-architecture /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Architecture { get; set; } /// <summary> /// AutoScalingType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-autoscalingtype /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic AutoScalingType { get; set; } /// <summary> /// AvailabilityZone /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-availabilityzone /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic AvailabilityZone { get; set; } /// <summary> /// BlockDeviceMappings /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-blockdevicemappings /// Required: False /// UpdateType: Immutable /// Type: List /// ItemType: BlockDeviceMapping /// </summary> public List<BlockDeviceMapping> BlockDeviceMappings { get; set; } /// <summary> /// EbsOptimized /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-ebsoptimized /// Required: False /// UpdateType: Immutable /// PrimitiveType: Boolean /// </summary> public dynamic EbsOptimized { get; set; } /// <summary> /// ElasticIps /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-elasticips /// Required: False /// UpdateType: Mutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic ElasticIps { get; set; } /// <summary> /// Hostname /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-hostname /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Hostname { get; set; } /// <summary> /// InstallUpdatesOnBoot /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-installupdatesonboot /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic InstallUpdatesOnBoot { get; set; } /// <summary> /// InstanceType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-instancetype /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic InstanceType { get; set; } /// <summary> /// LayerIds /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-layerids /// Required: True /// UpdateType: Mutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic LayerIds { get; set; } /// <summary> /// Os /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-os /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Os { get; set; } /// <summary> /// RootDeviceType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-rootdevicetype /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic RootDeviceType { get; set; } /// <summary> /// SshKeyName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-sshkeyname /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic SshKeyName { get; set; } /// <summary> /// StackId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-stackid /// Required: True /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic StackId { get; set; } /// <summary> /// SubnetId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-subnetid /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic SubnetId { get; set; } /// <summary> /// Tenancy /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-tenancy /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic Tenancy { get; set; } /// <summary> /// TimeBasedAutoScaling /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-timebasedautoscaling /// Required: False /// UpdateType: Immutable /// Type: TimeBasedAutoScaling /// </summary> public TimeBasedAutoScaling TimeBasedAutoScaling { get; set; } /// <summary> /// VirtualizationType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-virtualizationtype /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic VirtualizationType { get; set; } /// <summary> /// Volumes /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-volumes /// Required: False /// UpdateType: Mutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic Volumes { get; set; } } namespace InstanceTypes { public class BlockDeviceMapping { /// <summary> /// DeviceName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-blockdevicemapping.html#cfn-opsworks-instance-blockdevicemapping-devicename /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic DeviceName { get; set; } /// <summary> /// Ebs /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-blockdevicemapping.html#cfn-opsworks-instance-blockdevicemapping-ebs /// Required: False /// UpdateType: Mutable /// Type: EbsBlockDevice /// </summary> public EbsBlockDevice Ebs { get; set; } /// <summary> /// NoDevice /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-blockdevicemapping.html#cfn-opsworks-instance-blockdevicemapping-nodevice /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic NoDevice { get; set; } /// <summary> /// VirtualName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-blockdevicemapping.html#cfn-opsworks-instance-blockdevicemapping-virtualname /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic VirtualName { get; set; } } public class EbsBlockDevice { /// <summary> /// DeleteOnTermination /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-deleteontermination /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic DeleteOnTermination { get; set; } /// <summary> /// Iops /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-iops /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic Iops { get; set; } /// <summary> /// SnapshotId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-snapshotid /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic SnapshotId { get; set; } /// <summary> /// VolumeSize /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-volumesize /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic VolumeSize { get; set; } /// <summary> /// VolumeType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-volumetype /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic VolumeType { get; set; } } public class TimeBasedAutoScaling { /// <summary> /// Friday /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-friday /// Required: False /// UpdateType: Mutable /// Type: Map /// PrimitiveItemType: String /// </summary> public Dictionary<string, dynamic> Friday { get; set; } /// <summary> /// Monday /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-monday /// Required: False /// UpdateType: Mutable /// Type: Map /// PrimitiveItemType: String /// </summary> public Dictionary<string, dynamic> Monday { get; set; } /// <summary> /// Saturday /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-saturday /// Required: False /// UpdateType: Mutable /// Type: Map /// PrimitiveItemType: String /// </summary> public Dictionary<string, dynamic> Saturday { get; set; } /// <summary> /// Sunday /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-sunday /// Required: False /// UpdateType: Mutable /// Type: Map /// PrimitiveItemType: String /// </summary> public Dictionary<string, dynamic> Sunday { get; set; } /// <summary> /// Thursday /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-thursday /// Required: False /// UpdateType: Mutable /// Type: Map /// PrimitiveItemType: String /// </summary> public Dictionary<string, dynamic> Thursday { get; set; } /// <summary> /// Tuesday /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-tuesday /// Required: False /// UpdateType: Mutable /// Type: Map /// PrimitiveItemType: String /// </summary> public Dictionary<string, dynamic> Tuesday { get; set; } /// <summary> /// Wednesday /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-wednesday /// Required: False /// UpdateType: Mutable /// Type: Map /// PrimitiveItemType: String /// </summary> public Dictionary<string, dynamic> Wednesday { get; set; } } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace Hydra.Framework.Geometric { // //********************************************************************** /// <summary> /// Internal Representation of a Polygon /// </summary> //********************************************************************** // public class PolygonObject : IMapviewObject, ICloneable, IPersist { #region Private Member Variables // //********************************************************************** /// <summary> /// Graphics Event /// </summary> //********************************************************************** // public event GraphicEvents GraphicSelected; // //********************************************************************** /// <summary> /// List of Points /// </summary> //********************************************************************** // public ArrayList m_points = new ArrayList(); // //********************************************************************** /// <summary> /// Is Selected /// </summary> //********************************************************************** // private bool isselected = false; // //********************************************************************** /// <summary> /// Is Filled /// </summary> //********************************************************************** // private bool isfilled = true; // //********************************************************************** /// <summary> /// Is Visible /// </summary> //********************************************************************** // private bool visible = true; // //********************************************************************** /// <summary> /// Show ToolTip /// </summary> //********************************************************************** // private bool showtooptip = false; // //********************************************************************** /// <summary> /// Is Current /// </summary> //********************************************************************** // private bool iscurrent = true; // //********************************************************************** /// <summary> /// Is Locked /// </summary> //********************************************************************** // private bool islocked = false; // //********************************************************************** /// <summary> /// Is Disabled /// </summary> //********************************************************************** // private bool isdisabled = false; // //********************************************************************** /// <summary> /// Show Handle /// </summary> //********************************************************************** // private bool showhandle = false; // //********************************************************************** /// <summary> /// Size of Handle /// </summary> //********************************************************************** // private int handlesize = 6; // //********************************************************************** /// <summary> /// Fill Colour /// </summary> //********************************************************************** // private Color fillcolor = Color.Cyan; // //********************************************************************** /// <summary> /// Normal Colour /// </summary> //********************************************************************** // private Color normalcolor = Color.Yellow; // //********************************************************************** /// <summary> /// Selected Colour /// </summary> //********************************************************************** // private Color selectcolor = Color.Red; // //********************************************************************** /// <summary> /// Disabled Colour /// </summary> //********************************************************************** // private Color disabledcolor = Color.Gray; // //********************************************************************** /// <summary> /// Line Width /// </summary> //********************************************************************** // private int linewidth = 2; // //********************************************************************** /// <summary> /// List of Floating Points /// </summary> //********************************************************************** // public PointF[] points; // //********************************************************************** /// <summary> /// Xml String /// </summary> //********************************************************************** // private string xml = ""; #endregion #region Constructors // //********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="PolygonObject"/> class. /// </summary> //********************************************************************** // public PolygonObject() { } // //********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="T:PolygonObject"/> class. /// </summary> /// <param name="points">The points.</param> //********************************************************************** // public PolygonObject(ArrayList points) { m_points.Clear(); foreach (PointF item in points) { m_points.Add(item); } } // //********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="T:PolygonObject"/> class. /// </summary> /// <param name="points">The points.</param> //********************************************************************** // public PolygonObject(PointF[] points) { m_points.Clear(); foreach (PointF item in points) { m_points.Add(item); } } // //********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="T:PolygonObject"/> class. /// </summary> /// <param name="po">The po.</param> //********************************************************************** // public PolygonObject(PolygonObject po) { } #endregion of Polygon Object #region ICloneable Implementation // //********************************************************************** /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> //********************************************************************** // public object Clone() { return new PolygonObject(this); } #endregion #region Properties // //********************************************************************** /// <summary> /// Gets or sets the vertices. /// </summary> /// <value>The vertices.</value> //********************************************************************** // public PointF[] Vertices { get { return points; } set { points = value; } } // //********************************************************************** /// <summary> /// Gets or sets the color of the disabled. /// </summary> /// <value>The color of the disabled.</value> //********************************************************************** // [Category("Colors"), Description("The disabled Polygon object will be drawn using this pen")] public Color DisabledColor { get { return disabledcolor; } set { disabledcolor = value; } } // //********************************************************************** /// <summary> /// Gets or sets the color of the select. /// </summary> /// <value>The color of the select.</value> //********************************************************************** // [Category("Colors"), Description("The selected Polygon object willbe drawn using this pen")] public Color SelectColor { get { return selectcolor; } set { selectcolor = value; } } // //********************************************************************** /// <summary> /// Gets or sets the color of the normal. /// </summary> /// <value>The color of the normal.</value> //********************************************************************** // [Category("Colors"), Description("The Polygon object willbe drawn using this pen")] public Color NormalColor { get { return normalcolor; } set { normalcolor = value; } } // //********************************************************************** /// <summary> /// Gets or sets the width of the line. /// </summary> /// <value>The width of the line.</value> //********************************************************************** // [DefaultValue(2), Category("AbstractStyle"), Description("The gives the line thickness of the Polygon object")] public int LineWidth { get { return linewidth; } set { linewidth = value; } } // //********************************************************************** /// <summary> /// Gets or sets a value indicating whether this instance is filled. /// </summary> /// <value><c>true</c> if this instance is filled; otherwise, <c>false</c>.</value> //********************************************************************** // [Category("Appearance"), Description("The Polygon object will be filled with a given color or pattern")] public bool IsFilled { get { return isfilled; } set { isfilled = value; } } // //********************************************************************** /// <summary> /// Determines whether the object is visible or not /// </summary> /// <value></value> //********************************************************************** // [Category("Appearance"), Description("Determines whether the Polygon object is visible or hidden")] public bool Visible { get { return visible; } set { visible = value; } } // //********************************************************************** /// <summary> /// Determines whether the tool tip to be shown or not /// </summary> /// <value></value> //********************************************************************** // [Category("Appearance"), Description("Determines whether the tooltip information of the Polygon object to be shown or not")] public bool ShowToopTip { get { return showtooptip; } set { showtooptip = value; } } // //********************************************************************** /// <summary> /// Determines whether the object is in the current layer or not /// </summary> /// <value></value> //********************************************************************** // [Category("Appearance"), Description("Determines whether the Polygon object is in current selected legend or not")] public bool IsCurrent { get { return iscurrent; } set { iscurrent = value; } } // //********************************************************************** /// <summary> /// Determins whether the object is locked or not /// </summary> /// <value></value> //********************************************************************** // [Category("Appearance"), Description("Determines whether the Polygon object is locked from the current user or not")] public bool IsLocked { get { return islocked; } set { islocked = value; } } // //********************************************************************** /// <summary> /// Gets or sets a value indicating whether this instance is disabled. /// </summary> /// <value> /// <c>true</c> if this instance is disabled; otherwise, <c>false</c>. /// </value> //********************************************************************** // [Category("Appearance"), Description("Determines whether the Polygon object is disabled from editing")] public bool IsDisabled { get { return isdisabled; } set { isdisabled = value; } } // //********************************************************************** /// <summary> /// Returns true if the shape is in edit mode /// </summary> /// <value></value> /// <returns></returns> //********************************************************************** // [Category("Appearance"), Description("Determines whether the object is in edit mode")] public bool IsEdit { get { return showhandle; } set { isselected = true; showhandle = value; } } #endregion #region Public Methods // //********************************************************************** /// <summary> /// Returns true if the shape is selected /// </summary> /// <returns>true or false</returns> //********************************************************************** // public bool IsSelected() { return isselected; } // //********************************************************************** /// <summary> /// Select the shape if parameter is true. Deselect otherwice. /// </summary> /// <param name="m">selection flag</param> //********************************************************************** // public void Select(bool m) { isselected = m; } // //********************************************************************** /// <summary> /// Returns true if point close to the shape by specified distance /// </summary> /// <param name="pnt">source point</param> /// <param name="dist">distance between shape and point</param> /// <returns></returns> //********************************************************************** // public bool IsObjectAt(PointF pnt, float dist) { double min_dist = 100000; for (int i = 0; i < m_points.Count - 1; i++) { PointF p1 = (PointF)m_points[i]; PointF p2 = (PointF)m_points[i + 1]; double curr_dist = GeoUtil.DistanceBetweenPointToSegment(p1, p2, pnt); if (min_dist > curr_dist) min_dist = curr_dist; } return Math.Sqrt(min_dist) < dist; } // //********************************************************************** /// <summary> /// Inserts the specified pt. /// </summary> /// <param name="pt">The pt.</param> //********************************************************************** // public void Insert(PointF pt) { double min_dist = 100000; int iAt = 0; for (int i = 0; i < m_points.Count - 1; i++) { PointF p1 = (PointF)m_points[i]; PointF p2 = (PointF)m_points[i + 1]; double curr_dist = GeoUtil.DistanceBetweenPointToSegment(p1, p2, pt); if (min_dist > curr_dist) { min_dist = curr_dist; iAt = i; } } Insert(pt, iAt); } // //********************************************************************** /// <summary> /// Inserts the specified pt. /// </summary> /// <param name="pt">The pt.</param> /// <param name="i">The i.</param> //********************************************************************** // public void Insert(PointF pt, int i) { m_points.Insert(i, pt); } // //********************************************************************** /// <summary> /// Inserts the specified pt. /// </summary> /// <param name="pt">The pt.</param> /// <param name="i">The i.</param> //********************************************************************** // public void Insert(PointF[] pt, int i) { m_points.InsertRange(i, pt); } // //********************************************************************** /// <summary> /// calculate shape bounding box. /// </summary> /// <returns>bounding box rectangle</returns> //********************************************************************** // public Rectangle BoundingBox() { int x1 = (int)((PointF)(m_points[0])).X; int y1 = (int)((PointF)(m_points[0])).Y; int x2 = (int)((PointF)(m_points[0])).X; int y2 = (int)((PointF)(m_points[0])).Y; for (int i = 0; i < m_points.Count; i++) { if ((int)((PointF)m_points[i]).X < x1) x1 = (int)((PointF)m_points[i]).X; else if ((int)((PointF)m_points[i]).X > x2) x2 = (int)((PointF)m_points[i]).X; if ((int)((PointF)m_points[i]).Y < y1) y1 = (int)((PointF)m_points[i]).Y; else if ((int)((PointF)m_points[i]).Y > y2) y2 = (int)((PointF)m_points[i]).Y; } return new Rectangle((int)x1, (int)y1, (int)x2, (int)y2); } // //********************************************************************** /// <summary> /// get start point X /// </summary> /// <returns>X</returns> //********************************************************************** // public float X() { return ((PointF)m_points[0]).X; } // //********************************************************************** /// <summary> /// get start point Y /// </summary> /// <returns>Y</returns> //********************************************************************** // public float Y() { return ((PointF)m_points[0]).Y; } // //********************************************************************** /// <summary> /// Move shape to the point p. /// </summary> /// <param name="p">destination point</param> //********************************************************************** // public void Move(PointF p) { float dx = p.X - ((PointF)m_points[0]).X; float dy = p.Y - ((PointF)m_points[0]).Y; for (int i = 0; i < m_points.Count; i++) { PointF cp = new PointF(((PointF)m_points[i]).X + dx, ((PointF)m_points[i]).Y + dy); m_points[i] = cp; } } // //********************************************************************** /// <summary> /// Moves the by. /// </summary> /// <param name="dx">The dx.</param> /// <param name="dy">The dy.</param> //********************************************************************** // public void MoveBy(float dx, float dy) { for (int i = 0; i < m_points.Count; i++) { PointF cp = new PointF(((PointF)m_points[i]).X + dx, ((PointF)m_points[i]).Y + dy); m_points[i] = cp; } } // //********************************************************************** /// <summary> /// Scales the specified scale. /// </summary> /// <param name="scale">The scale.</param> //********************************************************************** // public void Scale(int scale) { for (int i = 0; i < m_points.Count; i++) { PointF cp = new PointF(((PointF)m_points[i]).X * scale, ((PointF)m_points[i]).Y + scale); m_points[i] = cp; } } // //********************************************************************** /// <summary> /// Rotates the specified radians. /// </summary> /// <param name="radians">The radians.</param> //********************************************************************** // public void Rotate(float radians) { // } // //********************************************************************** /// <summary> /// Rotates at. /// </summary> /// <param name="pt">The pt.</param> //********************************************************************** // public void RotateAt(PointF pt) { // } // //********************************************************************** /// <summary> /// Roates at. /// </summary> /// <param name="pt">The pt.</param> //********************************************************************** // public void RoateAt(Point pt) { // } // //********************************************************************** /// <summary> /// Draw shape on graphic device. /// Shape stored in "real world" coordinates, converted /// to client (graphic window) coordinate system and drawn /// on graphic device /// </summary> /// <param name="graph">graphic device</param> /// <param name="trans">real to client transformation</param> //********************************************************************** // public void Draw(Graphics graph, System.Drawing.Drawing2D.Matrix trans) { if (visible) { // // create 0,0 and width,height points // PointF[] points = new PointF[m_points.Count]; m_points.CopyTo(0, points, 0, m_points.Count); trans.TransformPoints(points); if (isdisabled || islocked) { graph.DrawPolygon(new Pen(disabledcolor, linewidth), points); } if (isselected) { graph.DrawPolygon(new Pen(selectcolor, linewidth), points); if (showhandle) { for (int i = 0; i < m_points.Count; i++) { graph.FillRectangle(new SolidBrush(fillcolor), points[i].X - handlesize / 2, points[i].Y - handlesize / 2, handlesize, handlesize); graph.DrawRectangle(new Pen(Color.Black, 1), points[i].X - handlesize / 2, points[i].Y - handlesize / 2, handlesize, handlesize); } PointF pc = Centroid(); graph.FillRectangle(new SolidBrush(Color.Red), pc.X - handlesize / 2, pc.Y - handlesize / 2, handlesize, handlesize); graph.DrawRectangle(new Pen(Color.Black, 1), pc.X - handlesize / 2, pc.Y - handlesize / 2, handlesize, handlesize); } } else if (isfilled) { graph.FillPolygon(new SolidBrush(fillcolor), points); graph.DrawPolygon(new Pen(normalcolor, linewidth), points); } else { graph.DrawPolygon(new Pen(normalcolor, linewidth), points); } } } // //********************************************************************** /// <summary> /// Polygons the area. /// </summary> /// <returns></returns> //********************************************************************** // public float PolygonArea() { // // Return the absolute value of the signed area. // The signed area is negative if the polyogn is // oriented clockwise. // return Math.Abs(SignedPolygonArea()); } // //********************************************************************** /// <summary> /// Find the polygon's centroid. /// </summary> /// <returns></returns> //********************************************************************** // public PointF Centroid() { float second_factor = 0.0F; float polygon_area = 0.0F; PointF pout = new PointF(0, 0); // // Find the centroid. // for (int i = 0; i < m_points.Count - 1; i++) { second_factor = (((PointF)m_points[i]).X * ((PointF)m_points[i + 1]).Y) - (((PointF)m_points[i + 1]).X * ((PointF)m_points[i]).Y); pout.X = pout.X + (((PointF)m_points[i]).X + ((PointF)m_points[i + 1]).X) * second_factor; pout.Y = pout.Y + (((PointF)m_points[i]).Y + ((PointF)m_points[i + 1]).Y) * second_factor; } // // Divide by 6 times the polygon's area. // polygon_area = PolygonArea(); pout.X = pout.X / (6.0F * polygon_area); pout.Y = pout.Y / (6.0F * polygon_area); // // If the values are negative, the polygon is // oriented counterclockwise. Reverse the signs. // if (pout.X < 0) { pout.X = -(pout.X); pout.Y = -(pout.Y); } return pout; } // //********************************************************************** /// <summary> /// Signeds the polygon area. /// </summary> /// <returns></returns> //********************************************************************** // private float SignedPolygonArea() { // // Return the polygon's area in "square" pixels. // Add the areas of the trapezoids defined by the // polygon's edges dropped to the X-axis. When the // program considers a bottom edge of a polygon, the // calculation gives a negative area so the space // between the polygon and the axis is subtracted, // leaving the polygon's area. This method gives odd // results for non-simple polygons. // // The value will be negative if the polyogn is // oriented clockwise. // float area = 0.0F; // // Get the areas. // for (int i = 0; i < m_points.Count - 1; i++) { area = area + (((PointF)m_points[i + 1]).X - ((PointF)m_points[i]).X) * (((PointF)m_points[i + 1]).Y + ((PointF)m_points[i]).Y) / 2; } // // Return the result. // return area; } // //********************************************************************** /// <summary> /// Points the in polygon. /// </summary> /// <param name="ptIn">The pt in.</param> /// <returns></returns> //********************************************************************** // public bool PointInPolygon(PointF ptIn) { //ByVal X As Single, ByVal Y As Single, ByVal num_polygon_points As Integer, polygon_points() As POINTAPI // Return True if the point is in the polygon. double total_angle = 0.0F; bool isvalid = false; if (m_points != null && m_points.Count > 0) { // // Get the angle between the point and the // first and last vertices. //total_angle = GeoUtil.GetAngle((PointF)m_points[m_points.Count]).X,((PointF)m_points[m_points.Count]).Y),ptIn.X,ptIn.Y,((PointF)m_points[1]).X,((PointF)polygon_points[1]).Y)); // total_angle = GeoUtil.GetAngle( ((PointF)m_points[m_points.Count - 1]).X, ((PointF)m_points[m_points.Count - 1]).Y, ptIn.X, ptIn.Y, ((PointF)m_points[0]).X, ((PointF)m_points[0]).Y); //' Add the angles from the point to each other //' pair of vertices. for (int i = 0; i < m_points.Count - 1; i++) { total_angle = total_angle + GeoUtil.GetAngle( ((PointF)m_points[i]).X, ((PointF)m_points[i]).Y, ptIn.X, ptIn.Y, ((PointF)m_points[i + 1]).X, ((PointF)m_points[i + 1]).Y); } } //' The total angle should be 2 * PI or -2 * PI if //' the point is in the polygon and close to zero //' if the point is outside the polygon isvalid = (Math.Abs(total_angle) > 0.000001); return isvalid; } // //********************************************************************** /// <summary> /// Insides the polygon. /// </summary> /// <param name="p">The p.</param> /// <returns></returns> //********************************************************************** // public bool InsidePolygon(PointF p) { int counter = 0; int i; double xinters; PointF p1; PointF p2; bool isValid = false; if (m_points != null && m_points.Count > 0) { p1 = ((PointF)m_points[0]); for (i = 1; i <= m_points.Count; i++) { p2 = ((PointF)m_points[i % m_points.Count]); if (p.Y > System.Math.Min(p1.Y, p2.Y)) { if (p.Y <= System.Math.Max(p1.Y, p2.Y)) { if (p.X <= System.Math.Max(p1.X, p2.X)) { if (p1.Y != p2.Y) { xinters = (p.Y - p1.Y) * (p2.X - p1.X) / (p2.Y - p1.Y) + p1.X; if (p1.X == p2.X || p.X <= xinters) counter++; } } } } p1 = p2; } isValid = (counter % 2 == 0) ? false : true; } return isValid; } // //********************************************************************** /// <summary> /// Triangulates this instance. /// </summary> //********************************************************************** // public void Triangulate() { // // Traingulate the polygon. // ArrayList tmpA=new ArrayList(m_points); // // // Orient the polygon. // OrientPolygonClockwise m_NumCopyPoints, m_CopyPoints // //' Repeat the first two points. //m_CopyPoints(m_NumCopyPoints + 1) = m_Points(1) //m_CopyPoints(m_NumCopyPoints + 2) = m_Points(2) // //'@ //For pt = 1 To m_NumCopyPoints //With m_CopyPoints(pt) //EditorForm.CurrentX = .X //EditorForm.CurrentY = .Y //EditorForm.Print pt //End With //Next pt //'@ // //' Make room for the triangles. //m_NumTriangles = 0 //ReDim m_Triangles(1 To m_NumPoints - 2) // //' While the copy of the polygon has more than //' three points, remove an ear. //Do While m_NumCopyPoints > 3 //' Remove an ear from the polygon. //RemoveEar //Loop // //' Copy the last three points into their own triangle. //m_NumTriangles = m_NumTriangles + 1 //With m_Triangles(m_NumTriangles) //For pt = 1 To 3 //.Points(pt) = m_CopyPoints(pt) //Next pt // End With } #endregion #region IPersist Implementation // //********************************************************************** /// <summary> /// Gets or sets to XML. /// </summary> /// <value>To XML.</value> //********************************************************************** // public string ToXML { get { return xml; } set { xml = value; } } // //********************************************************************** /// <summary> /// Gets or sets to GML. /// </summary> /// <value>To GML.</value> //********************************************************************** // public string ToGML { get { return xml; } set { xml = value; } } // //********************************************************************** /// <summary> /// Gets or sets to VML. /// </summary> /// <value>To VML.</value> //********************************************************************** // public string ToVML { get { return xml; } set { xml = value; } } // //********************************************************************** /// <summary> /// Gets or sets to SVG. /// </summary> /// <value>To SVG.</value> //********************************************************************** // public string ToSVG { get { string spoints = ""; for (int i = 0; i < m_points.Count - 1; i++) { spoints = ((PointF)m_points[i]).X + "," + ((PointF)m_points[i]).Y + " "; } return "<polyline fill='none' stroke=" + normalcolor + " stroke-width=" + linewidth + " points=" + spoints + " />"; } set { xml = value; } } #endregion } }
#region Author /* Name: * Created On: * Created by: * Purpose * Modified on: */ #endregion using System; using System.Data; using System.Configuration; using System.Web; using System.Data.SqlClient; using System.Collections.Generic; using DSL.POS.DataAccessLayer.Common.Imp; using DSL.POS.DataAccessLayer.Interface; using DSL.POS.DTO.DTO; namespace DSL.POS.DataAccessLayer.Imp { /// <summary> /// Summary description for ProductInfoDALImp /// </summary> public class ProductInfoDALImp : CommonDALImp, IProductInfoDAL { private static ProductInfoDALImp pInfo = new ProductInfoDALImp(); public static ProductInfoDALImp GetInstance() { return pInfo; } private string Get_NewProductInfoCode(ProductInfoDTO dto) { string pcCode = null; //2 string pscCode = null; //3 string pbCode = null; //4 // generate Product Code combination of Year+Month+Day+Hour+Minute+Second pscCode = Convert.ToString(DateTime.Today.Day.ToString("00")+1); pbCode = Convert.ToString(DateTime.Today.Year); string pCode = null; //13 int pCodeNo = 0; SqlConnection objMyCon = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = new SqlCommand(); objCmd.CommandText = "SELECT PC_Code FROM ProductCategoryInfo WHERE (PC_PK = @PC_PK)"; objCmd.Parameters.Add(new SqlParameter("@PC_PK", SqlDbType.UniqueIdentifier, 16)); objCmd.Parameters["@PC_PK"].Value = (Guid)dto.PC_PrimaryKey; objMyCon.Open(); objCmd.Connection = objMyCon; pcCode = (string)objCmd.ExecuteScalar(); objMyCon.Close(); //objCmd.CommandText = "SELECT PSC_Code FROM ProductSubCategoryInfo WHERE (PSC_PK = @PSC_PK)"; //objCmd.Parameters.Add(new SqlParameter("@PSC_PK", SqlDbType.UniqueIdentifier, 16)); //objCmd.Parameters["@PSC_PK"].Value = (Guid)dto.PSC_PrimaryKey; //objMyCon.Open(); //objCmd.Connection = objMyCon; //pscCode = (string)objCmd.ExecuteScalar(); //objMyCon.Close(); //objCmd.CommandText = "SELECT PB_Code FROM ProductBrandInfo WHERE (PB_PK = @PB_PK)"; //objCmd.Parameters.Add(new SqlParameter("@PB_PK", SqlDbType.UniqueIdentifier, 16)); //objCmd.Parameters["@PB_PK"].Value = (Guid)dto.PB_PrimaryKey; //objMyCon.Open(); //objCmd.Connection = objMyCon; //pbCode = (string)objCmd.ExecuteScalar(); //objMyCon.Close(); objCmd.CommandText = "SELECT ISNULL(MAX(CAST(RIGHT(P_Code, 4) AS int)), 0) + 1 FROM ProductInfo " + "WHERE (SUBSTRING(P_Code, 1, 2) = @pcCode) " + "AND (SUBSTRING(P_Code, 3, 3) = @pscCode) " + "AND (SUBSTRING(P_Code, 6, 4) = @pbCode)"; objCmd.Parameters.Add(new SqlParameter("@pcCode", SqlDbType.VarChar, 2)); objCmd.Parameters["@pcCode"].Value = (string)pcCode; objCmd.Parameters.Add(new SqlParameter("@pscCode", SqlDbType.VarChar, 3)); objCmd.Parameters["@pscCode"].Value = (string)pscCode; objCmd.Parameters.Add(new SqlParameter("@pbCode", SqlDbType.VarChar, 4)); objCmd.Parameters["@pbCode"].Value = (string)pbCode; objMyCon.Open(); objCmd.Connection = objMyCon; pCodeNo = (int)objCmd.ExecuteScalar(); objMyCon.Close(); pCode = pcCode + pscCode + pbCode + pCodeNo.ToString("0000"); return pCode; } public override void Save(object Obj) { ProductInfoDTO dto = (ProductInfoDTO)Obj; SqlConnection objMyCon = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = new SqlCommand(); if (dto.PrimaryKey.ToString() == "00000000-0000-0000-0000-000000000000") { dto.P_Code = Get_NewProductInfoCode(dto); objCmd.CommandText = "Insert Into ProductInfo(PC_PK,PSC_PK,PB_PK,P_Code,P_Name,P_Style,P_SalesPrice,P_CostPrice,P_Tax,P_VAT,P_Discount,P_MinLevel,P_MaxLevel,P_ReorderLevel,P_Status,P_SalesPriceDate,P_CostPriceDate,P_Warranty,P_WarrantyMonth,PU_PK,EntryBy,EntryDate) Values(@PC_PK,@PSC_PK,@PB_PK,@P_Code,@P_Name,@P_Style,@P_SalesPrice,@P_CostPrice,@P_Tax,@P_VAT,@P_Discount,@P_MinLevel,@P_MaxLevel,@P_ReorderLevel,@P_Status,@P_SalesPriceDate,@P_CostPriceDate,@P_Warranty,@P_WarrantyMonth,@PU_PK,@EntryBy,@EntryDate)"; } else { objCmd.CommandText = "Update ProductInfo Set PC_PK=@PC_PK,PSC_PK=@PSC_PK,PB_PK=@PB_PK,P_Code=@P_Code,P_Name=@P_Name,P_Style=@P_Style,P_SalesPrice=@P_SalesPrice,P_CostPrice=@P_CostPrice,P_Tax=@P_Tax,P_VAT=@P_VAT,P_Discount=@P_Discount,P_MinLevel=@P_MinLevel,P_MaxLevel=@P_MaxLevel,P_ReorderLevel=@P_ReorderLevel,P_Status=@P_Status,P_SalesPriceDate=@P_SalesPriceDate,P_CostPriceDate=@P_CostPriceDate,P_Warranty=@P_Warranty,P_WarrantyMonth=@P_WarrantyMonth,PU_PK=@PU_PK,EntryBy=@EntryBy,EntryDate=@EntryDate Where P_PK=@P_PK"; objCmd.Parameters.Add(new SqlParameter("@P_PK", SqlDbType.UniqueIdentifier, 16)); objCmd.Parameters["@P_PK"].Value = (Guid)dto.PrimaryKey; } objCmd.Parameters.Add(new SqlParameter("@PC_PK", SqlDbType.UniqueIdentifier, 16)); objCmd.Parameters.Add(new SqlParameter("@PSC_PK", SqlDbType.UniqueIdentifier, 16)); objCmd.Parameters.Add(new SqlParameter("@PB_PK", SqlDbType.UniqueIdentifier, 16)); objCmd.Parameters.Add(new SqlParameter("@PU_PK", SqlDbType.UniqueIdentifier, 16)); objCmd.Parameters.Add(new SqlParameter("@P_Code", SqlDbType.VarChar, 13)); objCmd.Parameters.Add(new SqlParameter("@P_Name", SqlDbType.VarChar, 50)); objCmd.Parameters.Add(new SqlParameter("@P_Style", SqlDbType.VarChar, 100)); objCmd.Parameters.Add(new SqlParameter("@P_SalesPrice", SqlDbType.Decimal, 9)); objCmd.Parameters.Add(new SqlParameter("@P_CostPrice", SqlDbType.Decimal, 9)); objCmd.Parameters.Add(new SqlParameter("@P_Tax", SqlDbType.Decimal, 9)); objCmd.Parameters.Add(new SqlParameter("@P_VAT", SqlDbType.Decimal, 9)); objCmd.Parameters.Add(new SqlParameter("@P_Discount", SqlDbType.Decimal, 9)); objCmd.Parameters.Add(new SqlParameter("@P_MinLevel", SqlDbType.Decimal, 9)); objCmd.Parameters.Add(new SqlParameter("@P_MaxLevel", SqlDbType.Decimal, 9)); objCmd.Parameters.Add(new SqlParameter("@P_ReorderLevel", SqlDbType.Decimal, 9)); objCmd.Parameters.Add(new SqlParameter("@P_Status", SqlDbType.Bit, 1)); objCmd.Parameters.Add(new SqlParameter("@P_SalesPriceDate", SqlDbType.DateTime, 8)); objCmd.Parameters.Add(new SqlParameter("@P_CostPriceDate", SqlDbType.DateTime, 8)); objCmd.Parameters.Add(new SqlParameter("@P_Warranty", SqlDbType.Bit, 1)); objCmd.Parameters.Add(new SqlParameter("@P_WarrantyMonth", SqlDbType.Int, 4)); objCmd.Parameters.Add(new SqlParameter("@EntryBy", SqlDbType.VarChar, 6)); objCmd.Parameters.Add(new SqlParameter("@EntryDate", SqlDbType.DateTime, 8)); objCmd.Parameters["@PC_PK"].Value = (Guid)dto.PC_PrimaryKey; objCmd.Parameters["@PSC_PK"].Value = (Guid)dto.PSC_PrimaryKey; objCmd.Parameters["@PB_PK"].Value = (Guid)dto.PB_PrimaryKey; objCmd.Parameters["@PU_PK"].Value = (Guid)dto.PU_PrimaryKey; objCmd.Parameters["@P_Code"].Value = (string)dto.P_Code; objCmd.Parameters["@P_Name"].Value = (string)dto.P_Name; objCmd.Parameters["@P_Style"].Value = (string)dto.P_Style; objCmd.Parameters["@P_SalesPrice"].Value = Convert.ToDecimal(dto.P_SalesPrice); objCmd.Parameters["@P_CostPrice"].Value = Convert.ToDecimal(dto.P_CostPrice); objCmd.Parameters["@P_Tax"].Value = Convert.ToDecimal(dto.P_Tax); objCmd.Parameters["@P_VAT"].Value = Convert.ToDecimal(dto.P_VAT); objCmd.Parameters["@P_Discount"].Value = Convert.ToDecimal(dto.P_Discount); objCmd.Parameters["@P_MinLevel"].Value = Convert.ToDecimal(dto.P_MinLevel); objCmd.Parameters["@P_MaxLevel"].Value = Convert.ToDecimal(dto.P_MaxLevel); objCmd.Parameters["@P_ReorderLevel"].Value = Convert.ToDecimal(dto.P_ReorderLevel); objCmd.Parameters["@P_Status"].Value = Convert.ToBoolean(dto.P_Status); objCmd.Parameters["@P_SalesPriceDate"].Value = (DateTime)dto.P_SalesPriceDate; objCmd.Parameters["@P_CostPriceDate"].Value = (DateTime)dto.P_CostPriceDate; objCmd.Parameters["@P_Warranty"].Value = Convert.ToBoolean(dto.P_Warranty); objCmd.Parameters["@P_WarrantyMonth"].Value = Convert.ToDecimal(dto.P_WarrantyMonth); objCmd.Parameters["@EntryBy"].Value = (string)dto.EntryBy; objCmd.Parameters["@EntryDate"].Value = (DateTime)dto.EntryDate; objCmd.Connection = objMyCon; objMyCon.Open(); objCmd.ExecuteNonQuery(); objMyCon.Close(); } public override void Delete(object obj) { ProductInfoDTO pDto = (ProductInfoDTO)obj; SqlConnection objmycon = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objcmd = new SqlCommand(); objcmd.CommandText = "Delete From ProductInfo WHERE P_PK=@P_PK"; objcmd.Parameters.Add(new SqlParameter("@P_PK", SqlDbType.UniqueIdentifier, 16)); objcmd.Parameters["@P_PK"].Value = (Guid)pDto.PrimaryKey; objcmd.Connection = objmycon; try { objmycon.Open(); objcmd.ExecuteNonQuery(); } catch (Exception Exp) { throw Exp; } finally { objmycon.Close(); } } public List<ProductInfoDTO> GetProductInfo() { List<ProductInfoDTO> productInfoList = new List<ProductInfoDTO>(); SqlDataReader DR; SqlConnection objMyCon = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = new SqlCommand(); objCmd.Connection = objMyCon; objCmd.CommandText = "SELECT ProductInfo.P_PK, ProductInfo.P_Code, ProductInfo.PC_PK, ProductInfo.PSC_PK, ProductInfo.PB_PK, ProductInfo.P_Name, ProductInfo.P_Style, "+ "ProductInfo.P_SalesPrice, ProductInfo.P_CostPrice, ProductInfo.P_Tax, ProductInfo.P_VAT, ProductInfo.P_Discount, ProductInfo.P_MinLevel, "+ "ProductInfo.P_MaxLevel, ProductInfo.P_ReorderLevel, ProductInfo.P_Status, ProductInfo.P_SalesPricedate, ProductInfo.P_CostPricedate, "+ "ProductInfo.P_Warranty, ProductInfo.P_WarrantyMonth, ProductInfo.PU_PK, ProductInfo.EntryBy, ProductInfo.EntryDate, "+ "ProductCategoryInfo.PC_Description "+ "FROM ProductInfo INNER JOIN "+ "ProductCategoryInfo ON ProductInfo.PC_PK = ProductCategoryInfo.PC_PK "+ "ORDER BY ProductInfo.P_Code DESC "; //objCmd.CommandText = "SELECT ProductInfo.P_PK, ProductInfo.P_Code, ProductInfo.PC_PK, ProductInfo.PSC_PK, ProductInfo.PB_PK, ProductInfo.P_Name, ProductInfo.P_Style, " + // "ProductInfo.P_SalesPrice, ProductInfo.P_CostPrice, ProductInfo.P_Tax, ProductInfo.P_VAT, ProductInfo.P_Discount, ProductInfo.P_MinLevel, " + // "ProductInfo.P_MaxLevel, ProductInfo.P_ReorderLevel, ProductInfo.P_status, ProductInfo.P_SalesPricedate, ProductInfo.P_CostPricedate, " + // "ProductInfo.P_Warranty, ProductInfo.P_WarrantyMonth, ProductInfo.PU_PK, ProductInfo.EntryBy, ProductInfo.EntryDate, " + // "ProductCategoryInfo.PC_Description, ProductSubCategoryInfo.PSC_Description, ProductBrandInfo.PB_Name, ProductUnitInfo.PU_Name " + // "FROM ProductInfo INNER JOIN " + // "ProductCategoryInfo ON ProductInfo.PC_PK = ProductCategoryInfo.PC_PK " + // "ProductBrandInfo ON ProductInfo.PB_PK = ProductBrandInfo.PB_PK INNER JOIN " + // "ProductUnitInfo ON ProductInfo.PU_PK = ProductUnitInfo.PU_PK INNER JOIN " + // "ProductSubCategoryInfo ON ProductInfo.PSC_PK = ProductSubCategoryInfo.PSC_PK " + // "ORDER BY ProductInfo.P_Code DESC"; try { objMyCon.Open(); DR = objCmd.ExecuteReader(); while (DR.Read()) { ProductInfoDTO pDto = new ProductInfoDTO(); pDto.PrimaryKey = (Guid)DR[0]; pDto.P_Code = (string)DR[1]; pDto.PC_PrimaryKey = (Guid)DR[2]; pDto.PSC_PrimaryKey = (Guid)DR[3]; pDto.PB_PrimaryKey = (Guid)DR[4]; pDto.P_Name = (string)DR[5]; pDto.P_Style = (string)DR[6]; pDto.P_SalesPrice = Convert.ToDecimal(DR[7]); pDto.P_CostPrice = Convert.ToDecimal(DR[8]); pDto.P_Tax = Convert.ToDecimal(DR[9]); pDto.P_VAT = Convert.ToDecimal(DR[10]); pDto.P_Discount = Convert.ToDecimal(DR[11]); pDto.P_MinLevel = Convert.ToDecimal(DR[12]); pDto.P_MaxLevel = Convert.ToDecimal(DR[13]); pDto.P_ReorderLevel = Convert.ToDecimal(DR[14]); pDto.P_Status = (Boolean)DR[15]; pDto.P_SalesPriceDate = (DateTime)DR[16]; pDto.P_CostPriceDate = (DateTime)DR[17]; pDto.P_Warranty = (Boolean)DR[18]; pDto.P_WarrantyMonth = (int)DR[19]; pDto.PU_PrimaryKey = (Guid)DR[20]; pDto.EntryBy = (string)DR[21]; pDto.EntryDate = (DateTime)DR[22]; productInfoList.Add(pDto); } DR.Close(); objMyCon.Close(); return productInfoList; } catch (Exception Exp) { throw Exp; } } public ProductInfoDTO FindByPK(Guid pk) { ProductInfoDTO pInfoDTO = new ProductInfoDTO(); string sqlSelect = "SELECT ProductInfo.P_PK, ProductInfo.P_Code, ProductInfo.PC_PK, ProductInfo.PSC_PK, ProductInfo.PB_PK, ProductInfo.P_Name, ProductInfo.P_Style, " + "ProductInfo.P_SalesPrice, ProductInfo.P_CostPrice, ProductInfo.P_Tax, ProductInfo.P_VAT, ProductInfo.P_Discount, ProductInfo.P_MinLevel, " + "ProductInfo.P_MaxLevel, ProductInfo.P_ReorderLevel, ProductInfo.P_Status, ProductInfo.P_SalesPricedate, ProductInfo.P_CostPricedate, " + "ProductInfo.P_Warranty, ProductInfo.P_WarrantyMonth, ProductInfo.PU_PK, ProductInfo.EntryBy, ProductInfo.EntryDate, " + "ProductCategoryInfo.PC_Description " + "FROM ProductInfo INNER JOIN " + "ProductCategoryInfo ON ProductInfo.PC_PK = ProductCategoryInfo.PC_PK " + "WHERE P_PK=@P_PK "; //string sqlSelect = "SELECT ProductInfo.P_PK, ProductInfo.P_Code, ProductInfo.PC_PK, ProductInfo.PSC_PK, ProductInfo.PB_PK, ProductInfo.P_Name, ProductInfo.P_Style, " + // "ProductInfo.P_SalesPrice, ProductInfo.P_CostPrice, ProductInfo.P_Tax, ProductInfo.P_VAT, ProductInfo.P_Discount, ProductInfo.P_MinLevel, " + // "ProductInfo.P_MaxLevel, ProductInfo.P_ReorderLevel, ProductInfo.P_status, ProductInfo.P_SalesPricedate, ProductInfo.P_CostPricedate, " + // "ProductInfo.P_Warranty, ProductInfo.P_WarrantyMonth, ProductInfo.PU_PK, ProductInfo.EntryBy, ProductInfo.EntryDate, " + // "ProductCategoryInfo.PC_Description, ProductSubCategoryInfo.PSC_Description, ProductBrandInfo.PB_Name, ProductUnitInfo.PU_Name " + // "FROM ProductInfo INNER JOIN " + // "ProductCategoryInfo ON ProductInfo.PC_PK = ProductCategoryInfo.PC_PK INNER JOIN " + // "ProductBrandInfo ON ProductInfo.PB_PK = ProductBrandInfo.PB_PK INNER JOIN " + // "ProductUnitInfo ON ProductInfo.PU_PK = ProductUnitInfo.PU_PK INNER JOIN " + // "ProductSubCategoryInfo ON ProductInfo.PSC_PK = ProductSubCategoryInfo.PSC_PK " + // "WHERE P_PK=@P_PK"; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = sqlConn.CreateCommand(); try { objCmd.CommandText = sqlSelect; objCmd.Connection = sqlConn; objCmd.Parameters.Add("@P_PK", SqlDbType.UniqueIdentifier, 16); objCmd.Parameters["@P_PK"].Value = pk; sqlConn.Open(); SqlDataReader thisReader = objCmd.ExecuteReader(); while (thisReader.Read()) { pInfoDTO = Populate(thisReader); } thisReader.Close(); thisReader.Dispose(); } catch (Exception Exp) { throw Exp; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } return pInfoDTO; } public ProductInfoDTO Populate(SqlDataReader reader) { try { ProductInfoDTO dto = new ProductInfoDTO(); dto.PrimaryKey = (Guid)reader["P_PK"]; dto.PC_PrimaryKey = (Guid)reader["PC_PK"]; dto.PSC_PrimaryKey = (Guid)reader["PSC_PK"]; dto.PB_PrimaryKey = (Guid)reader["PB_PK"]; dto.P_Code = (string)reader["P_Code"]; dto.P_Name = (string)reader["P_Name"]; dto.P_Style = (string)reader["P_Style"]; dto.P_SalesPrice = Convert.ToDecimal(reader["P_SalesPrice"]); dto.P_CostPrice = Convert.ToDecimal(reader["P_CostPrice"]); dto.P_Tax = Convert.ToDecimal(reader["P_Tax"]); dto.P_VAT = Convert.ToDecimal(reader["P_VAT"]); dto.P_Discount = Convert.ToDecimal(reader["P_Discount"]); dto.P_MinLevel = Convert.ToDecimal(reader["P_MinLevel"]); dto.P_MaxLevel = Convert.ToDecimal(reader["P_MaxLevel"]); dto.P_ReorderLevel = Convert.ToDecimal(reader["P_ReorderLevel"]); dto.P_Status = (Boolean)reader["P_Status"]; dto.P_SalesPriceDate = (DateTime)reader["P_SalesPricedate"]; dto.P_CostPriceDate = (DateTime)reader["P_CostPricedate"]; dto.P_Warranty = (Boolean)reader["P_Warranty"]; dto.P_WarrantyMonth = (int)reader["P_WarrantyMonth"]; dto.PU_PrimaryKey = (Guid)reader["PU_PK"]; dto.EntryBy = (string)reader["EntryBy"]; dto.EntryDate = (DateTime)reader["EntryDate"]; return dto; } catch (Exception Exp) { throw Exp; } } /// <summary> /// Get Primary Key corresponding Product Code /// </summary> /// <param name="strCode"></param> /// <returns> Primary Key</returns> /// public Guid GetPKBYCode(string strCode) { SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); Guid guidCust_ID = new Guid(); string sqlSelect = "Select P_PK From ProductInfo where P_Code=@P_Code"; SqlCommand objCmd = sqlConn.CreateCommand(); objCmd.CommandText = sqlSelect; objCmd.Parameters.Add("@P_Code", SqlDbType.VarChar, 13); objCmd.Parameters["@P_Code"].Value = strCode; try { sqlConn.Open(); SqlDataReader sqlDReader = objCmd.ExecuteReader(); if (sqlDReader.Read()) guidCust_ID = (Guid)sqlDReader["P_PK"]; //else // guidCust_ID = (Guid)"00000000-0000-0000-0000-000000000000"; } catch (Exception Exp) { throw Exp; } finally { objCmd.Dispose(); sqlConn.Dispose(); sqlConn.Close(); } return guidCust_ID; } public ProductInfoDALImp() { // // TODO: Add constructor logic here // } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Composition.Hosting; using System.Composition.Convention; using System.Linq; using System.Reflection; using System.Composition.Convention.UnitTests; using Xunit; namespace System.Composition.Convention { public class PartBuilderTests { private class MyDoNotIncludeAttribute : Attribute { } [MyDoNotIncludeAttribute] public class MyNotToBeIncludedClass { } public class MyToBeIncludedClass { } public class ImporterOfMyNotTobeIncludedClass { [Import(AllowDefault = true)] public MyNotToBeIncludedClass MyNotToBeIncludedClass { get; set; } [Import(AllowDefault = true)] public MyToBeIncludedClass MyToBeIncludedClass { get; set; } } public interface IFirst { } private interface IFoo { } private class FooImpl { public string P1 { get; set; } public string P2 { get; set; } public IEnumerable<IFoo> P3 { get; set; } } [Export] public class OnImportsSatisfiedTestClass { public int OnImportsSatisfiedInvoked = 0; [Import("P1", AllowDefault = true)] public string P1 { get; set; } [Import("P2", AllowDefault = true)] public string P2 { get; set; } public int OnImportsSatisfiedInvalidReturnValue() { return 1; } public void OnImportsSatisfiedInvalidArgs(int arg1) { } [OnImportsSatisfied] public void OnImportsSatisfied() { ++OnImportsSatisfiedInvoked; } } [Export] public class OnImportsSatisfiedMultipleClass { public int OnImportsSatisfiedInvoked = 0; [Import("P1", AllowDefault = true)] public string P1 { get; set; } [Import("P2", AllowDefault = true)] public string P2 { get; set; } public int OnImportsSatisfiedInvalidReturnValue() { return 1; } public void OnImportsSatisfiedInvalidArgs(int arg1) { } public void OnImportsSatisfied1() { OnImportsSatisfiedInvoked += 2; } public void OnImportsSatisfied2() { OnImportsSatisfiedInvoked += 4; } } [Export] public class OnImportsSatisfiedConfiguredClass { public int OnImportsSatisfiedInvoked = 0; [Import("P1", AllowDefault = true)] public string P1 { get; set; } [Import("P2", AllowDefault = true)] public string P2 { get; set; } public int OnImportsSatisfiedInvalidReturnValue() { return 1; } public void OnImportsSatisfiedInvalidArgs(int arg1) { } [OnImportsSatisfied] public void OnImportsSatisfied() { ++OnImportsSatisfiedInvoked; } } [Export] public class OnImportsSatisfiedDerivedClass : OnImportsSatisfiedTestClass { } [Export] public class OnImportsSatisfiedTestClassPropertiesAndFields { public int OnImportsSatisfiedInvoked = 0; [Import("P1", AllowDefault = true)] public string P1 { get; set; } [Import("P2", AllowDefault = true)] public string P2 { get; set; } public int OnImportsSatisfiedInvalidReturnValue() { return 1; } public void OnImportsSatisfiedInvalidArgs(int arg1) { } public int OnImportsSatisfied3; // Field public int OnImportsSatisfied4 { get; set; } // Property } public class ExportValues { public ExportValues() { P1 = "Hello, World from P1"; P2 = "Hello, World from P2"; } [Export("P1")] public string P1 { get; set; } [Export("P2")] public string P2 { get; set; } } private class FooImplWithConstructors { public FooImplWithConstructors() { } public FooImplWithConstructors(int id) { } public FooImplWithConstructors(IEnumerable<IFoo> ids) { } public FooImplWithConstructors(int id, string name) { } } private class FooImplWithConstructorsAmbiguous { public FooImplWithConstructorsAmbiguous(string name, int id) { } public FooImplWithConstructorsAmbiguous(int id, string name) { } } [Fact] public void NoOperations_ShouldGenerateNoAttributes() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImpl)); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ExportSelf_ShouldGenerateSingleExportAttribute() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImpl)).Export(); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(1, attributes.Count()); Assert.NotNull(attributes[0] as ExportAttribute); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ExportOfT_ShouldGenerateSingleExportAttributeWithContractType() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImpl)).Export<IFoo>(); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(1, attributes.Count()); var exportAttribute = attributes[0] as ExportAttribute; Assert.NotNull(exportAttribute); Assert.Equal(typeof(IFoo), exportAttribute.ContractType); Assert.Null(exportAttribute.ContractName); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void AddMetadata_ShouldGeneratePartMetadataAttribute() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImpl)).Export<IFoo>().AddPartMetadata("name", "value"); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(2, attributes.Count()); var exportAttribute = attributes.First((t) => t.GetType() == typeof(ExportAttribute)) as ExportAttribute; Assert.Equal(typeof(IFoo), exportAttribute.ContractType); Assert.Null(exportAttribute.ContractName); var mdAttribute = attributes.First((t) => t.GetType() == typeof(PartMetadataAttribute)) as PartMetadataAttribute; Assert.Equal("name", mdAttribute.Name); Assert.Equal("value", mdAttribute.Value); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void AddMetadataWithFunc_ShouldGeneratePartMetadataAttribute() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImpl)).Export<IFoo>().AddPartMetadata("name", t => t.Name); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(2, attributes.Count()); var exportAttribute = attributes.First((t) => t.GetType() == typeof(ExportAttribute)) as ExportAttribute; Assert.Equal(typeof(IFoo), exportAttribute.ContractType); Assert.Null(exportAttribute.ContractName); var mdAttribute = attributes.First((t) => t.GetType() == typeof(PartMetadataAttribute)) as PartMetadataAttribute; Assert.Equal("name", mdAttribute.Name); Assert.Equal(typeof(FooImpl).Name, mdAttribute.Value); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ExportProperty_ShouldGenerateExportForPropertySelected() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImpl)).ExportProperties(p => p.Name == "P1"); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(1, attributes.Count()); var exportAttribute = attributes.First((t) => t.GetType() == typeof(ExportAttribute)) as ExportAttribute; Assert.Null(exportAttribute.ContractName); Assert.Null(exportAttribute.ContractType); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ImportProperty_ShouldGenerateImportForPropertySelected() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImpl)).ImportProperties(p => p.Name == "P1"); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(1, attributes.Count()); var importAttribute = attributes.First((t) => t.GetType() == typeof(ImportAttribute)) as ImportAttribute; Assert.Null(importAttribute.ContractName); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ImportProperties_ShouldGenerateImportForPropertySelected_And_ApplyImportMany() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImpl)).ImportProperties(p => p.Name == "P3"); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(1, attributes.Count()); var importAttribute = attributes.First((t) => t.GetType() == typeof(ImportManyAttribute)) as ImportManyAttribute; Assert.Null(importAttribute.ContractName); } [Fact] public void ExportPropertyWithConfiguration_ShouldGenerateExportForPropertySelected() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImpl)).ExportProperties(p => p.Name == "P1", (pi, c) => c.AsContractName("hey").AsContractType<IFoo>()); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(1, attributes.Count()); var exportAttribute = attributes.First((t) => t.GetType() == typeof(ExportAttribute)) as ExportAttribute; Assert.Same("hey", exportAttribute.ContractName); Assert.Same(typeof(IFoo), exportAttribute.ContractType); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ExportPropertyOfT_ShouldGenerateExportForPropertySelectedWithTAsContractType() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImpl)).ExportProperties(p => p.Name == "P1", (p, c) => c.AsContractType<IFoo>()); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(1, attributes.Count()); var exportAttribute = attributes.First((t) => t.GetType() == typeof(ExportAttribute)) as ExportAttribute; Assert.Null(exportAttribute.ContractName); Assert.Same(typeof(IFoo), exportAttribute.ContractType); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ConventionSelectsConstructor_SelectsTheOneWithMostParameters() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImplWithConstructors)); var selectedConstructor = GetSelectedConstructor(builder, typeof(FooImplWithConstructors)); Assert.NotNull(selectedConstructor); Assert.Equal(2, selectedConstructor.GetParameters().Length); // Should select public FooImplWithConstructors(int id, string name) { } var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); } [Fact] public void ManuallySelectingConstructor_SelectsTheExplicitOne() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImplWithConstructors)).SelectConstructor(cis => cis.ElementAt(1)); var selectedConstructor = GetSelectedConstructor(builder, typeof(FooImplWithConstructors)); Assert.NotNull(selectedConstructor); Assert.Equal(1, selectedConstructor.GetParameters().Length); // Should select public FooImplWithConstructors(int) { } var pi = selectedConstructor.GetParameters()[0]; Assert.Equal(typeof(int), pi.ParameterType); var attributes = builder.GetDeclaredAttributes(typeof(FooImplWithConstructors), pi); Assert.Equal(1, attributes.Count()); Assert.NotNull(attributes[0] as ImportAttribute); attributes = GetAttributesFromMember(builder, typeof(FooImplWithConstructors), null); Assert.Equal(0, attributes.Count()); } [Fact] public void ManuallySelectingConstructor_SelectsTheExplicitOne_IEnumerableParameterBecomesImportMany() { var builder = new ConventionBuilder(); builder.ForType(typeof(FooImplWithConstructors)).SelectConstructor(cis => cis.ElementAt(2)); var selectedConstructor = GetSelectedConstructor(builder, typeof(FooImplWithConstructors)); Assert.NotNull(selectedConstructor); Assert.Equal(1, selectedConstructor.GetParameters().Length); // Should select public FooImplWithConstructors(IEnumerable<IFoo>) { } var pi = selectedConstructor.GetParameters()[0]; Assert.Equal(typeof(IEnumerable<IFoo>), pi.ParameterType); var attributes = builder.GetDeclaredAttributes(typeof(FooImplWithConstructors), pi); Assert.Equal(1, attributes.Count()); Assert.NotNull(attributes[0] as ImportManyAttribute); attributes = GetAttributesFromMember(builder, typeof(FooImplWithConstructors), null); Assert.Equal(0, attributes.Count()); } [Fact] public void ExportInterfaceSelectorNull_ShouldThrowArgumentNull() { var builder = new ConventionBuilder(); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("interfaceFilter", () => builder.ForTypesMatching((t) => true).ExportInterfaces(null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("interfaceFilter", () => builder.ForTypesMatching((t) => true).ExportInterfaces(null, null)); } [Fact] public void ImportSelectorNull_ShouldThrowArgumentNull() { var builder = new ConventionBuilder(); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ImportProperties(null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ImportProperties(null, null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ImportProperties<IFirst>(null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ImportProperties<IFirst>(null, null)); } [Fact] public void ExportSelectorNull_ShouldThrowArgumentNull() { var builder = new ConventionBuilder(); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties(null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties(null, null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties<IFirst>(null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties<IFirst>(null, null)); } [Fact] public void InsideTheLambdaCallGetCustomAttributesShouldSucceed() { var builder = new ConventionBuilder(); builder.ForTypesMatching((t) => !t.GetTypeInfo().IsDefined(typeof(MyDoNotIncludeAttribute), false)).Export(); var container = new ContainerConfiguration() .WithPart<MyNotToBeIncludedClass>(builder) .WithPart<MyToBeIncludedClass>(builder) .CreateContainer(); var importer = new ImporterOfMyNotTobeIncludedClass(); container.SatisfyImports(importer); Assert.Null(importer.MyNotToBeIncludedClass); Assert.NotNull(importer.MyToBeIncludedClass); } [Fact] public void NotifyImportsSatisfiedAttributeAlreadyApplied_ShouldSucceed() { var builder = new ConventionBuilder(); builder.ForTypesMatching(t => true).NotifyImportsSatisfied(mi => mi.Name == "OnImportsSatisfied"); var container = new ContainerConfiguration() .WithPart<OnImportsSatisfiedConfiguredClass>(builder) .WithPart<ExportValues>(builder) .CreateContainer(); var test = container.GetExport<OnImportsSatisfiedConfiguredClass>(); Assert.NotNull(test.P1); Assert.NotNull(test.P2); Assert.Equal(1, test.OnImportsSatisfiedInvoked); } [Fact] public void NotifyImportsSatisfiedAttributeAppliedToBaseClass_ShouldSucceed() { var builder = new ConventionBuilder(); builder.ForTypesMatching(t => true).NotifyImportsSatisfied(mi => mi.Name == "OnImportsSatisfied"); var container = new ContainerConfiguration() .WithPart<OnImportsSatisfiedDerivedClass>(builder) .WithPart<ExportValues>(builder) .CreateContainer(); var test = container.GetExport<OnImportsSatisfiedDerivedClass>(); Assert.NotNull(test.P1); Assert.NotNull(test.P2); Assert.Equal(1, test.OnImportsSatisfiedInvoked); } [Fact] public void NotifyImportsSatisfiedMultipleNotifications_ShouldSucceed() { var builder = new ConventionBuilder(); builder.ForTypesMatching(t => true).NotifyImportsSatisfied(mi => mi.Name == "OnImportsSatisfied1"); var container = new ContainerConfiguration() .WithPart<OnImportsSatisfiedMultipleClass>(builder) .WithPart<ExportValues>(builder) .CreateContainer(); var test = container.GetExport<OnImportsSatisfiedMultipleClass>(); Assert.NotNull(test.P1); Assert.NotNull(test.P2); Assert.Equal(2, test.OnImportsSatisfiedInvoked); } [Fact] public void NotifyImportsSatisfiedTwice_ShouldSucceed() { var builder = new ConventionBuilder(); builder.ForTypesMatching(t => true).NotifyImportsSatisfied(mi => mi.Name == "OnImportsSatisfied1" || mi.Name == "OnImportsSatisfied2"); var container = new ContainerConfiguration() .WithPart<OnImportsSatisfiedMultipleClass>(builder) .WithPart<ExportValues>(builder) .CreateContainer(); var test = container.GetExport<OnImportsSatisfiedMultipleClass>(); Assert.NotNull(test.P1); Assert.NotNull(test.P2); Assert.Equal(6, test.OnImportsSatisfiedInvoked); } [Fact] public void NotifyImportsSatisfiedInvalidMethod_ShouldSucceed() { var builder = new ConventionBuilder(); builder.ForTypesMatching(t => true).NotifyImportsSatisfied(mi => mi.Name == "OnImportsSatisfied3" || mi.Name == "OnImportsSatisfied4"); var container = new ContainerConfiguration() .WithPart<OnImportsSatisfiedTestClassPropertiesAndFields>(builder) .WithPart<ExportValues>(builder) .CreateContainer(); var test = container.GetExport<OnImportsSatisfiedTestClassPropertiesAndFields>(); Assert.NotNull(test.P1); Assert.NotNull(test.P2); Assert.Equal(0, test.OnImportsSatisfiedInvoked); } [Fact] public void NotifyImportsSatisfiedPropertiesAndFields_ShouldSucceed() { var builder = new ConventionBuilder(); builder.ForTypesMatching(t => true).NotifyImportsSatisfied(mi => mi.Name == "OnImportsSatisfied5" || mi.Name == "OnImportsSatisfied6"); var container = new ContainerConfiguration() .WithPart<OnImportsSatisfiedTestClassPropertiesAndFields>(builder) .WithPart<ExportValues>(builder) .CreateContainer(); var test = container.GetExport<OnImportsSatisfiedTestClassPropertiesAndFields>(); Assert.NotNull(test.P1); Assert.NotNull(test.P2); Assert.Equal(0, test.OnImportsSatisfiedInvoked); } private static Attribute[] GetAttributesFromMember(ConventionBuilder builder, Type type, string member) { if (string.IsNullOrEmpty(member)) { var list = builder.GetDeclaredAttributes(null, type.GetTypeInfo()); return list; } else { var pi = type.GetRuntimeProperty(member); var list = builder.GetDeclaredAttributes(type, pi); return list; } } private static ConstructorInfo GetSelectedConstructor(ConventionBuilder builder, Type type) { ConstructorInfo reply = null; foreach (var ci in type.GetTypeInfo().DeclaredConstructors) { var li = builder.GetDeclaredAttributes(type, ci); if (li.Length > 0) { Assert.True(reply == null); // Fail if we got more than one constructor reply = ci; } } return reply; } } }
using System; using swc = Windows.UI.Xaml.Controls; using sw = Windows.UI.Xaml; using wf = Windows.Foundation; using swm = Windows.UI.Xaml.Media; using Eto.Forms; using Eto.Drawing; namespace Eto.WinRT.Forms.Controls { /// <summary> /// Scrollable handler. /// </summary> /// <copyright>(c) 2014 by Vivek Jhaveri</copyright> /// <copyright>(c) 2012-2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class ScrollableHandler : WpfPanel<swc.Border, Scrollable, Scrollable.ICallback>, Scrollable.IHandler { BorderType borderType; bool expandContentWidth = true; bool expandContentHeight = true; readonly swc.ScrollViewer scroller; public sw.FrameworkElement ContentControl { get { return scroller; } } protected override bool UseContentSize { get { return false; } } public override Color BackgroundColor { get { return scroller.Background.ToEtoColor(); } set { scroller.Background = value.ToWpfBrush(scroller.Background); } } public ScrollableHandler() { Control = new swc.Border { #if TODO_XAML SnapsToDevicePixels = true, Focusable = false, #endif }; scroller = new swc.ScrollViewer { VerticalScrollBarVisibility = swc.ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = swc.ScrollBarVisibility.Auto, #if TODO_XAML CanContentScroll = true, SnapsToDevicePixels = true, Focusable = false #endif }; scroller.SizeChanged += (s, e) => UpdateSizes(); scroller.Loaded += (s, e) => UpdateSizes(); Control.Child = scroller; this.Border = BorderType.Bezel; } void UpdateSizes() { //var info = scroller.GetScrollInfo(); //if (info != null) { var content = (swc.Border)scroller.Content; var viewportSize = new wf.Size(scroller.ViewportWidth, scroller.ViewportHeight); var prefSize = Content.GetPreferredSize(Conversions.PositiveInfinitySize); // hack for when a scrollable is in a group box it expands vertically if (Widget.FindParent<GroupBox>() != null) viewportSize.Height = Math.Max(0, viewportSize.Height - 1); if (ExpandContentWidth) content.Width = Math.Max(0, Math.Max(prefSize.Width, viewportSize.Width)); else content.Width = prefSize.Width; if (ExpandContentHeight) content.Height = Math.Max(0, Math.Max(prefSize.Height, viewportSize.Height)); else content.Height = prefSize.Height; } scroller.InvalidateMeasure(); } public override void UpdatePreferredSize() { UpdateSizes(); base.UpdatePreferredSize(); } public void UpdateScrollSizes() { Control.InvalidateMeasure(); UpdateSizes(); } public Point ScrollPosition { get { EnsureLoaded(); return new Point((int)scroller.HorizontalOffset, (int)scroller.VerticalOffset); } set { scroller.ChangeView(value.X, value.Y, null); } } public Size ScrollSize { get { EnsureLoaded(); return new Size((int)scroller.ExtentWidth, (int)scroller.ExtentHeight); } set { var content = (swc.Border)Control.Child; content.MinHeight = value.Height; content.MinWidth = value.Width; UpdateSizes(); } } public BorderType Border { get { return borderType; } set { borderType = value; switch (value) { case BorderType.Bezel: #if TODO_XAML Control.BorderBrush = sw.SystemColors.ControlDarkDarkBrush; #endif Control.BorderThickness = new sw.Thickness(1.0); break; case BorderType.Line: #if TODO_XAML Control.BorderBrush = sw.SystemColors.ControlDarkDarkBrush; #endif Control.BorderThickness = new sw.Thickness(1); break; case BorderType.None: Control.BorderBrush = null; break; default: throw new NotSupportedException(); } } } public override Size ClientSize { get { if (!Widget.Loaded) return Size; EnsureLoaded(); return new Size((int)scroller.ViewportWidth, (int)scroller.ViewportHeight); } set { Size = value; } } public Rectangle VisibleRect { get { return new Rectangle(ScrollPosition, ClientSize); } } public override void SetContainerContent(sw.FrameworkElement content) { content.HorizontalAlignment = sw.HorizontalAlignment.Left; content.VerticalAlignment = sw.VerticalAlignment.Top; content.SizeChanged += (s, e) => UpdateSizes(); scroller.Content = content; } public override void AttachEvent(string id) { switch (id) { case Scrollable.ScrollEvent: scroller.ViewChanged += (sender, e) => { Callback.OnScroll(Widget, new ScrollEventArgs(new Point((int)scroller.HorizontalOffset, (int)scroller.VerticalOffset))); }; break; default: base.AttachEvent(id); break; } } public bool ExpandContentWidth { get { return expandContentWidth; } set { if (expandContentWidth != value) { expandContentWidth = value; UpdateSizes(); } } } public bool ExpandContentHeight { get { return expandContentHeight; } set { if (expandContentHeight != value) { expandContentHeight = value; UpdateSizes(); } } } public override void Invalidate() { base.Invalidate(); foreach (var control in Widget.Children) { control.Invalidate(); } } public override void Invalidate(Rectangle rect) { base.Invalidate(rect); foreach (var control in Widget.Children) { control.Invalidate(rect); } } public float MinimumZoom { get { return 1f; } set { } } public float MaximumZoom { get { return 1f; } set { } } public float Zoom { get { return 1f; } set { } } } }
using System.Collections.Generic; using Antlr4.Runtime; using Antlr4.Runtime.Atn; using Antlr4CodeCompletion.Core.CodeCompletion; using Antlr4CodeCompletion.CoreUnitTest.Grammar; using Antlr4CodeCompletion.CoreUnitTest.Utils; using NFluent; using Xunit; namespace Antlr4CodeCompletion.CoreUnitTest.CodeCompletion { /// <summary> /// </summary> /// <remarks> /// Port of antlr-c3 java unit test library to c# /// The c3 engine is able to provide code completion candidates useful for /// editors with ANTLR generated parsers, independent of the actual /// language/grammar used for the generation. /// https://github.com/mike-lischke/antlr4-c3 /// </remarks> public class CodeCompletionCoreUnitTests { [Fact] public void Completion_Grammar_SimpleExpression() { // arrange var input = "var c = a + b()"; var inputStream = new AntlrInputStream(input); var lexer = new ExprLexer(inputStream); var tokenStream = new CommonTokenStream(lexer); var parser = new ExprParser(tokenStream); lexer.RemoveErrorListeners(); parser.RemoveErrorListeners(); var errorListener = new CountingErrorListener(); parser.AddErrorListener(errorListener); // act // assert // Specify our entry point var tree = parser.expression(); Check.That(errorListener.ErrorCount).IsEqualTo(0); var core = new CodeCompletionCore(parser, null, null); // 1) At the input start. var candidates = core.CollectCandidates(0, null); Check.That(candidates.Tokens).HasSize(3); Check.That(candidates.Tokens).ContainsKey(ExprLexer.VAR); Check.That(candidates.Tokens).ContainsKey(ExprLexer.LET); Check.That(candidates.Tokens).ContainsKey(ExprLexer.ID); Check.That(candidates.Tokens[ExprLexer.VAR]).IsEqualTo(new[] { ExprLexer.ID, ExprLexer.EQUAL }); Check.That(candidates.Tokens[ExprLexer.LET]).IsEqualTo(new[] { ExprLexer.ID, ExprLexer.EQUAL }); Check.That(candidates.Tokens[ExprLexer.ID]).HasSize(0); // 2) On the first whitespace. In real implementations you would do some additional checks where in the whitespace // the caret is, as the outcome is different depending on that position. candidates = core.CollectCandidates(1, null); Check.That(candidates.Tokens).HasSize(1); Check.That(candidates.Tokens).ContainsKey(ExprLexer.ID); // 3) On the variable name ('c'). candidates = core.CollectCandidates(2, null); Check.That(candidates.Tokens).HasSize(1); Check.That(candidates.Tokens).ContainsKey(ExprLexer.ID); // 4) On the equal sign (ignoring whitespace positions from now on). candidates = core.CollectCandidates(4, null); Check.That(candidates.Tokens).HasSize(1); Check.That(candidates.Tokens).ContainsKey(ExprLexer.EQUAL); // 5) On the variable reference 'a'. But since we have not configure the c3 engine to return us var refs // (or function refs for that matter) we only get an ID here. candidates = core.CollectCandidates(6, null); Check.That(candidates.Tokens).HasSize(1); Check.That(candidates.Tokens).ContainsKey(ExprLexer.ID); // 6) On the '+' operator. Usually you would not show operators as candidates, but we have not set up the c3 engine // yet to not return them. candidates = core.CollectCandidates(8, null); Check.That(candidates.Tokens).HasSize(5); Check.That(candidates.Tokens).ContainsKey(ExprLexer.PLUS); Check.That(candidates.Tokens).ContainsKey(ExprLexer.MINUS); Check.That(candidates.Tokens).ContainsKey(ExprLexer.MULTIPLY); Check.That(candidates.Tokens).ContainsKey(ExprLexer.DIVIDE); Check.That(candidates.Tokens).ContainsKey(ExprLexer.OPEN_PAR); } [Fact] public void Completion_Grammar_TypicalExpression() { // arrange var expression = "var c = a + b"; var inputStream = new AntlrInputStream(expression); var lexer = new ExprLexer(inputStream); var tokenStream = new CommonTokenStream(lexer); var parser = new ExprParser(tokenStream); parser.Interpreter.PredictionMode = PredictionMode.LlExactAmbigDetection; lexer.RemoveErrorListeners(); parser.RemoveErrorListeners(); var errorListener = new CountingErrorListener(); parser.AddErrorListener(errorListener); // act // assert // Specify our entry point var tree = parser.expression(); Check.That(errorListener.ErrorCount).IsEqualTo(0); // Tell the engine to return certain rules to us, which we could use to look up values in a symbol table. var preferredRules = new HashSet<int>() { ExprParser.RULE_functionRef, ExprParser.RULE_variableRef }; // Ignore operators and the generic ID token. var ignoredTokens = new HashSet<int>() { ExprLexer.PLUS, ExprLexer.MINUS, ExprLexer.MULTIPLY, ExprLexer.DIVIDE }; var core = new CodeCompletionCore(parser, preferredRules, ignoredTokens); // 1) At the input start. var candidates = core.CollectCandidates(0, null); Check.That(candidates.Tokens).HasSize(2); Check.That(candidates.Tokens).ContainsKey(ExprLexer.VAR); Check.That(candidates.Tokens).ContainsKey(ExprLexer.LET); Check.That(candidates.Tokens .TryGetValue(ExprLexer.VAR, out var varCandidates)) .IsTrue(); Check.That(candidates.Tokens .TryGetValue(ExprLexer.LET, out var letCandidates)) .IsTrue(); Check.That(varCandidates).HasSize(2); Check.That(letCandidates).HasSize(2); Check.That(varCandidates).IsEqualTo(new[] { ExprLexer.ID, ExprLexer.EQUAL }); Check.That(letCandidates).IsEqualTo(new[] { ExprLexer.ID, ExprLexer.EQUAL }); // 2) On the variable name ('c'). ignoredTokens = new HashSet<int>() { ExprLexer.ID, ExprLexer.PLUS, ExprLexer.MINUS, ExprLexer.MULTIPLY, ExprLexer.DIVIDE, ExprLexer.EQUAL }; core = new CodeCompletionCore(parser, preferredRules, ignoredTokens); candidates = core.CollectCandidates(2, null); Check.That(candidates.Tokens).HasSize(0); // 4) On the equal sign (ignoring whitespace positions from now on). candidates = core.CollectCandidates(4, null); Check.That(candidates.Tokens).HasSize(0); // 5) On the variable reference 'a'. candidates = core.CollectCandidates(6, null); Check.That(candidates.Tokens).HasSize(0); Check.That(candidates.Rules).HasSize(2); // Here we get 2 rule indexes, derived from 2 different IDs possible at this caret position. // These are what we told the engine above to be preferred rules for us. var found = 0; foreach (var candidate in candidates.Rules) { switch (candidate.Key) { case ExprParser.RULE_functionRef: { found++; break; } case ExprParser.RULE_variableRef: { found++; break; } } } Check.That(found).Equals(2); // 6) On the whitespace after the 'a' candidates = core.CollectCandidates(7, null); Check.That(candidates.Tokens).HasSize(0); Check.That(candidates.Rules).HasSize(1); // Here we get 2 rule indexes found = 0; foreach (var candidate in candidates.Rules) { switch (candidate.Key) { case ExprParser.RULE_functionRef: { found++; break; } case ExprParser.RULE_variableRef: { found++; break; } } } Check.That(found).Equals(1); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Pooling; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Testing; using osu.Framework.Timing; using osu.Framework.Utils; using osuTK; using osuTK.Graphics; namespace osu.Framework.Tests.Visual.Drawables { public class TestSceneDrawablePool : TestScene { private DrawablePool<TestDrawable> pool; private SpriteText count; private readonly HashSet<TestDrawable> consumed = new HashSet<TestDrawable>(); [Test] public void TestPoolInitialDrawableLoadedAheadOfTime() { const int pool_size = 3; resetWithNewPool(() => new TestPool(TimePerAction, pool_size)); for (int i = 0; i < 3; i++) AddAssert("check drawable is in ready state", () => pool.Get().LoadState == LoadState.Ready); } [Test] public void TestPoolUsageWithinLimits() { const int pool_size = 10; resetWithNewPool(() => new TestPool(TimePerAction, pool_size)); AddRepeatStep("get new pooled drawable", () => consumeDrawable(), 50); AddUntilStep("all returned to pool", () => pool.CountAvailable == pool_size); AddAssert("consumed drawables report returned to pool", () => consumed.All(d => d.IsInPool)); AddAssert("consumed drawables not disposed", () => consumed.All(d => !d.IsDisposed)); AddAssert("consumed less than pool size", () => consumed.Count < pool_size); } [Test] public void TestPoolUsageExceedsLimits() { const int pool_size = 10; resetWithNewPool(() => new TestPool(TimePerAction * 20, pool_size)); AddRepeatStep("get new pooled drawable", () => consumeDrawable(), 50); AddUntilStep("all returned to pool", () => pool.CountAvailable == consumed.Count); AddAssert("pool grew in size", () => pool.CountAvailable > pool_size); AddAssert("consumed drawables report returned to pool", () => consumed.All(d => d.IsInPool)); AddAssert("consumed drawables not disposed", () => consumed.All(d => !d.IsDisposed)); } [TestCase(10)] [TestCase(20)] public void TestPoolInitialSize(int initialPoolSize) { resetWithNewPool(() => new TestPool(TimePerAction * 20, initialPoolSize)); AddUntilStep("available count is correct", () => pool.CountAvailable == initialPoolSize); } [Test] public void TestReturnWithoutAdding() { resetWithNewPool(() => new TestPool(TimePerAction, 1)); TestDrawable drawable = null; AddStep("consume without adding", () => drawable = pool.Get()); AddStep("manually return", () => drawable.Return()); AddUntilStep("free was run", () => drawable.FreedCount == 1); AddUntilStep("was returned", () => pool.CountAvailable == 1); AddAssert("manually return twice throws", () => { try { drawable.Return(); return false; } catch (InvalidOperationException) { return true; } }); } [Test] public void TestPoolReturnWhenAboveCapacity() { resetWithNewPool(() => new TestPool(TimePerAction * 20, 1, 1)); TestDrawable first = null, second = null; AddStep("consume item", () => first = consumeDrawable()); AddAssert("pool is empty", () => pool.CountAvailable == 0); AddStep("consume and return another item", () => { second = pool.Get(); second.Return(); }); AddAssert("first item still in use", () => first.IsInUse); AddUntilStep("second is returned", () => !second.IsInUse && pool.CountAvailable == 1); AddStep("expire first", () => first.Expire()); AddUntilStep("wait until first dead", () => !first.IsAlive); AddUntilStep("drawable is disposed", () => first.IsDisposed); } [Test] public void TestPrepareAndFreeMethods() { resetWithNewPool(() => new TestPool(TimePerAction, 1)); TestDrawable drawable = null; TestDrawable drawable2 = null; AddStep("consume item", () => drawable = consumeDrawable()); AddAssert("prepare was run", () => drawable.PreparedCount == 1); AddUntilStep("free was run", () => drawable.FreedCount == 1); AddStep("consume item", () => drawable2 = consumeDrawable()); AddAssert("is same item", () => ReferenceEquals(drawable, drawable2)); AddAssert("prepare was run", () => drawable2.PreparedCount == 2); AddUntilStep("free was run", () => drawable2.FreedCount == 2); } [Test] public void TestPrepareOnlyOnceOnMultipleUsages() { resetWithNewPool(() => new TestPool(TimePerAction, 1)); TestDrawable drawable = null; TestDrawable drawable2 = null; AddStep("consume item", () => drawable = consumeDrawable(false)); AddAssert("prepare was not run", () => drawable.PreparedCount == 0); AddUntilStep("free was not run", () => drawable.FreedCount == 0); AddStep("manually return drawable", () => pool.Return(drawable)); AddUntilStep("free was run", () => drawable.FreedCount == 1); AddStep("consume item", () => drawable2 = consumeDrawable()); AddAssert("is same item", () => ReferenceEquals(drawable, drawable2)); AddAssert("prepare was only run once", () => drawable2.PreparedCount == 1); AddUntilStep("free was run", () => drawable2.FreedCount == 2); } [Test] public void TestUsePoolableDrawableWithoutPool() { TestDrawable drawable = null; AddStep("consume item", () => Add(drawable = new TestDrawable())); AddAssert("prepare was run", () => drawable.PreparedCount == 1); AddUntilStep("free was run", () => drawable.FreedCount == 1); AddUntilStep("drawable was disposed", () => drawable.IsDisposed); } [Test] public void TestAllDrawablesComeReady() { const int pool_size = 10; List<Drawable> retrieved = new List<Drawable>(); resetWithNewPool(() => new TestPool(TimePerAction * 20, 10, pool_size)); AddStep("get many pooled drawables", () => { retrieved.Clear(); for (int i = 0; i < pool_size * 2; i++) retrieved.Add(pool.Get()); }); AddAssert("all drawables in ready state", () => retrieved.All(d => d.LoadState == LoadState.Ready)); } [TestCase(10)] [TestCase(20)] public void TestPoolUsageExceedsMaximum(int maxPoolSize) { resetWithNewPool(() => new TestPool(TimePerAction * 20, 10, maxPoolSize)); AddStep("get many pooled drawables", () => { for (int i = 0; i < maxPoolSize * 2; i++) consumeDrawable(); }); AddAssert("pool saturated", () => pool.CountAvailable == 0); AddUntilStep("pool size returned to correct maximum", () => pool.CountAvailable == maxPoolSize); AddUntilStep("count in pool is correct", () => consumed.Count(d => d.IsInPool) == maxPoolSize); AddAssert("excess drawables were used", () => consumed.Any(d => !d.IsInPool)); AddAssert("non-returned drawables disposed", () => consumed.Where(d => !d.IsInPool).All(d => d.IsDisposed)); } [Test] public void TestGetFromNotLoadedPool() { Assert.DoesNotThrow(() => new TestPool(100, 1).Get()); } /// <summary> /// Tests that when a child of a pooled drawable receives a parent invalidation, the parent pooled drawable is not returned. /// A parent invalidation can happen on the child if it's added to the hierarchy of the parent. /// </summary> [Test] public void TestParentInvalidationFromChildDoesNotReturnPooledParent() { resetWithNewPool(() => new TestPool(TimePerAction, 1)); TestDrawable drawable = null; AddStep("consume item", () => drawable = consumeDrawable(false)); AddStep("add child", () => drawable.AddChild(Empty())); AddAssert("not freed", () => drawable.FreedCount == 0); } [Test] public void TestDrawablePreparedWhenClockRewound() { resetWithNewPool(() => new TestPool(TimePerAction, 1)); TestDrawable drawable = null; AddStep("consume item and rewind clock", () => { var clock = new ManualClock { CurrentTime = Time.Current }; Add(new Container { RelativeSizeAxes = Axes.Both, Clock = new FramedClock(clock), Child = drawable = consumeDrawable(false) }); clock.CurrentTime = 0; }); AddAssert("child prepared", () => drawable.PreparedCount == 1); } protected override void Update() { base.Update(); if (count != null) count.Text = $"available: {pool.CountAvailable} consumed: {consumed.Count} disposed: {consumed.Count(d => d.IsDisposed)}"; } private static int displayCount; private TestDrawable consumeDrawable(bool addToHierarchy = true) { var drawable = pool.Get(d => { d.Position = new Vector2(RNG.NextSingle(), RNG.NextSingle()); d.DisplayString = (++displayCount).ToString(); }); consumed.Add(drawable); if (addToHierarchy) Add(drawable); return drawable; } private void resetWithNewPool(Func<DrawablePool<TestDrawable>> createPool) { AddStep("reset stats", () => consumed.Clear()); AddStep("create pool", () => { pool = createPool(); Children = new Drawable[] { pool, count = new SpriteText(), }; }); } private class TestPool : DrawablePool<TestDrawable> { private readonly double fadeTime; public TestPool(double fadeTime, int initialSize, int? maximumSize = null) : base(initialSize, maximumSize) { this.fadeTime = fadeTime; } protected override TestDrawable CreateNewDrawable() { return new TestDrawable(fadeTime); } } private class TestDrawable : PoolableDrawable { private readonly double fadeTime; private readonly SpriteText text; public string DisplayString { set => text.Text = value; } public TestDrawable() : this(1000) { } public TestDrawable(double fadeTime) { this.fadeTime = fadeTime; RelativePositionAxes = Axes.Both; Size = new Vector2(50); Origin = Anchor.Centre; InternalChildren = new Drawable[] { new Box { Colour = Color4.Green, RelativeSizeAxes = Axes.Both, }, text = new SpriteText { Text = "-", Font = FontUsage.Default.With(size: 40), Anchor = Anchor.Centre, Origin = Anchor.Centre, }, }; } public void AddChild(Drawable drawable) => AddInternal(drawable); public new bool IsDisposed => base.IsDisposed; public int PreparedCount { get; private set; } public int FreedCount { get; private set; } protected override void PrepareForUse() { this.FadeOutFromOne(fadeTime); this.RotateTo(0).RotateTo(80, fadeTime); Expire(); PreparedCount++; } protected override void FreeAfterUse() { base.FreeAfterUse(); FreedCount++; } } } }
// Copyright (C) 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Runtime.InteropServices; using System; using System.Collections.Generic; /// <summary> /// Plays video using Exoplayer rendering it on the main texture. /// </summary> public class GvrVideoPlayerTexture : MonoBehaviour { private const int MIN_BUFFER_SIZE = 3; private const int MAX_BUFFER_SIZE = 15; /// <summary> /// The video texture array used as a circular buffer to get the video image. /// </summary> private Texture2D[] videoTextures; private int currentTexture; /// <summary> /// The video player pointer used to uniquely identify the player instance. /// </summary> private IntPtr videoPlayerPtr; /// <summary> /// The video player event base. /// </summary> /// <remarks>This is added to the event id when issues events to /// the plugin. /// </remarks> private int videoPlayerEventBase; private Texture initialTexture; private bool initialized; private int texWidth = 1024; private int texHeight = 1024; private long lastBufferedPosition; private float framecount = 0; private Graphic graphicComponent; private Renderer rendererComponent; /// <summary> /// The render event function. /// </summary> private IntPtr renderEventFunction; private bool processingRunning; private bool exitProcessing; /// <summary>List of callbacks to invoke when the video is ready.</summary> private List<Action<int>> onEventCallbacks; /// <summary>List of callbacks to invoke on exception.</summary> /// <remarks>The first parameter is the type of exception, /// the second is the message. /// </remarks> private List<Action<string, string>> onExceptionCallbacks; private readonly static Queue<Action> ExecuteOnMainThread = new Queue<Action>(); // Attach a text component to get some debug status info. public Text statusText; /// <summary> /// Video type. /// </summary> public enum VideoType { Dash = 0, HLS = 2, Other = 3 }; public enum VideoResolution { Lowest = 1, _720 = 720, _1080 = 1080, _2048 = 2048, Highest = 4096 }; /// <summary> /// Video player state. /// </summary> public enum VideoPlayerState { Idle = 1, Preparing = 2, Buffering = 3, Ready = 4, Ended = 5 }; public enum VideoEvents { VideoReady = 1, VideoStartPlayback = 2, VideoFormatChanged = 3, VideoSurfaceSet = 4, VideoSizeChanged = 5 }; /// <summary> /// Plugin render commands. /// </summary> /// <remarks> /// These are added to the eventbase for the specific player object and /// issued to the plugin. /// </remarks> private enum RenderCommand { None = -1, InitializePlayer = 0, UpdateVideo = 1, RenderMono = 2, RenderLeftEye = 3, RenderRightEye = 4, Shutdown = 5 }; // The circular buffer has to be at least 2, // but in some cases that is too small, so set some reasonable range // so a slider shows up in the property inspector. [Range(MIN_BUFFER_SIZE, MAX_BUFFER_SIZE)] public int bufferSize; /// <summary> /// The type of the video. /// </summary> public VideoType videoType; public string videoURL; public string videoContentID; public string videoProviderId; public VideoResolution initialResolution = VideoResolution.Highest; /// <summary> /// True for adjusting the aspect ratio of the renderer. /// </summary> public bool adjustAspectRatio; /// <summary> /// The use secure path for DRM protected video. /// </summary> public bool useSecurePath; public bool VideoReady { get { return videoPlayerPtr != IntPtr.Zero && IsVideoReady(videoPlayerPtr); } } public long CurrentPosition { get { return videoPlayerPtr != IntPtr.Zero ? GetCurrentPosition(videoPlayerPtr) : 0; } set { // If the position is being set to 0, reset the framecount as well. // This allows the texture swapping to work correctly at the beginning // of the stream. if (value == 0) { framecount = 0; } SetCurrentPosition(videoPlayerPtr, value); } } public long VideoDuration { get { return videoPlayerPtr != IntPtr.Zero ? GetDuration(videoPlayerPtr) : 0; } } public long BufferedPosition { get { return videoPlayerPtr != IntPtr.Zero ? GetBufferedPosition(videoPlayerPtr) : 0; } } public int BufferedPercentage { get { return videoPlayerPtr != IntPtr.Zero ? GetBufferedPercentage(videoPlayerPtr) : 0; } } public bool IsPaused { get { return !initialized || videoPlayerPtr == IntPtr.Zero || IsVideoPaused(videoPlayerPtr); } } public VideoPlayerState PlayerState { get { return videoPlayerPtr != IntPtr.Zero ? (VideoPlayerState)GetPlayerState(videoPlayerPtr) : VideoPlayerState.Idle; } } public int MaxVolume { get { return videoPlayerPtr != IntPtr.Zero ? GetMaxVolume(videoPlayerPtr) : 0; } } public int CurrentVolume { get { return videoPlayerPtr != IntPtr.Zero ? GetCurrentVolume(videoPlayerPtr) : 0; } set { SetCurrentVolume(value); } } /// Create the video player instance and the event base id. void Awake() { // Find the components on which to set the video texture. graphicComponent = GetComponent<Graphic>(); rendererComponent = GetComponent<Renderer>(); CreatePlayer(); } void CreatePlayer() { bufferSize = bufferSize < MIN_BUFFER_SIZE ? MIN_BUFFER_SIZE : bufferSize; if (videoTextures != null) { DestroyVideoTextures(); } videoTextures = new Texture2D[bufferSize]; currentTexture = 0; videoPlayerPtr = CreateVideoPlayer(); videoPlayerEventBase = GetVideoPlayerEventBase(videoPlayerPtr); Debug.Log(" -- " + gameObject.name + " created with base " + videoPlayerEventBase); SetOnVideoEventCallback((eventId) => { Debug.Log("------------- E V E N T " + eventId + " -----------------"); UpdateStatusText(); }); SetOnExceptionCallback((type, msg) => { Debug.LogError("Exception: " + type + ": " + msg); }); initialized = false; if (rendererComponent != null) { initialTexture = rendererComponent.material.mainTexture; } else if (graphicComponent) { initialTexture = graphicComponent.mainTexture; } } IEnumerator Start() { CreateTextureForVideoMaybe(); renderEventFunction = GetRenderEventFunc(); if (renderEventFunction != IntPtr.Zero) { IssuePlayerEvent(RenderCommand.InitializePlayer); yield return StartCoroutine(CallPluginAtEndOfFrames()); } } void OnDisable() { if (videoPlayerPtr != IntPtr.Zero) { if (GetPlayerState(videoPlayerPtr) == (int)VideoPlayerState.Ready) { PauseVideo(videoPlayerPtr); } } } /// <summary> /// Sets the display texture. /// </summary> /// <param name="texture">Texture to display. // If null, the initial texture of the renderer is used.</param> public void SetDisplayTexture(Texture texture) { if (texture == null) { texture = initialTexture; } if (texture == null) { return; } if (rendererComponent != null) { rendererComponent.sharedMaterial.mainTexture = initialTexture; } else if (graphicComponent != null) { graphicComponent.material.mainTexture = initialTexture; } } public void CleanupVideo() { Debug.Log("Cleaning Up video!"); exitProcessing = true; if (videoPlayerPtr != IntPtr.Zero) { DestroyVideoPlayer(videoPlayerPtr); videoPlayerPtr = IntPtr.Zero; } DestroyVideoTextures(); if (rendererComponent != null) { rendererComponent.sharedMaterial.mainTexture = initialTexture; } else if (graphicComponent != null) { graphicComponent.material.mainTexture = initialTexture; } } public void ReInitializeVideo() { if (rendererComponent != null) { rendererComponent.sharedMaterial.mainTexture = initialTexture; } else if (graphicComponent != null) { graphicComponent.material.mainTexture = initialTexture; } if (videoPlayerPtr == IntPtr.Zero) { CreatePlayer(); IssuePlayerEvent(RenderCommand.InitializePlayer); } if (Init()) { StartCoroutine(CallPluginAtEndOfFrames()); } } void DestroyVideoTextures() { if (videoTextures != null) { foreach (Texture2D t in videoTextures) { if (t != null) { // Free GPU memory immediately. t.Resize(1, 1); t.Apply(); // Unity's destroy is lazy. Destroy(t); } } videoTextures = null; } } void OnEnable() { if (videoPlayerPtr != IntPtr.Zero) { StartCoroutine(CallPluginAtEndOfFrames()); } } void OnDestroy() { if (videoPlayerPtr != IntPtr.Zero) { DestroyVideoPlayer(videoPlayerPtr); } DestroyVideoTextures(); } void OnValidate() { Renderer r = GetComponent<Renderer>(); Graphic g = GetComponent<Graphic>(); if (g == null && r == null) { Debug.LogError("TexturePlayer object must have either " + "a Renderer component or a Graphic component."); } } void OnApplicationPause(bool bPause) { if (videoPlayerPtr != IntPtr.Zero) { if (bPause) { PauseVideo(videoPlayerPtr); } else { PlayVideo(videoPlayerPtr); } } } void OnRenderObject() { // Don't render if not initialized. if (videoPlayerPtr == IntPtr.Zero || videoTextures[0] == null) { return; } Texture newTex = videoTextures[currentTexture]; // Handle either the renderer component or the graphic component. if (rendererComponent != null) { // Don't render the first texture from the player, it is unitialized. if (currentTexture <= 1 && framecount <= 1) { return; } // Don't swap the textures if the video ended. if (PlayerState == VideoPlayerState.Ended) { return; } // Unity may build new a new material instance when assigning // material.x which can lead to duplicating materials each frame // whereas using the shared material will modify the original material. if (rendererComponent.material.mainTexture != null) { IntPtr currentTexId = rendererComponent.sharedMaterial.mainTexture.GetNativeTexturePtr(); // Update the material's texture if it is different. if (currentTexId != newTex.GetNativeTexturePtr()) { rendererComponent.sharedMaterial.mainTexture = newTex; framecount += 1f; } } else { rendererComponent.sharedMaterial.mainTexture = newTex; } } else if (graphicComponent != null) { if (graphicComponent.material.mainTexture != null) { IntPtr currentTexId = graphicComponent.material.mainTexture.GetNativeTexturePtr(); // Update the material's texture if it is different. if (currentTexId != newTex.GetNativeTexturePtr()) { graphicComponent.material.mainTexture = newTex; framecount += 1f; } } else { graphicComponent.material.mainTexture = newTex; } } else { Debug.LogError("GvrVideoPlayerTexture: No render or graphic component."); } } private void OnRestartVideoEvent(int eventId) { if (eventId == (int)VideoEvents.VideoReady) { Debug.Log("Restarting video complete."); RemoveOnVideoEventCallback(OnRestartVideoEvent); } } /// <summary> /// Resets the video player. /// </summary> public void RestartVideo() { SetOnVideoEventCallback(OnRestartVideoEvent); string theUrl = ProcessURL(); InitVideoPlayer(videoPlayerPtr, (int) videoType, theUrl, videoContentID, videoProviderId, useSecurePath, true); framecount = 0; } public void SetCurrentVolume(int val) { SetCurrentVolume(videoPlayerPtr, val); } /// <summary> /// Initialize the video player. /// </summary> /// <returns>true if successful</returns> public bool Init() { if (initialized) { Debug.Log("Skipping initialization: video player already loaded"); return true; } if (videoURL == null || videoURL.Length == 0) { Debug.LogError("Cannot initialize with null videoURL"); return false; } videoURL = videoURL == null ? "" : videoURL.Trim(); videoContentID = videoContentID == null ? "" : videoContentID.Trim(); videoProviderId = videoProviderId == null ? "" : videoProviderId.Trim(); SetInitialResolution(videoPlayerPtr, (int) initialResolution); string theUrl = ProcessURL(); Debug.Log("Playing " + videoType + " " + theUrl); Debug.Log("videoContentID = " + videoContentID); Debug.Log("videoProviderId = " + videoProviderId); videoPlayerPtr = InitVideoPlayer(videoPlayerPtr, (int) videoType, theUrl, videoContentID, videoProviderId, useSecurePath, false); initialized = true; framecount = 0; return videoPlayerPtr != IntPtr.Zero; } public bool Play() { if (!initialized) { Init(); } else if (!processingRunning) { StartCoroutine(CallPluginAtEndOfFrames()); } if (videoPlayerPtr != IntPtr.Zero && IsVideoReady(videoPlayerPtr)) { return PlayVideo(videoPlayerPtr) == 0; } else { Debug.LogError("Video player not ready to Play!"); return false; } } public bool Pause() { if (!initialized) { Init(); } if (VideoReady) { return PauseVideo(videoPlayerPtr) == 0; } else { Debug.LogError("Video player not ready to Pause!"); return false; } } /// <summary> /// Adjusts the aspect ratio. /// </summary> /// <remarks> /// This adjusts the transform scale to match the aspect /// ratio of the texture. /// </remarks> private void AdjustAspectRatio() { float aspectRatio = texWidth / texHeight; // set the y scale based on the x value Vector3 newscale = transform.localScale; newscale.y = Mathf.Min(newscale.y, newscale.x / aspectRatio); transform.localScale = newscale; } /// <summary> /// Creates the texture for video if needed. /// </summary> private void CreateTextureForVideoMaybe() { if (videoTextures[0] == null || (texWidth != videoTextures[0].width || texHeight != videoTextures[0].height)) { // Check the dimensions to make sure they are valid. if (texWidth < 0 || texHeight < 0) { // Maybe use the last dimension. This happens when re-initializing the player. if (videoTextures != null && videoTextures[0].width > 0) { texWidth = videoTextures[0].width; texHeight = videoTextures[0].height; } } int[] tex_ids = new int[videoTextures.Length]; for (int idx = 0; idx < videoTextures.Length; idx++) { // Resize the existing texture if there, otherwise create it. if (videoTextures[idx] != null) { if (videoTextures[idx].width != texWidth || videoTextures[idx].height != texHeight) { videoTextures[idx].Resize(texWidth, texHeight); videoTextures[idx].Apply(); } } else { videoTextures[idx] = new Texture2D(texWidth, texHeight, TextureFormat.RGBA32, false); videoTextures[idx].filterMode = FilterMode.Bilinear; videoTextures[idx].wrapMode = TextureWrapMode.Clamp; } tex_ids[idx] = videoTextures[idx].GetNativeTexturePtr().ToInt32(); } SetExternalTextures(videoPlayerPtr, tex_ids, tex_ids.Length, texWidth, texHeight); currentTexture = 0; UpdateStatusText(); } if (adjustAspectRatio) { AdjustAspectRatio(); } } private void UpdateStatusText() { float fps = CurrentPosition > 0 ? (framecount / (CurrentPosition / 1000f)) : CurrentPosition; string status = texWidth + " x " + texHeight + " buffer: " + (BufferedPosition / 1000) + " " + PlayerState + " fps: " + fps; if (statusText != null) { if (statusText.text != status) { statusText.text = status; Debug.Log("STATUS: " + status); } } } /// <summary> /// Issues the player event. /// </summary> /// <param name="evt">The event to send to the video player /// instance. /// </param> private void IssuePlayerEvent(RenderCommand evt) { if (renderEventFunction != IntPtr.Zero && evt != RenderCommand.None) { GL.IssuePluginEvent(renderEventFunction, videoPlayerEventBase + (int) evt); } } void Update() { while (ExecuteOnMainThread.Count > 0) { ExecuteOnMainThread.Dequeue().Invoke(); } } private IEnumerator CallPluginAtEndOfFrames() { if (processingRunning) { Debug.LogError("CallPluginAtEndOfFrames invoked while already running."); yield break; } // Only run while the video is playing. bool running = true; processingRunning = true; exitProcessing = false; WaitForEndOfFrame wfeof = new WaitForEndOfFrame(); while (running) { // Wait until all frame rendering is done yield return wfeof; if (exitProcessing) { running = false; break; } if (videoPlayerPtr != IntPtr.Zero) { CreateTextureForVideoMaybe(); } IntPtr tex = GetRenderableTextureId(videoPlayerPtr); currentTexture = 0; for (int i = 0; i < videoTextures.Length; i++) { if (tex == videoTextures[i].GetNativeTexturePtr()) { currentTexture = i; } } if (!VideoReady) { continue; } else if (framecount > 1 && PlayerState == VideoPlayerState.Ended) { running = false; } IssuePlayerEvent(RenderCommand.UpdateVideo); IssuePlayerEvent(RenderCommand.RenderMono); int w = GetWidth(videoPlayerPtr); int h = GetHeight(videoPlayerPtr); // Limit total pixel count to the same as 2160p. // 3840 * 2160 == 2880 * 2880 if (w * h > 2880 * 2880) { // Clamp the max resolution preserving aspect ratio. float aspectRoot = (float) Math.Sqrt(w / h); w = (int) (2880 * aspectRoot); h = (int) (2880 / aspectRoot); } texWidth = w; texHeight = h; if ((int) framecount % 30 == 0) { UpdateStatusText(); } long bp = BufferedPosition; if (bp != lastBufferedPosition) { lastBufferedPosition = bp; UpdateStatusText(); } } processingRunning = false; } public void RemoveOnVideoEventCallback(Action<int> callback) { if (onEventCallbacks != null) { onEventCallbacks.Remove(callback); } } public void SetOnVideoEventCallback(Action<int> callback) { if (onEventCallbacks == null) { onEventCallbacks = new List<Action<int>>(); } onEventCallbacks.Add(callback); SetOnVideoEventCallback(videoPlayerPtr, InternalOnVideoEventCallback, ToIntPtr(this)); } internal void FireVideoEvent(int eventId) { if (onEventCallbacks == null) { return; } // Copy the collection so the callbacks can remove themselves from the list. Action<int>[] cblist = onEventCallbacks.ToArray(); foreach (Action<int> cb in cblist) { try { cb(eventId); } catch (Exception e) { Debug.LogError("exception calling callback: " + e); } } } [AOT.MonoPInvokeCallback(typeof(OnVideoEventCallback))] static void InternalOnVideoEventCallback(IntPtr cbdata, int eventId) { if (cbdata == IntPtr.Zero) { return; } GvrVideoPlayerTexture player; var gcHandle = GCHandle.FromIntPtr(cbdata); try { player = (GvrVideoPlayerTexture) gcHandle.Target; } catch (InvalidCastException e) { Debug.LogError("GC Handle pointed to unexpected type: " + gcHandle.Target + ". Expected " + typeof(GvrVideoPlayerTexture)); throw e; } if (player != null) { ExecuteOnMainThread.Enqueue(() => player.FireVideoEvent(eventId)); } } public void SetOnExceptionCallback(Action<string, string> callback) { if (onExceptionCallbacks == null) { onExceptionCallbacks = new List<Action<string, string>>(); SetOnExceptionCallback(videoPlayerPtr, InternalOnExceptionCallback, ToIntPtr(this)); } onExceptionCallbacks.Add(callback); } [AOT.MonoPInvokeCallback(typeof(OnExceptionCallback))] static void InternalOnExceptionCallback(string type, string msg, IntPtr cbdata) { if (cbdata == IntPtr.Zero) { return; } GvrVideoPlayerTexture player; var gcHandle = GCHandle.FromIntPtr(cbdata); try { player = (GvrVideoPlayerTexture) gcHandle.Target; } catch (InvalidCastException e) { Debug.LogError("GC Handle pointed to unexpected type: " + gcHandle.Target + ". Expected " + typeof(GvrVideoPlayerTexture)); throw e; } if (player != null) { ExecuteOnMainThread.Enqueue(() => player.FireOnException(type, msg)); } } internal void FireOnException(string type, string msg) { if (onExceptionCallbacks == null) { return; } foreach (Action<string, string> cb in onExceptionCallbacks) { try { cb(type, msg); } catch (Exception e) { Debug.LogError("exception calling callback: " + e); } } } internal static IntPtr ToIntPtr(System.Object obj) { GCHandle handle = GCHandle.Alloc(obj); return GCHandle.ToIntPtr(handle); } internal string ProcessURL() { return videoURL.Replace("${Application.dataPath}", Application.dataPath); } internal delegate void OnVideoEventCallback(IntPtr cbdata, int eventId); internal delegate void OnExceptionCallback(string type, string msg, IntPtr cbdata); #if UNITY_ANDROID && !UNITY_EDITOR private const string dllName = "gvrvideo"; [DllImport(dllName)] private static extern IntPtr GetRenderEventFunc(); [DllImport(dllName)] private static extern void SetExternalTextures(IntPtr videoPlayerPtr, int[] texIds, int size, int w, int h); [DllImport(dllName)] private static extern IntPtr GetRenderableTextureId(IntPtr videoPlayerPtr); // Keep public so we can check for the dll being present at runtime. [DllImport(dllName)] public static extern IntPtr CreateVideoPlayer(); // Keep public so we can check for the dll being present at runtime. [DllImport(dllName)] public static extern void DestroyVideoPlayer(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern int GetVideoPlayerEventBase(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern IntPtr InitVideoPlayer(IntPtr videoPlayerPtr, int videoType, string videoURL, string contentID, string providerId, bool useSecurePath, bool useExisting); [DllImport(dllName)] private static extern void SetInitialResolution(IntPtr videoPlayerPtr, int initialResolution); [DllImport(dllName)] private static extern int GetPlayerState(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern int GetWidth(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern int GetHeight(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern int PlayVideo(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern int PauseVideo(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern bool IsVideoReady(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern bool IsVideoPaused(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern long GetDuration(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern long GetBufferedPosition(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern long GetCurrentPosition(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern void SetCurrentPosition(IntPtr videoPlayerPtr, long pos); [DllImport(dllName)] private static extern int GetBufferedPercentage(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern int GetMaxVolume(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern int GetCurrentVolume(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern void SetCurrentVolume(IntPtr videoPlayerPtr, int value); [DllImport(dllName)] private static extern bool SetVideoPlayerSupportClassname( IntPtr videoPlayerPtr, string classname); [DllImport(dllName)] private static extern IntPtr GetRawPlayer(IntPtr videoPlayerPtr); [DllImport(dllName)] private static extern void SetOnVideoEventCallback(IntPtr videoPlayerPtr, OnVideoEventCallback callback, IntPtr callback_arg); [DllImport(dllName)] private static extern void SetOnExceptionCallback(IntPtr videoPlayerPtr, OnExceptionCallback callback, IntPtr callback_arg); #else private const string NOT_IMPLEMENTED_MSG = "Not implemented on this platform"; private static IntPtr GetRenderEventFunc() { Debug.Log(NOT_IMPLEMENTED_MSG); return IntPtr.Zero; } private static void SetExternalTextures(IntPtr videoPlayerPtr, int[] texIds, int size, int w, int h) { Debug.Log(NOT_IMPLEMENTED_MSG); } private static IntPtr GetRenderableTextureId(IntPtr videoPlayerPtr) { return IntPtr.Zero; } // Make this public so we can test the loading of the DLL. public static IntPtr CreateVideoPlayer() { Debug.Log(NOT_IMPLEMENTED_MSG); return IntPtr.Zero; } // Make this public so we can test the loading of the DLL. public static void DestroyVideoPlayer(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); } private static int GetVideoPlayerEventBase(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return 0; } private static IntPtr InitVideoPlayer(IntPtr videoPlayerPtr, int videoType, string videoURL, string contentID, string providerId, bool useSecurePath, bool useExisting) { Debug.Log(NOT_IMPLEMENTED_MSG); return IntPtr.Zero; } private static void SetInitialResolution(IntPtr videoPlayerPtr, int initialResolution) { Debug.Log(NOT_IMPLEMENTED_MSG); } private static int GetPlayerState(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return -1; } private static int GetWidth(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return -1; } private static int GetHeight(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return -1; } private static int PlayVideo(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return 0; } private static int PauseVideo(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return 0; } private static bool IsVideoReady(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return false; } private static bool IsVideoPaused(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return true; } private static long GetDuration(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return -1; } private static long GetBufferedPosition(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return -1; } private static long GetCurrentPosition(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return -1; } private static void SetCurrentPosition(IntPtr videoPlayerPtr, long pos) { Debug.Log(NOT_IMPLEMENTED_MSG); } private static int GetBufferedPercentage(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return 0; } private static int GetMaxVolume(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return 0; } private static int GetCurrentVolume(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return 0; } private static void SetCurrentVolume(IntPtr videoPlayerPtr, int value) { Debug.Log(NOT_IMPLEMENTED_MSG); } private static bool SetVideoPlayerSupportClassname(IntPtr videoPlayerPtr, string classname) { Debug.Log(NOT_IMPLEMENTED_MSG); return false; } private static IntPtr GetRawPlayer(IntPtr videoPlayerPtr) { Debug.Log(NOT_IMPLEMENTED_MSG); return IntPtr.Zero; } private static void SetOnVideoEventCallback(IntPtr videoPlayerPtr, OnVideoEventCallback callback, IntPtr callback_arg) { Debug.Log(NOT_IMPLEMENTED_MSG); } private static void SetOnExceptionCallback(IntPtr videoPlayerPtr, OnExceptionCallback callback, IntPtr callback_arg) { Debug.Log(NOT_IMPLEMENTED_MSG); } #endif // UNITY_ANDROID && !UNITY_EDITOR }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Net.Interop; using System; using System.Buffers; namespace Microsoft.Net.Sockets { public struct TcpServer { IntPtr _handle; public TcpServer(ushort port, byte address1, byte address2, byte address3, byte address4) { var version = new TcpServer.Version(2, 2); WSDATA data; int result = SocketImports.WSAStartup((short)version.Raw, out data); if (result != 0) { var error = SocketImports.WSAGetLastError(); throw new Exception(String.Format("ERROR: WSAStartup returned {0}", error)); } _handle = SocketImports.socket(ADDRESS_FAMILIES.AF_INET, SOCKET_TYPE.SOCK_STREAM, PROTOCOL.IPPROTO_TCP); if (_handle == IntPtr.Zero) { var error = SocketImports.WSAGetLastError(); SocketImports.WSACleanup(); throw new Exception(String.Format("ERROR: socket returned {0}", error)); } Start(port, address1, address2, address3, address4); } private void Start(ushort port, byte address1, byte address2, byte address3, byte address4) { // BIND in_addr inAddress = new in_addr(); inAddress.s_b1 = address1; inAddress.s_b2 = address2; inAddress.s_b3 = address3; inAddress.s_b4 = address4; sockaddr_in sa = new sockaddr_in(); sa.sin_family = ADDRESS_FAMILIES.AF_INET; sa.sin_port = SocketImports.htons(port); sa.sin_addr = inAddress; int result; unsafe { var size = sizeof(sockaddr_in); result = SocketImports.bind(_handle, ref sa, size); } if (result == SocketImports.SOCKET_ERROR) { SocketImports.WSACleanup(); throw new Exception("bind failed"); } // LISTEN result = SocketImports.listen(_handle, 10); if (result == SocketImports.SOCKET_ERROR) { SocketImports.WSACleanup(); throw new Exception("listen failed"); } } public TcpConnection Accept() { IntPtr accepted = SocketImports.accept(_handle, IntPtr.Zero, 0); if (accepted == new IntPtr(-1)) { var error = SocketImports.WSAGetLastError(); SocketImports.WSACleanup(); throw new Exception(String.Format("listen failed with {0}", error)); } return new TcpConnection(accepted); } public void Stop() { SocketImports.WSACleanup(); } public struct Version { public ushort Raw; public Version(byte major, byte minor) { Raw = major; Raw <<= 8; Raw += minor; } public byte Major { get { UInt16 result = Raw; result >>= 8; return (byte)result; } } public byte Minor { get { UInt16 result = Raw; result &= 0x00FF; return (byte)result; } } public override string ToString() { return String.Format("{0}.{1}", Major, Minor); } } } public struct TcpConnection { IntPtr _handle; public TcpConnection(IntPtr handle) { _handle = handle; } public IntPtr Handle { get { return _handle; } } public int Receive(byte[] bytes) { unsafe { fixed (byte* buffer = bytes) { IntPtr ptr = new IntPtr(buffer); int bytesReceived = SocketImports.recv(Handle, ptr, bytes.Length, 0); if (bytesReceived < 0) { var error = SocketImports.WSAGetLastError(); throw new Exception(String.Format("receive failed with {0}", error)); } return bytesReceived; } } } public void Close() { SocketImports.closesocket(_handle); } public unsafe int Send(ReadOnlySpan<byte> buffer) { // TODO: This can work with Span<byte> because it's synchronous but we need async pinning support fixed (byte* bytes = &buffer.DangerousGetPinnableReference()) { IntPtr pointer = new IntPtr(bytes); return SendPinned(pointer, buffer.Length); } } public int Send(ReadOnlyBuffer<byte> buffer) { return Send(buffer.Span); } public int Send(ArraySegment<byte> buffer) { return Send(buffer.Array, buffer.Offset, buffer.Count); } public int Send(byte[] bytes, int offset, int count) { unsafe { fixed (byte* buffer = bytes) { IntPtr pointer = new IntPtr(buffer + offset); return SendPinned(pointer, count); } } } public unsafe int Receive(Span<byte> buffer) { // TODO: This can work with Span<byte> because it's synchronous but we need async pinning support fixed (byte* bytes = &buffer.DangerousGetPinnableReference()) { IntPtr pointer = new IntPtr(bytes); return ReceivePinned(pointer, buffer.Length); } } public int Receive(Buffer<byte> buffer) { return Receive(buffer.Span); } public int Receive(ArraySegment<byte> buffer) { return Receive(buffer.Array, buffer.Offset, buffer.Count); } public int Receive(byte[] array, int offset, int count) { unsafe { fixed (byte* buffer = array) { IntPtr pointer = new IntPtr(buffer + offset); return ReceivePinned(pointer, count); } } } private unsafe int SendPinned(IntPtr buffer, int length) { int bytesSent = SocketImports.send(_handle, buffer, length, 0); if (bytesSent == SocketImports.SOCKET_ERROR) { var error = SocketImports.WSAGetLastError(); throw new Exception(String.Format("send failed with {0}", error)); } return bytesSent; } private int ReceivePinned(IntPtr ptr, int length) { int bytesReceived = SocketImports.recv(Handle, ptr, length, 0); if (bytesReceived < 0) { var error = SocketImports.WSAGetLastError(); throw new Exception(String.Format("receive failed with {0}", error)); } return bytesReceived; } } }
using System.Runtime.Serialization; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using Newtonsoft.Json; #if NETFULL using System.Web; using StackifyLib.Web; #endif namespace StackifyLib.Models { [JsonObject] public class WebRequestDetail { public delegate void SetWebRequestDetailEventHandler(WebRequestDetail detail); public static event SetWebRequestDetailEventHandler SetWebRequestDetail; private StackifyError _Error; public WebRequestDetail() { } public WebRequestDetail(StackifyError error) { _Error = error; #if NETFULL if (System.Web.HttpContext.Current != null) { Load(new HttpContextWrapper(System.Web.HttpContext.Current)); } #endif //if something has subscribed to this, like our AspNetCore library SetWebRequestDetail?.Invoke(this); } [JsonProperty] public string UserIPAddress { get; set; } [JsonProperty] public string HttpMethod { get; set; } [JsonProperty] public string RequestProtocol { get; set; } [JsonProperty] public string RequestUrl { get; set; } [JsonProperty] public string RequestUrlRoot { get; set; } [JsonProperty] public string ReportingUrl { get; set; } [JsonProperty] public string ReferralUrl { get; set; } [JsonProperty] public string UserAgent { get; set; } [JsonProperty] public Dictionary<string, string> Headers { get; set; } [JsonProperty] public Dictionary<string, string> Cookies { get; set; } [JsonProperty] public Dictionary<string, string> QueryString { get; set; } [JsonProperty] public Dictionary<string, string> PostData { get; set; } [JsonProperty] public Dictionary<string, string> SessionData { get; set; } [JsonProperty] public string PostDataRaw { get; set; } [JsonProperty] public string MVCAction { get; set; } [JsonProperty] public string MVCController { get; set; } [JsonProperty] public string MVCArea { get; set; } #if NETFULL public void Load(HttpContextBase context) { if (context == null || context.Request == null) return; HttpRequestBase request = context.Request; try { HttpMethod = request.RequestType; UserIPAddress = request.UserHostAddress; UserAgent = request.UserAgent; if (context.Items != null && context.Items.Contains("Stackify.ReportingUrl")) { ReportingUrl = context.Items["Stackify.ReportingUrl"].ToString(); } //We be nice to detect if it is a web sockets connection and denote that in the protocol field //do we care about things like HTTP/1.1 or the port? if (request.IsSecureConnection) { RequestProtocol = "https"; } else { RequestProtocol = "http"; } if (request.Url != null) { RequestUrl = request.Url.ToString(); } if (request.AppRelativeCurrentExecutionFilePath != null) { RequestUrlRoot = request.AppRelativeCurrentExecutionFilePath.TrimStart('~'); } RouteResolver resolver = new RouteResolver(context); var route = resolver.GetRoute(); MVCArea = route.Area; MVCController = route.Controller; MVCAction = route.Action; if (string.IsNullOrEmpty(ReportingUrl) && route != null && !string.IsNullOrEmpty(route.Action)) { ReportingUrl = route.ToString(); } } catch { // ignored } try { if (request.QueryString != null) { QueryString = ToKeyValues(request.QueryString, null, null); } if (request.ServerVariables != null && Config.CaptureServerVariables) { List<string> badKeys = new List<string>(); badKeys.AddRange(new string[] { "all_http", "all_raw", "http_cookie" }); var serverVars = ToKeyValues(request.ServerVariables, null, badKeys); foreach (var serverVar in serverVars) { _Error.ServerVariables[serverVar.Key] = serverVar.Value; } } if (request.Headers != null && Config.CaptureErrorHeaders) { if (Config.ErrorHeaderBadKeys == null) { Config.ErrorHeaderBadKeys = new List<string>(); } if (!Config.ErrorHeaderBadKeys.Contains("cookie")) { Config.ErrorHeaderBadKeys.Add("cookie"); } if (!Config.ErrorHeaderBadKeys.Contains("authorization")) { Config.ErrorHeaderBadKeys.Add("authorization"); } Headers = ToKeyValues(request.Headers, Config.ErrorHeaderGoodKeys, Config.ErrorHeaderBadKeys); } if (request.Cookies != null && Config.CaptureErrorCookies) { Cookies = ToKeyValues(request.Cookies, Config.ErrorCookiesGoodKeys, Config.ErrorCookiesBadKeys); } if (request.Form != null && Config.CaptureErrorPostdata) { PostData = ToKeyValues(request.Form,null, null); } if (context.Session != null && Config.CaptureSessionVariables && Config.ErrorSessionGoodKeys.Any()) { SessionData = ToKeyValues(context.Session, Config.ErrorSessionGoodKeys, null); } } catch { // ignored } } #endif internal static void AddKey(string key, string value, Dictionary<string, string> dictionary, List<string> goodKeys, List<string> badKeys) { //is this key in the bad key list? if (badKeys != null && badKeys.Any(x => x.Equals(key, StringComparison.CurrentCultureIgnoreCase))) { dictionary[key] = "X-MASKED-X"; return; } //if not in the good key list, return //if good key list is empty, we let it take it else if (goodKeys != null && goodKeys.Any() && !goodKeys.Any(x => x.Equals(key, StringComparison.CurrentCultureIgnoreCase))) { return; } dictionary[key] = value; } #if NETFULL internal static Dictionary<string, string> ToKeyValues(HttpSessionStateBase collection, List<string> goodKeys, List<string> badKeys) { var keys = collection.Keys; var items = new Dictionary<string, string>(); foreach (string key in keys) { try { HttpCookie cookie = collection[key] as HttpCookie; if (cookie != null && !string.IsNullOrWhiteSpace(cookie.Value) && !items.ContainsKey(key)) { AddKey(key, cookie.Value, items, goodKeys, badKeys); } } catch { // ignored } } return items; } internal static Dictionary<string, string> ToKeyValues(HttpCookieCollection collection, List<string> goodKeys, List<string> badKeys) { var keys = collection.Keys; var items = new Dictionary<string, string>(); foreach (string key in keys) { try { HttpCookie cookie = collection[key] as HttpCookie; if (cookie != null && !string.IsNullOrWhiteSpace(cookie.Value) && !items.ContainsKey(key)) { AddKey(key, cookie.Value, items, goodKeys, badKeys); } } catch { // ignored } } return items; } internal static Dictionary<string, string> ToKeyValues(NameValueCollection collection, List<string> goodKeys, List<string> badKeys) { var keys = collection.AllKeys; var items = new Dictionary<string, string>(); foreach (string key in keys) { try { string val = collection[key]; AddKey(key, val, items, goodKeys, badKeys); } catch { // ignored } } return items; } internal static Dictionary<string, string> ToKeyValues(System.Web.SessionState.HttpSessionState collection, List<string> goodKeys, List<string> badKeys) { var keys = collection.Keys; var items = new Dictionary<string, string>(); foreach (string key in keys) { try { object val = collection[key]; if (val != null && !string.IsNullOrWhiteSpace(val.ToString()) && items.ContainsKey(key)) { AddKey(key, val.ToString(), items, goodKeys, badKeys); } } catch { // ignored } } return items; } #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. /****************************************************************************** * 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 OrUInt32() { var test = new SimpleBinaryOpTest__OrUInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__OrUInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt32> _fld1; public Vector256<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__OrUInt32 testClass) { var result = Avx2.Or(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrUInt32 testClass) { fixed (Vector256<UInt32>* pFld1 = &_fld1) fixed (Vector256<UInt32>* pFld2 = &_fld2) { var result = Avx2.Or( Avx.LoadVector256((UInt32*)(pFld1)), Avx.LoadVector256((UInt32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector256<UInt32> _clsVar1; private static Vector256<UInt32> _clsVar2; private Vector256<UInt32> _fld1; private Vector256<UInt32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__OrUInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); } public SimpleBinaryOpTest__OrUInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new UInt32[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.Or( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Or( Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Or( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector256<UInt32>* pClsVar2 = &_clsVar2) { var result = Avx2.Or( Avx.LoadVector256((UInt32*)(pClsVar1)), Avx.LoadVector256((UInt32*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__OrUInt32(); var result = Avx2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__OrUInt32(); fixed (Vector256<UInt32>* pFld1 = &test._fld1) fixed (Vector256<UInt32>* pFld2 = &test._fld2) { var result = Avx2.Or( Avx.LoadVector256((UInt32*)(pFld1)), Avx.LoadVector256((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<UInt32>* pFld1 = &_fld1) fixed (Vector256<UInt32>* pFld2 = &_fld2) { var result = Avx2.Or( Avx.LoadVector256((UInt32*)(pFld1)), Avx.LoadVector256((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.Or( Avx.LoadVector256((UInt32*)(&test._fld1)), Avx.LoadVector256((UInt32*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<UInt32> op1, Vector256<UInt32> op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((uint)(left[0] | right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((uint)(left[i] | right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Or)}<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityEngine.VR; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(CapsuleCollider))] public class RigidbodyFirstPersonController : MonoBehaviour { [Serializable] public class MovementSettings { public float ForwardSpeed = 8.0f; // Speed when walking forward public float BackwardSpeed = 4.0f; // Speed when walking backwards public float StrafeSpeed = 4.0f; // Speed when walking sideways public float RunMultiplier = 2.0f; // Speed when sprinting public KeyCode RunKey = KeyCode.LeftShift; public float JumpForce = 30f; public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f)); [HideInInspector] public float CurrentTargetSpeed = 8f; #if !MOBILE_INPUT private bool m_Running; #endif public void UpdateDesiredTargetSpeed(Vector2 input) { if (input == Vector2.zero) return; if (input.x > 0 || input.x < 0) { //strafe CurrentTargetSpeed = StrafeSpeed; } if (input.y < 0) { //backwards CurrentTargetSpeed = BackwardSpeed; } if (input.y > 0) { //forwards //handled last as if strafing and moving forward at the same time forwards speed should take precedence CurrentTargetSpeed = ForwardSpeed; } #if !MOBILE_INPUT if (Input.GetKey(RunKey)) { CurrentTargetSpeed *= RunMultiplier; m_Running = true; } else { m_Running = false; } #endif } #if !MOBILE_INPUT public bool Running { get { return m_Running; } } #endif } bool wasTouching = false; [Serializable] public class AdvancedSettings { public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this ) public float stickToGroundHelperDistance = 0.5f; // stops the character public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input public bool airControl; // can the user control the direction that is being moved in the air [Tooltip("set it to 0.1 or more if you get stuck in wall")] public float shellOffset; //reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice) } public Camera cam; public MovementSettings movementSettings = new MovementSettings(); public MouseLook mouseLook = new MouseLook(); public AdvancedSettings advancedSettings = new AdvancedSettings(); private Rigidbody m_RigidBody; private CapsuleCollider m_Capsule; private float m_YRotation; private Vector3 m_GroundContactNormal; private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded; public Vector3 Velocity { get { return m_RigidBody.velocity; } } public bool Grounded { get { return m_IsGrounded; } } public bool Jumping { get { return m_Jumping; } } public bool Running { get { #if !MOBILE_INPUT return movementSettings.Running; #else return false; #endif } } private void Start() { m_RigidBody = GetComponent<Rigidbody>(); m_Capsule = GetComponent<CapsuleCollider>(); mouseLook.Init(transform, cam.transform); } private void Update() { RotateView(); if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump) { m_Jump = true; } } public void Move(Vector2 direction, float speed) { Vector3 desiredMove = cam.transform.forward * direction.x + cam.transform.right * direction.y; desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized; desiredMove.x = desiredMove.x * speed; desiredMove.z = desiredMove.z * speed; desiredMove.y = desiredMove.y * speed; if (m_RigidBody.velocity.sqrMagnitude < (movementSettings.CurrentTargetSpeed * movementSettings.CurrentTargetSpeed)) { m_RigidBody.AddForce(desiredMove * SlopeMultiplier(), ForceMode.Impulse); } } private void FixedUpdate() { GroundCheck(); if (Input.touchCount > 0) { // if (!wasTouching) // { Debug.Log("Touched"); Move(new Vector2(1, 0), 50f); wasTouching = true; // } } else { // wasTouching = false; } if (Input.GetKeyDown(KeyCode.W)) { if (true) //placeMnemonicMode { Move(new Vector2(1, 0), 50f); } //placeMnemonicMode = false; //todo: (hardcoded) } else if (Input.GetKeyDown(KeyCode.S)) { Move(new Vector2(-1, 0), 50f); } else if (Input.GetKeyDown(KeyCode.D)) { Move(new Vector2(0, 1), 50f); } else if (Input.GetKeyDown(KeyCode.A)) { Move(new Vector2(0, -1), 50f); } /* // read commands from the android part AndroidJavaClass pluginClass = new AndroidJavaClass("com.vroneinc.vrone.My_Plugin"); char moveCommand = pluginClass.CallStatic<char>("getBTCommand"); if (moveCommand == 'F' || Input.GetKeyDown(KeyCode.W)) { Move (new Vector2 (1, 0), 8f); } else if (moveCommand == 'B' || Input.GetKeyDown(KeyCode.S)) { Move (new Vector2 (-1, 0), 4f); } else if (moveCommand == 'L' || Input.GetKeyDown(KeyCode.A)) { Move (new Vector2 (0, 1), 4f); } else if (moveCommand == 'R' || Input.GetKeyDown(KeyCode.D)) { Move (new Vector2 (0, -1), 4f); } */ /* Vector2 input = GetInput(); if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded)) { // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = cam.transform.forward * input.y + cam.transform.right * input.x; desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized; desiredMove.x = desiredMove.x * movementSettings.CurrentTargetSpeed; desiredMove.z = desiredMove.z * movementSettings.CurrentTargetSpeed; desiredMove.y = desiredMove.y * movementSettings.CurrentTargetSpeed; if (m_RigidBody.velocity.sqrMagnitude < (movementSettings.CurrentTargetSpeed * movementSettings.CurrentTargetSpeed)) { m_RigidBody.AddForce(desiredMove * SlopeMultiplier(), ForceMode.Impulse); } } */ if (m_IsGrounded) { m_RigidBody.drag = 5f; if (m_Jump) { m_RigidBody.drag = 0f; m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z); m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse); m_Jumping = true; } /* if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f) { m_RigidBody.Sleep(); }*/ } else { m_RigidBody.drag = 0f; if (m_PreviouslyGrounded && !m_Jumping) { StickToGroundHelper(); } } m_Jump = false; } private float SlopeMultiplier() { float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up); return movementSettings.SlopeCurveModifier.Evaluate(angle); } private void StickToGroundHelper() { RaycastHit hitInfo; if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo, ((m_Capsule.height / 2f) - m_Capsule.radius) + advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore)) { if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f) { m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal); } } } private Vector2 GetInput() { Vector2 input = new Vector2 { x = CrossPlatformInputManager.GetAxis("Horizontal"), y = CrossPlatformInputManager.GetAxis("Vertical") }; movementSettings.UpdateDesiredTargetSpeed(input); return input; } private void RotateView() { //avoids the mouse looking if the game is effectively paused if (Mathf.Abs(Time.timeScale) < float.Epsilon) return; // get the rotation before it's changed float oldYRotation = transform.eulerAngles.y; mouseLook.LookRotation(transform, cam.transform); if (m_IsGrounded || advancedSettings.airControl) { // Rotate the rigidbody velocity to match the new direction that the character is looking Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up); m_RigidBody.velocity = velRotation * m_RigidBody.velocity; } } /// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom private void GroundCheck() { m_PreviouslyGrounded = m_IsGrounded; RaycastHit hitInfo; if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo, ((m_Capsule.height / 2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore)) { m_IsGrounded = true; m_GroundContactNormal = hitInfo.normal; } else { m_IsGrounded = false; m_GroundContactNormal = Vector3.up; } if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping) { m_Jumping = 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.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; namespace System.Runtime.Serialization.Formatters.Binary { internal sealed class BinaryFormatterWriter { private const int ChunkSize = 4096; private readonly Stream _outputStream; private readonly FormatterTypeStyle _formatterTypeStyle; private readonly ObjectWriter _objectWriter = null; private readonly BinaryWriter _dataWriter = null; private int _consecutiveNullArrayEntryCount = 0; private Dictionary<string, ObjectMapInfo> _objectMapTable; private BinaryObject _binaryObject; private BinaryObjectWithMap _binaryObjectWithMap; private BinaryObjectWithMapTyped _binaryObjectWithMapTyped; private BinaryObjectString _binaryObjectString; private BinaryArray _binaryArray; private byte[] _byteBuffer = null; private MemberPrimitiveUnTyped _memberPrimitiveUnTyped; private MemberPrimitiveTyped _memberPrimitiveTyped; private ObjectNull _objectNull; private MemberReference _memberReference; private BinaryAssembly _binaryAssembly; internal BinaryFormatterWriter(Stream outputStream, ObjectWriter objectWriter, FormatterTypeStyle formatterTypeStyle) { _outputStream = outputStream; _formatterTypeStyle = formatterTypeStyle; _objectWriter = objectWriter; _dataWriter = new BinaryWriter(outputStream, Encoding.UTF8); } internal void WriteBegin() { } internal void WriteEnd() { _dataWriter.Flush(); } internal void WriteBoolean(bool value) => _dataWriter.Write(value); internal void WriteByte(byte value) => _dataWriter.Write(value); private void WriteBytes(byte[] value) => _dataWriter.Write(value); private void WriteBytes(byte[] byteA, int offset, int size) => _dataWriter.Write(byteA, offset, size); internal void WriteChar(char value) => _dataWriter.Write(value); internal void WriteChars(char[] value) => _dataWriter.Write(value); internal void WriteDecimal(decimal value) => WriteString(value.ToString(CultureInfo.InvariantCulture)); internal void WriteSingle(float value) => _dataWriter.Write(value); internal void WriteDouble(double value) => _dataWriter.Write(value); internal void WriteInt16(short value) => _dataWriter.Write(value); internal void WriteInt32(int value) => _dataWriter.Write(value); internal void WriteInt64(long value) => _dataWriter.Write(value); internal void WriteSByte(sbyte value) => WriteByte(unchecked((byte)value)); internal void WriteString(string value) => _dataWriter.Write(value); internal void WriteTimeSpan(TimeSpan value) => WriteInt64(value.Ticks); internal void WriteDateTime(DateTime value) => WriteInt64(value.Ticks); // in desktop, this uses ToBinaryRaw internal void WriteUInt16(ushort value) => _dataWriter.Write(value); internal void WriteUInt32(uint value) => _dataWriter.Write(value); internal void WriteUInt64(ulong value) => _dataWriter.Write(value); internal void WriteObjectEnd(NameInfo memberNameInfo, NameInfo typeNameInfo) { } internal void WriteSerializationHeaderEnd() { var record = new MessageEnd(); record.Write(this); } internal void WriteSerializationHeader(int topId, int headerId, int minorVersion, int majorVersion) { var record = new SerializationHeaderRecord(BinaryHeaderEnum.SerializedStreamHeader, topId, headerId, minorVersion, majorVersion); record.Write(this); } internal void WriteObject(NameInfo nameInfo, NameInfo typeNameInfo, int numMembers, string[] memberNames, Type[] memberTypes, WriteObjectInfo[] memberObjectInfos) { InternalWriteItemNull(); int assemId; int objectId = (int)nameInfo._objectId; string objectName = objectId < 0 ? objectName = typeNameInfo.NIname : // Nested Object objectName = nameInfo.NIname; // Non-Nested if (_objectMapTable == null) { _objectMapTable = new Dictionary<string, ObjectMapInfo>(); } ObjectMapInfo objectMapInfo; if (_objectMapTable.TryGetValue(objectName, out objectMapInfo) && objectMapInfo.IsCompatible(numMembers, memberNames, memberTypes)) { // Object if (_binaryObject == null) { _binaryObject = new BinaryObject(); } _binaryObject.Set(objectId, objectMapInfo._objectId); _binaryObject.Write(this); } else if (!typeNameInfo._transmitTypeOnObject) { // ObjectWithMap if (_binaryObjectWithMap == null) { _binaryObjectWithMap = new BinaryObjectWithMap(); } // BCL types are not placed into table assemId = (int)typeNameInfo._assemId; _binaryObjectWithMap.Set(objectId, objectName, numMembers, memberNames, assemId); _binaryObjectWithMap.Write(this); if (objectMapInfo == null) { _objectMapTable.Add(objectName, new ObjectMapInfo(objectId, numMembers, memberNames, memberTypes)); } } else { // ObjectWithMapTyped var binaryTypeEnumA = new BinaryTypeEnum[numMembers]; var typeInformationA = new object[numMembers]; var assemIdA = new int[numMembers]; for (int i = 0; i < numMembers; i++) { object typeInformation = null; binaryTypeEnumA[i] = BinaryTypeConverter.GetBinaryTypeInfo(memberTypes[i], memberObjectInfos[i], null, _objectWriter, out typeInformation, out assemId); typeInformationA[i] = typeInformation; assemIdA[i] = assemId; } if (_binaryObjectWithMapTyped == null) { _binaryObjectWithMapTyped = new BinaryObjectWithMapTyped(); } // BCL types are not placed in table assemId = (int)typeNameInfo._assemId; _binaryObjectWithMapTyped.Set(objectId, objectName, numMembers, memberNames, binaryTypeEnumA, typeInformationA, assemIdA, assemId); _binaryObjectWithMapTyped.Write(this); if (objectMapInfo == null) { _objectMapTable.Add(objectName, new ObjectMapInfo(objectId, numMembers, memberNames, memberTypes)); } } } internal void WriteObjectString(int objectId, string value) { InternalWriteItemNull(); if (_binaryObjectString == null) { _binaryObjectString = new BinaryObjectString(); } _binaryObjectString.Set(objectId, value); _binaryObjectString.Write(this); } internal void WriteSingleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, Array array) { InternalWriteItemNull(); BinaryArrayTypeEnum binaryArrayTypeEnum; var lengthA = new int[1]; lengthA[0] = length; int[] lowerBoundA = null; object typeInformation = null; if (lowerBound == 0) { binaryArrayTypeEnum = BinaryArrayTypeEnum.Single; } else { binaryArrayTypeEnum = BinaryArrayTypeEnum.SingleOffset; lowerBoundA = new int[1]; lowerBoundA[0] = lowerBound; } int assemId; BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo( arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); if (_binaryArray == null) { _binaryArray = new BinaryArray(); } _binaryArray.Set((int)arrayNameInfo._objectId, 1, lengthA, lowerBoundA, binaryTypeEnum, typeInformation, binaryArrayTypeEnum, assemId); _binaryArray.Write(this); if (Converter.IsWriteAsByteArray(arrayElemTypeNameInfo._primitiveTypeEnum) && (lowerBound == 0)) { //array is written out as an array of bytes if (arrayElemTypeNameInfo._primitiveTypeEnum == InternalPrimitiveTypeE.Byte) { WriteBytes((byte[])array); } else if (arrayElemTypeNameInfo._primitiveTypeEnum == InternalPrimitiveTypeE.Char) { WriteChars((char[])array); } else { WriteArrayAsBytes(array, Converter.TypeLength(arrayElemTypeNameInfo._primitiveTypeEnum)); } } } private void WriteArrayAsBytes(Array array, int typeLength) { InternalWriteItemNull(); int byteLength = array.Length * typeLength; int arrayOffset = 0; if (_byteBuffer == null) { _byteBuffer = new byte[ChunkSize]; } while (arrayOffset < array.Length) { int numArrayItems = Math.Min(ChunkSize / typeLength, array.Length - arrayOffset); int bufferUsed = numArrayItems * typeLength; Buffer.BlockCopy(array, arrayOffset * typeLength, _byteBuffer, 0, bufferUsed); if (!BitConverter.IsLittleEndian) { // we know that we are writing a primitive type, so just do a simple swap Debug.Fail("Re-review this code if/when we start running on big endian systems"); for (int i = 0; i < bufferUsed; i += typeLength) { for (int j = 0; j < typeLength / 2; j++) { byte tmp = _byteBuffer[i + j]; _byteBuffer[i + j] = _byteBuffer[i + typeLength - 1 - j]; _byteBuffer[i + typeLength - 1 - j] = tmp; } } } WriteBytes(_byteBuffer, 0, bufferUsed); arrayOffset += numArrayItems; } } internal void WriteJaggedArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound) { InternalWriteItemNull(); BinaryArrayTypeEnum binaryArrayTypeEnum; var lengthA = new int[1]; lengthA[0] = length; int[] lowerBoundA = null; object typeInformation = null; int assemId = 0; if (lowerBound == 0) { binaryArrayTypeEnum = BinaryArrayTypeEnum.Jagged; } else { binaryArrayTypeEnum = BinaryArrayTypeEnum.JaggedOffset; lowerBoundA = new int[1]; lowerBoundA[0] = lowerBound; } BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); if (_binaryArray == null) { _binaryArray = new BinaryArray(); } _binaryArray.Set((int)arrayNameInfo._objectId, 1, lengthA, lowerBoundA, binaryTypeEnum, typeInformation, binaryArrayTypeEnum, assemId); _binaryArray.Write(this); } internal void WriteRectangleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int rank, int[] lengthA, int[] lowerBoundA) { InternalWriteItemNull(); BinaryArrayTypeEnum binaryArrayTypeEnum = BinaryArrayTypeEnum.Rectangular; object typeInformation = null; int assemId = 0; BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); if (_binaryArray == null) { _binaryArray = new BinaryArray(); } for (int i = 0; i < rank; i++) { if (lowerBoundA[i] != 0) { binaryArrayTypeEnum = BinaryArrayTypeEnum.RectangularOffset; break; } } _binaryArray.Set((int)arrayNameInfo._objectId, rank, lengthA, lowerBoundA, binaryTypeEnum, typeInformation, binaryArrayTypeEnum, assemId); _binaryArray.Write(this); } internal void WriteObjectByteArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, byte[] byteA) { InternalWriteItemNull(); WriteSingleArray(memberNameInfo, arrayNameInfo, objectInfo, arrayElemTypeNameInfo, length, lowerBound, byteA); } internal void WriteMember(NameInfo memberNameInfo, NameInfo typeNameInfo, object value) { InternalWriteItemNull(); InternalPrimitiveTypeE typeInformation = typeNameInfo._primitiveTypeEnum; // Writes Members with primitive values if (memberNameInfo._transmitTypeOnMember) { if (_memberPrimitiveTyped == null) { _memberPrimitiveTyped = new MemberPrimitiveTyped(); } _memberPrimitiveTyped.Set(typeInformation, value); _memberPrimitiveTyped.Write(this); } else { if (_memberPrimitiveUnTyped == null) { _memberPrimitiveUnTyped = new MemberPrimitiveUnTyped(); } _memberPrimitiveUnTyped.Set(typeInformation, value); _memberPrimitiveUnTyped.Write(this); } } internal void WriteNullMember(NameInfo memberNameInfo, NameInfo typeNameInfo) { InternalWriteItemNull(); if (_objectNull == null) { _objectNull = new ObjectNull(); } if (!memberNameInfo._isArrayItem) { _objectNull.SetNullCount(1); _objectNull.Write(this); _consecutiveNullArrayEntryCount = 0; } } internal void WriteMemberObjectRef(NameInfo memberNameInfo, int idRef) { InternalWriteItemNull(); if (_memberReference == null) { _memberReference = new MemberReference(); } _memberReference.Set(idRef); _memberReference.Write(this); } internal void WriteMemberNested(NameInfo memberNameInfo) { InternalWriteItemNull(); } internal void WriteMemberString(NameInfo memberNameInfo, NameInfo typeNameInfo, string value) { InternalWriteItemNull(); WriteObjectString((int)typeNameInfo._objectId, value); } internal void WriteItem(NameInfo itemNameInfo, NameInfo typeNameInfo, object value) { InternalWriteItemNull(); WriteMember(itemNameInfo, typeNameInfo, value); } internal void WriteNullItem(NameInfo itemNameInfo, NameInfo typeNameInfo) { _consecutiveNullArrayEntryCount++; InternalWriteItemNull(); } internal void WriteDelayedNullItem() { _consecutiveNullArrayEntryCount++; } internal void WriteItemEnd() => InternalWriteItemNull(); private void InternalWriteItemNull() { if (_consecutiveNullArrayEntryCount > 0) { if (_objectNull == null) { _objectNull = new ObjectNull(); } _objectNull.SetNullCount(_consecutiveNullArrayEntryCount); _objectNull.Write(this); _consecutiveNullArrayEntryCount = 0; } } internal void WriteItemObjectRef(NameInfo nameInfo, int idRef) { InternalWriteItemNull(); WriteMemberObjectRef(nameInfo, idRef); } internal void WriteAssembly(Type type, string assemblyString, int assemId, bool isNew) { //If the file being tested wasn't built as an assembly, then we're going to get null back //for the assembly name. This is very unfortunate. InternalWriteItemNull(); if (assemblyString == null) { assemblyString = string.Empty; } if (isNew) { if (_binaryAssembly == null) { _binaryAssembly = new BinaryAssembly(); } _binaryAssembly.Set(assemId, assemblyString); _binaryAssembly.Write(this); } } // Method to write a value onto a stream given its primitive type code internal void WriteValue(InternalPrimitiveTypeE code, object value) { switch (code) { case InternalPrimitiveTypeE.Boolean: WriteBoolean(Convert.ToBoolean(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Byte: WriteByte(Convert.ToByte(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Char: WriteChar(Convert.ToChar(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Double: WriteDouble(Convert.ToDouble(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Int16: WriteInt16(Convert.ToInt16(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Int32: WriteInt32(Convert.ToInt32(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Int64: WriteInt64(Convert.ToInt64(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.SByte: WriteSByte(Convert.ToSByte(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Single: WriteSingle(Convert.ToSingle(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.UInt16: WriteUInt16(Convert.ToUInt16(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.UInt32: WriteUInt32(Convert.ToUInt32(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.UInt64: WriteUInt64(Convert.ToUInt64(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Decimal: WriteDecimal(Convert.ToDecimal(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.TimeSpan: WriteTimeSpan((TimeSpan)value); break; case InternalPrimitiveTypeE.DateTime: WriteDateTime((DateTime)value); break; default: throw new SerializationException(SR.Format(SR.Serialization_TypeCode, code.ToString())); } } private sealed class ObjectMapInfo { internal readonly int _objectId; private readonly int _numMembers; private readonly string[] _memberNames; private readonly Type[] _memberTypes; internal ObjectMapInfo(int objectId, int numMembers, string[] memberNames, Type[] memberTypes) { _objectId = objectId; _numMembers = numMembers; _memberNames = memberNames; _memberTypes = memberTypes; } internal bool IsCompatible(int numMembers, string[] memberNames, Type[] memberTypes) { if (_numMembers != numMembers) { return false; } for (int i = 0; i < numMembers; i++) { if (!(_memberNames[i].Equals(memberNames[i]))) { return false; } if ((memberTypes != null) && (_memberTypes[i] != memberTypes[i])) { return false; } } return true; } } } }
/* * 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.IO; using System.Reflection; using System.Threading; using System.Text; using System.Xml; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Servers; using log4net; using log4net.Config; using log4net.Appender; using log4net.Core; using log4net.Repository; using Nini.Config; namespace OpenSim.Server.Base { public class ServicesServerBase : ServerBase { // Logger // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // Command line args // protected string[] m_Arguments; protected string m_configDirectory = "."; // Run flag // private bool m_Running = true; #if (_MONO) private static Mono.Unix.UnixSignal[] signals; #endif // Handle all the automagical stuff // public ServicesServerBase(string prompt, string[] args) : base() { // Save raw arguments m_Arguments = args; // Read command line ArgvConfigSource argvConfig = new ArgvConfigSource(args); argvConfig.AddSwitch("Startup", "console", "c"); argvConfig.AddSwitch("Startup", "logfile", "l"); argvConfig.AddSwitch("Startup", "inifile", "i"); argvConfig.AddSwitch("Startup", "prompt", "p"); argvConfig.AddSwitch("Startup", "logconfig", "g"); // Automagically create the ini file name string fileName = ""; if (Assembly.GetEntryAssembly() != null) fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location); string iniFile = fileName + ".ini"; string logConfig = null; IConfig startupConfig = argvConfig.Configs["Startup"]; if (startupConfig != null) { // Check if a file name was given on the command line iniFile = startupConfig.GetString("inifile", iniFile); // Check if a prompt was given on the command line prompt = startupConfig.GetString("prompt", prompt); // Check for a Log4Net config file on the command line logConfig =startupConfig.GetString("logconfig", logConfig); } Config = ReadConfigSource(iniFile); List<string> sources = new List<string>(); sources.Add(iniFile); int sourceIndex = 1; while (AddIncludes(Config, sources)) { for ( ; sourceIndex < sources.Count ; ++sourceIndex) { IConfigSource s = ReadConfigSource(sources[sourceIndex]); Config.Merge(s); } } // Merge OpSys env vars Console.WriteLine("[CONFIG]: Loading environment variables for Config"); Util.MergeEnvironmentToConfig(Config); // Merge the configuration from the command line into the loaded file Config.Merge(argvConfig); Config.ReplaceKeyValues(); // Refresh the startupConfig post merge if (Config.Configs["Startup"] != null) { startupConfig = Config.Configs["Startup"]; } if (startupConfig != null) { m_configDirectory = startupConfig.GetString("ConfigDirectory", m_configDirectory); prompt = startupConfig.GetString("Prompt", prompt); } // Allow derived classes to load config before the console is opened. ReadConfig(); // Create main console string consoleType = "local"; if (startupConfig != null) consoleType = startupConfig.GetString("console", consoleType); if (consoleType == "basic") { MainConsole.Instance = new CommandConsole(prompt); } else if (consoleType == "rest") { MainConsole.Instance = new RemoteConsole(prompt); ((RemoteConsole)MainConsole.Instance).ReadConfig(Config); } else if (consoleType == "mock") { MainConsole.Instance = new MockConsole(); } else if (consoleType == "local") { MainConsole.Instance = new LocalConsole(prompt, startupConfig); } m_console = MainConsole.Instance; if (logConfig != null) { FileInfo cfg = new FileInfo(logConfig); XmlConfigurator.Configure(cfg); } else { XmlConfigurator.Configure(); } LogEnvironmentInformation(); RegisterCommonAppenders(startupConfig); if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty) { CreatePIDFile(startupConfig.GetString("PIDFile")); } RegisterCommonCommands(); RegisterCommonComponents(Config); #if (_MONO) Thread signal_thread = new Thread (delegate () { while (true) { // Wait for a signal to be delivered int index = Mono.Unix.UnixSignal.WaitAny (signals, -1); //Mono.Unix.Native.Signum signal = signals [index].Signum; ShutdownSpecific(); m_Running = false; Environment.Exit(0); } }); if(!Util.IsWindows()) { try { // linux mac os specifics signals = new Mono.Unix.UnixSignal[] { new Mono.Unix.UnixSignal(Mono.Unix.Native.Signum.SIGTERM) }; ignal_thread.IsBackground = true; signal_thread.Start(); } catch (Exception e) { m_log.Info("Could not set up UNIX signal handlers. SIGTERM will not"); m_log.InfoFormat("shut down gracefully: {0}", e.Message); m_log.Debug("Exception was: ", e); } } #endif // Allow derived classes to perform initialization that // needs to be done after the console has opened Initialise(); } public bool Running { get { return m_Running; } } public virtual int Run() { Watchdog.Enabled = true; MemoryWatchdog.Enabled = true; while (m_Running) { try { MainConsole.Instance.Prompt(); } catch (Exception e) { m_log.ErrorFormat("Command error: {0}", e); } } MemoryWatchdog.Enabled = false; Watchdog.Enabled = false; WorkManager.Stop(); RemovePIDFile(); return 0; } protected override void ShutdownSpecific() { if(!m_Running) return; m_Running = false; m_log.Info("[CONSOLE] Quitting"); base.ShutdownSpecific(); } protected virtual void ReadConfig() { } protected virtual void Initialise() { } /// <summary> /// Adds the included files as ini configuration files /// </summary> /// <param name="sources">List of URL strings or filename strings</param> private bool AddIncludes(IConfigSource configSource, List<string> sources) { bool sourcesAdded = false; //loop over config sources foreach (IConfig config in configSource.Configs) { // Look for Include-* in the key name string[] keys = config.GetKeys(); foreach (string k in keys) { if (k.StartsWith("Include-")) { // read the config file to be included. string file = config.GetString(k); if (IsUri(file)) { if (!sources.Contains(file)) { sourcesAdded = true; sources.Add(file); } } else { string basepath = Path.GetFullPath(m_configDirectory); // Resolve relative paths with wildcards string chunkWithoutWildcards = file; string chunkWithWildcards = string.Empty; int wildcardIndex = file.IndexOfAny(new char[] { '*', '?' }); if (wildcardIndex != -1) { chunkWithoutWildcards = file.Substring(0, wildcardIndex); chunkWithWildcards = file.Substring(wildcardIndex); } string path = Path.Combine(basepath, chunkWithoutWildcards); path = Path.GetFullPath(path) + chunkWithWildcards; string[] paths = Util.Glob(path); // If the include path contains no wildcards, then warn the user that it wasn't found. if (wildcardIndex == -1 && paths.Length == 0) { Console.WriteLine("[CONFIG]: Could not find include file {0}", path); } else { foreach (string p in paths) { if (!sources.Contains(p)) { sourcesAdded = true; sources.Add(p); } } } } } } } return sourcesAdded; } /// <summary> /// Check if we can convert the string to a URI /// </summary> /// <param name="file">String uri to the remote resource</param> /// <returns>true if we can convert the string to a Uri object</returns> bool IsUri(string file) { Uri configUri; return Uri.TryCreate(file, UriKind.Absolute, out configUri) && configUri.Scheme == Uri.UriSchemeHttp; } IConfigSource ReadConfigSource(string iniFile) { // Find out of the file name is a URI and remote load it if possible. // Load it as a local file otherwise. Uri configUri; IConfigSource s = null; try { if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) && configUri.Scheme == Uri.UriSchemeHttp) { XmlReader r = XmlReader.Create(iniFile); s = new XmlConfigSource(r); } else { s = new IniConfigSource(iniFile); } } catch (Exception e) { System.Console.WriteLine("Error reading from config source. {0}", e.Message); Environment.Exit(1); } return s; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Text.RegularExpressions; using AutoRest.Core.Model; using AutoRest.Core.Utilities; using AutoRest.Extensions; using Newtonsoft.Json; namespace AutoRest.CSharp.Model { public class MethodCs : Method { public MethodCs() { } public bool IsCustomBaseUri => CodeModel.Extensions.ContainsKey(SwaggerExtensions.ParameterizedHostExtension); public SyncMethodsGenerationMode SyncMethods { get; set; } /// <summary> /// Get the predicate to determine of the http operation status code indicates failure /// </summary> public string FailureStatusCodePredicate { get { if (Responses.Any()) { List<string> predicates = new List<string>(); foreach (var responseStatus in Responses.Keys) { predicates.Add(string.Format(CultureInfo.InvariantCulture, "(int)_statusCode != {0}", GetStatusCodeReference(responseStatus))); } return string.Join(" && ", predicates); } return "!_httpResponse.IsSuccessStatusCode"; } } /// <summary> /// Generate the method parameter declaration for async methods and extensions /// </summary> public virtual string GetAsyncMethodParameterDeclaration() { return this.GetAsyncMethodParameterDeclaration(false); } /// <summary> /// Generate the method parameter declaration for sync methods and extensions /// </summary> /// <param name="addCustomHeaderParameters">If true add the customHeader to the parameters</param> /// <returns>Generated string of parameters</returns> public virtual string GetSyncMethodParameterDeclaration(bool addCustomHeaderParameters) { List<string> declarations = new List<string>(); foreach (var parameter in LocalParameters) { string format = (parameter.IsRequired ? "{0} {1}" : "{0} {1} = {2}"); string defaultValue = $"default({parameter.ModelTypeName})"; if (!string.IsNullOrEmpty(parameter.DefaultValue) && parameter.ModelType is PrimaryType) { defaultValue = parameter.DefaultValue; } declarations.Add(string.Format(CultureInfo.InvariantCulture, format, parameter.ModelTypeName, parameter.Name, defaultValue)); } if (addCustomHeaderParameters) { declarations.Add("System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null"); } return string.Join(", ", declarations); } /// <summary> /// Generate the method parameter declaration for async methods and extensions /// </summary> /// <param name="addCustomHeaderParameters">If true add the customHeader to the parameters</param> /// <returns>Generated string of parameters</returns> public virtual string GetAsyncMethodParameterDeclaration(bool addCustomHeaderParameters) { var declarations = this.GetSyncMethodParameterDeclaration(addCustomHeaderParameters); if (!string.IsNullOrEmpty(declarations)) { declarations += ", "; } declarations += "System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)"; return declarations; } /// <summary> /// Arguments for invoking the method from a synchronous extension method /// </summary> public string SyncMethodInvocationArgs => string.Join(", ", LocalParameters.Select(each => each.Name)); /// <summary> /// Get the invocation args for an invocation with an async method /// </summary> public string GetAsyncMethodInvocationArgs(string customHeaderReference, string cancellationTokenReference = "cancellationToken") => string.Join(", ", LocalParameters.Select(each => (string)each.Name).Concat(new[] { customHeaderReference, cancellationTokenReference })); /// <summary> /// Get the parameters that are actually method parameters in the order they appear in the method signature /// exclude global parameters /// </summary> [JsonIgnore] public IEnumerable<ParameterCs> LocalParameters { get { return Parameters.Where(parameter => parameter != null && !parameter.IsClientProperty && !string.IsNullOrWhiteSpace(parameter.Name) && !parameter.IsConstant) .OrderBy(item => !item.IsRequired).Cast<ParameterCs>(); } } /// <summary> /// Get the return type name for the underlying interface method /// </summary> public virtual string OperationResponseReturnTypeString { get { if (ReturnType.Body != null && ReturnType.Headers != null) { return $"Microsoft.Rest.HttpOperationResponse<{ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head && IsXNullableReturnType)},{ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head)}>"; } if (ReturnType.Body != null) { return $"Microsoft.Rest.HttpOperationResponse<{ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head && IsXNullableReturnType)}>"; } if (ReturnType.Headers != null) { return $"Microsoft.Rest.HttpOperationHeaderResponse<{ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head)}>"; } return "Microsoft.Rest.HttpOperationResponse"; } } /// <summary> /// Get the return type for the async extension method /// </summary> public virtual string TaskExtensionReturnTypeString { get { if (ReturnType.Body != null) { return string.Format(CultureInfo.InvariantCulture, "System.Threading.Tasks.Task<{0}>", ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head && IsXNullableReturnType)); } else if (ReturnType.Headers != null) { return string.Format(CultureInfo.InvariantCulture, "System.Threading.Tasks.Task<{0}>", ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head)); } else { return "System.Threading.Tasks.Task"; } } } /// <summary> /// Get the type for operation exception /// </summary> public virtual string OperationExceptionTypeString { get { if (this.DefaultResponse.Body is CompositeType) { CompositeType type = this.DefaultResponse.Body as CompositeType; if (type.Extensions.ContainsKey(SwaggerExtensions.NameOverrideExtension)) { var ext = type.Extensions[SwaggerExtensions.NameOverrideExtension] as Newtonsoft.Json.Linq.JContainer; if (ext != null && ext["name"] != null) { return ext["name"].ToString(); } } return type.Name + "Exception"; } else { return "Microsoft.Rest.HttpOperationException"; } } } /// <summary> /// Get the expression for exception initialization with message. /// </summary> public virtual string InitializeExceptionWithMessage { get { return string.Empty; } } /// <summary> /// Get the expression for exception initialization with message. /// </summary> public virtual string InitializeException { get { return string.Empty; } } /// <summary> /// Gets the expression for response body initialization. /// </summary> public virtual string InitializeResponseBody { get { return string.Empty; } } /// <summary> /// Gets the expression for default header setting. /// </summary> public virtual string SetDefaultHeaders { get { return string.Empty; } } /// <summary> /// Get the type name for the method's return type /// </summary> public virtual string ReturnTypeString { get { if (ReturnType.Body != null) { return ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head && IsXNullableReturnType); } if (ReturnType.Headers != null) { return ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head); } else { return "void"; } } } /// <summary> /// Get the method's request body (or null if there is no request body) /// </summary> [JsonIgnore] public ParameterCs RequestBody => Body as ParameterCs; /// <summary> /// Generate a reference to the ServiceClient /// </summary> [JsonIgnore] public string ClientReference => Group.IsNullOrEmpty() ? "this" : "this.Client"; /// <summary> /// Returns serialization settings reference. /// </summary> /// <param name="serializationType"></param> /// <returns></returns> public string GetSerializationSettingsReference(IModelType serializationType) { if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.Date)) { return "new Microsoft.Rest.Serialization.DateJsonConverter()"; } else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { return "new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()"; } else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.Base64Url)) { return "new Microsoft.Rest.Serialization.Base64UrlJsonConverter()"; } else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.UnixTime)) { return "new Microsoft.Rest.Serialization.UnixTimeJsonConverter()"; } return ClientReference + ".SerializationSettings"; } /// <summary> /// Returns deserialization settings reference. /// </summary> /// <param name="deserializationType"></param> /// <returns></returns> public string GetDeserializationSettingsReference(IModelType deserializationType) { if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Date)) { return "new Microsoft.Rest.Serialization.DateJsonConverter()"; } else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Base64Url)) { return "new Microsoft.Rest.Serialization.Base64UrlJsonConverter()"; } else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.UnixTime)) { return "new Microsoft.Rest.Serialization.UnixTimeJsonConverter()"; } return ClientReference + ".DeserializationSettings"; } public string GetExtensionParameters(string methodParameters) { string operationsParameter = "this I" + MethodGroup.TypeName + " operations"; return string.IsNullOrWhiteSpace(methodParameters) ? operationsParameter : operationsParameter + ", " + methodParameters; } public static string GetStatusCodeReference(HttpStatusCode code) { return ((int)code).ToString(CultureInfo.InvariantCulture); } /// <summary> /// Generate code to build the URL from a url expression and method parameters /// </summary> /// <param name="variableName">The variable to store the url in.</param> /// <returns></returns> public virtual string BuildUrl(string variableName) { var builder = new IndentedStringBuilder(); foreach (var pathParameter in this.LogicalParameters.Where(p => p.Location == ParameterLocation.Path)) { string replaceString = "{0} = {0}.Replace(\"{{{1}}}\", System.Uri.EscapeDataString({2}));"; if (pathParameter.SkipUrlEncoding()) { replaceString = "{0} = {0}.Replace(\"{{{1}}}\", {2});"; } var urlPathName = pathParameter.SerializedName; if (pathParameter.ModelType is SequenceType) { builder.AppendLine(replaceString, variableName, urlPathName, pathParameter.GetFormattedReferenceValue(ClientReference)); } else { builder.AppendLine(replaceString, variableName, urlPathName, pathParameter.ModelType.ToString(ClientReference, pathParameter.Name)); } } if (this.LogicalParameters.Any(p => p.Location == ParameterLocation.Query)) { builder.AppendLine("System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();"); foreach (var queryParameter in this.LogicalParameters.Where(p => p.Location == ParameterLocation.Query)) { var replaceString = "_queryParameters.Add(string.Format(\"{0}={{0}}\", System.Uri.EscapeDataString({1})));"; if ((queryParameter as ParameterCs).IsNullable()) { builder.AppendLine("if ({0} != null)", queryParameter.Name) .AppendLine("{").Indent(); } if (queryParameter.SkipUrlEncoding()) { replaceString = "_queryParameters.Add(string.Format(\"{0}={{0}}\", {1}));"; } if (queryParameter.CollectionFormat == CollectionFormat.Multi) { builder.AppendLine("if ({0}.Count == 0)", queryParameter.Name) .AppendLine("{").Indent() .AppendLine(replaceString, queryParameter.SerializedName, "string.Empty").Outdent() .AppendLine("}") .AppendLine("else") .AppendLine("{").Indent() .AppendLine("foreach (var _item in {0})", queryParameter.Name) .AppendLine("{").Indent() .AppendLine(replaceString, queryParameter.SerializedName, "_item ?? string.Empty").Outdent() .AppendLine("}").Outdent() .AppendLine("}").Outdent(); } else { builder.AppendLine(replaceString, queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue(ClientReference)); } if ((queryParameter as ParameterCs).IsNullable()) { builder.Outdent() .AppendLine("}"); } } builder.AppendLine("if (_queryParameters.Count > 0)") .AppendLine("{").Indent(); if (this.Extensions.ContainsKey("nextLinkMethod") && (bool)this.Extensions["nextLinkMethod"]) { builder.AppendLine("{0} += ({0}.Contains(\"?\") ? \"&\" : \"?\") + string.Join(\"&\", _queryParameters);", variableName); } else { builder.AppendLine("{0} += \"?\" + string.Join(\"&\", _queryParameters);", variableName); } builder.Outdent().AppendLine("}"); } return builder.ToString(); } /// <summary> /// Generates input mapping code block. /// </summary> /// <returns></returns> public virtual string BuildInputMappings() { var builder = new IndentedStringBuilder(); foreach (var transformation in InputParameterTransformation) { var compositeOutputParameter = transformation.OutputParameter.ModelType as CompositeType; if (transformation.OutputParameter.IsRequired && compositeOutputParameter != null) { builder.AppendLine("{0} {1} = new {0}();", transformation.OutputParameter.ModelTypeName, transformation.OutputParameter.Name); } else { builder.AppendLine("{0} {1} = default({0});", transformation.OutputParameter.ModelTypeName, transformation.OutputParameter.Name); } var nullCheck = BuildNullCheckExpression(transformation); if (!string.IsNullOrEmpty(nullCheck)) { builder.AppendLine("if ({0})", nullCheck) .AppendLine("{").Indent(); } if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) && compositeOutputParameter != null && !transformation.OutputParameter.IsRequired) { builder.AppendLine("{0} = new {1}();", transformation.OutputParameter.Name, transformation.OutputParameter.ModelType.Name); } foreach (var mapping in transformation.ParameterMappings) { builder.AppendLine("{0};", mapping.CreateCode(transformation.OutputParameter)); } if (!string.IsNullOrEmpty(nullCheck)) { builder.Outdent() .AppendLine("}"); } } return builder.ToString(); } private static string BuildNullCheckExpression(ParameterTransformation transformation) { if (transformation == null) { throw new ArgumentNullException("transformation"); } return string.Join(" || ", transformation.ParameterMappings .Where(m => m.InputParameter.IsNullable()) .Select(m => m.InputParameter.Name + " != null")); } } }
// // LayerManager.cs // // Author: // Jonathan Pobst <monkey@jpobst.com> // // Copyright (c) 2010 Jonathan Pobst // // 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.ComponentModel; using System.Collections.Specialized; using System.Linq; using Cairo; using Mono.Unix; namespace Pinta.Core { public class LayerManager { #region Public Properties public UserLayer this[int index] { get { return PintaCore.Workspace.ActiveDocument.UserLayers[index]; } } public UserLayer CurrentLayer { get { return PintaCore.Workspace.ActiveDocument.CurrentUserLayer; } } public int Count { get { return PintaCore.Workspace.ActiveDocument.UserLayers.Count; } } public Layer ToolLayer { get { return PintaCore.Workspace.ActiveDocument.ToolLayer; } } public Layer SelectionLayer { get { return PintaCore.Workspace.ActiveDocument.SelectionLayer; } } public int CurrentLayerIndex { get { return PintaCore.Workspace.ActiveDocument.CurrentUserLayerIndex; } } public bool ShowSelection { get { return PintaCore.Workspace.ActiveDocument.ShowSelection; } set { PintaCore.Workspace.ActiveDocument.ShowSelection = value; } } public bool ShowSelectionLayer { get { return PintaCore.Workspace.ActiveDocument.ShowSelectionLayer; } set { PintaCore.Workspace.ActiveDocument.ShowSelectionLayer = value; } } #endregion #region Public Methods public void Clear () { PintaCore.Workspace.ActiveDocument.Clear (); } public List<Layer> GetLayersToPaint () { return PintaCore.Workspace.ActiveDocument.GetLayersToPaint (); } public void SetCurrentLayer (int i) { PintaCore.Workspace.ActiveDocument.SetCurrentUserLayer (i); } public void SetCurrentLayer(UserLayer layer) { PintaCore.Workspace.ActiveDocument.SetCurrentUserLayer (layer); } public void FinishSelection () { PintaCore.Workspace.ActiveDocument.FinishSelection (); } // Adds a new layer above the current one public UserLayer AddNewLayer(string name) { return PintaCore.Workspace.ActiveDocument.AddNewLayer (name); } // Adds a new layer above the current one public void Insert(UserLayer layer, int index) { PintaCore.Workspace.ActiveDocument.Insert (layer, index); } public int IndexOf(UserLayer layer) { return PintaCore.Workspace.ActiveDocument.IndexOf (layer); } // Delete the current layer public void DeleteCurrentLayer () { PintaCore.Workspace.ActiveDocument.DeleteCurrentLayer (); } // Delete the layer public void DeleteLayer (int index, bool dispose) { PintaCore.Workspace.ActiveDocument.DeleteLayer (index, dispose); } // Duplicate current layer public Layer DuplicateCurrentLayer () { return PintaCore.Workspace.ActiveDocument.DuplicateCurrentLayer (); } // Flatten current layer public void MergeCurrentLayerDown () { PintaCore.Workspace.ActiveDocument.MergeCurrentLayerDown (); } // Move current layer up public void MoveCurrentLayerUp () { PintaCore.Workspace.ActiveDocument.MoveCurrentLayerUp (); } // Move current layer down public void MoveCurrentLayerDown () { PintaCore.Workspace.ActiveDocument.MoveCurrentLayerDown (); } // Flip image horizontally public void FlipImageHorizontal () { PintaCore.Workspace.ActiveDocument.FlipImageHorizontal (); } // Flip image vertically public void FlipImageVertical () { PintaCore.Workspace.ActiveDocument.FlipImageVertical (); } // Rotate image 180 degrees (flip H+V) public void RotateImage180 () { PintaCore.Workspace.ActiveDocument.RotateImage180 (); } public void RotateImageCW () { PintaCore.Workspace.ActiveDocument.RotateImageCW (); } public void RotateImageCCW () { PintaCore.Workspace.ActiveDocument.RotateImageCCW (); } // Flatten image public void FlattenImage () { PintaCore.Workspace.ActiveDocument.FlattenImage (); } public void CreateSelectionLayer () { PintaCore.Workspace.ActiveDocument.CreateSelectionLayer (); } public void DestroySelectionLayer () { PintaCore.Workspace.ActiveDocument.DestroySelectionLayer (); } public void ResetSelectionPath () { PintaCore.Workspace.ActiveDocument.ResetSelectionPaths (); } public ImageSurface GetClippedLayer (int index) { return PintaCore.Workspace.ActiveDocument.GetClippedLayer (index); } #endregion #region Protected Methods protected internal void OnLayerAdded () { if (LayerAdded != null) LayerAdded.Invoke (this, EventArgs.Empty); } protected internal void OnLayerRemoved () { if (LayerRemoved != null) LayerRemoved.Invoke (this, EventArgs.Empty); } protected internal void OnSelectedLayerChanged () { if (SelectedLayerChanged != null) SelectedLayerChanged.Invoke (this, EventArgs.Empty); } #endregion #region Private Methods public Layer CreateLayer () { return PintaCore.Workspace.ActiveDocument.CreateLayer (); } public Layer CreateLayer (string name, int width, int height) { return PintaCore.Workspace.ActiveDocument.CreateLayer (name, width, height); } internal void RaiseLayerPropertyChangedEvent (object sender, PropertyChangedEventArgs e) { if (LayerPropertyChanged != null) LayerPropertyChanged (sender, e); //TODO Get the workspace to subscribe to this event, and invalidate itself. PintaCore.Workspace.Invalidate (); } #endregion #region Events public event EventHandler LayerAdded; public event EventHandler LayerRemoved; public event EventHandler SelectedLayerChanged; public event PropertyChangedEventHandler LayerPropertyChanged; #endregion } }
using System; using System.Threading.Tasks; using EasyNetQ.Consumer; using EasyNetQ.FluentConfiguration; using EasyNetQ.Producer; namespace EasyNetQ { /// <summary> /// Provides a simple Publish/Subscribe and Request/Response API for a message bus. /// </summary> public interface IBus : IDisposable { /// <summary> /// Publishes a message. /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="message">The message to publish</param> void Publish<T>(T message) where T : class; /// <summary> /// Publishes a message. /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="message">The message to publish</param> /// <param name="configure"> /// Fluent configuration e.g. x => x.WithTopic("*.brighton").WithPriority(2) /// </param> void Publish<T>(T message, Action<IPublishConfiguration> configure) where T : class; /// <summary> /// Publishes a message with a topic /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="message">The message to publish</param> /// <param name="topic">The topic string</param> void Publish<T>(T message, string topic) where T : class; /// <summary> /// Publishes a message. /// When used with publisher confirms the task completes when the publish is confirmed. /// Task will throw an exception if the confirm is NACK'd or times out. /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="message">The message to publish</param> /// <returns></returns> Task PublishAsync<T>(T message) where T : class; /// <summary> /// Publishes a message. /// When used with publisher confirms the task completes when the publish is confirmed. /// Task will throw an exception if the confirm is NACK'd or times out. /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="message">The message to publish</param> /// <param name="configure"> /// Fluent configuration e.g. x => x.WithTopic("*.brighton").WithPriority(2) /// </param> /// <returns></returns> Task PublishAsync<T>(T message, Action<IPublishConfiguration> configure) where T : class; /// <summary> /// Publishes a message with a topic. /// When used with publisher confirms the task completes when the publish is confirmed. /// Task will throw an exception if the confirm is NACK'd or times out. /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="message">The message to publish</param> /// <param name="topic">The topic string</param> /// <returns></returns> Task PublishAsync<T>(T message, string topic) where T : class; /// <summary> /// Subscribes to a stream of messages that match a .NET type. /// </summary> /// <typeparam name="T">The type to subscribe to</typeparam> /// <param name="subscriptionId"> /// A unique identifier for the subscription. Two subscriptions with the same subscriptionId /// and type will get messages delivered in turn. This is useful if you want multiple subscribers /// to load balance a subscription in a round-robin fashion. /// </param> /// <param name="onMessage"> /// The action to run when a message arrives. When onMessage completes the message /// recipt is Ack'd. All onMessage delegates are processed on a single thread so you should /// avoid long running blocking IO operations. Consider using SubscribeAsync /// </param> /// <returns> /// An <see cref="ISubscriptionResult"/> /// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription. /// </returns> ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage) where T : class; /// <summary> /// Subscribes to a stream of messages that match a .NET type. /// </summary> /// <typeparam name="T">The type to subscribe to</typeparam> /// <param name="subscriptionId"> /// A unique identifier for the subscription. Two subscriptions with the same subscriptionId /// and type will get messages delivered in turn. This is useful if you want multiple subscribers /// to load balance a subscription in a round-robin fashion. /// </param> /// <param name="onMessage"> /// The action to run when a message arrives. When onMessage completes the message /// recipt is Ack'd. All onMessage delegates are processed on a single thread so you should /// avoid long running blocking IO operations. Consider using SubscribeAsync /// </param> /// <param name="configure"> /// Fluent configuration e.g. x => x.WithTopic("uk.london") /// </param> /// <returns> /// An <see cref="ISubscriptionResult"/> /// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription. /// </returns> ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage, Action<ISubscriptionConfiguration> configure) where T : class; /// <summary> /// Subscribes to a stream of messages that match a .NET type. /// Allows the subscriber to complete asynchronously. /// </summary> /// <typeparam name="T">The type to subscribe to</typeparam> /// <param name="subscriptionId"> /// A unique identifier for the subscription. Two subscriptions with the same subscriptionId /// and type will get messages delivered in turn. This is useful if you want multiple subscribers /// to load balance a subscription in a round-robin fashion. /// </param> /// <param name="onMessage"> /// The action to run when a message arrives. onMessage can immediately return a Task and /// then continue processing asynchronously. When the Task completes the message will be /// Ack'd. /// </param> /// <returns> /// An <see cref="ISubscriptionResult"/> /// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription. /// </returns> ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage) where T : class; /// <summary> /// Subscribes to a stream of messages that match a .NET type. /// </summary> /// <typeparam name="T">The type to subscribe to</typeparam> /// <param name="subscriptionId"> /// A unique identifier for the subscription. Two subscriptions with the same subscriptionId /// and type will get messages delivered in turn. This is useful if you want multiple subscribers /// to load balance a subscription in a round-robin fashion. /// </param> /// <param name="onMessage"> /// The action to run when a message arrives. onMessage can immediately return a Task and /// then continue processing asynchronously. When the Task completes the message will be /// Ack'd. /// </param> /// <param name="configure"> /// Fluent configuration e.g. x => x.WithTopic("uk.london").WithArgument("x-message-ttl", "60") /// </param> /// <returns> /// An <see cref="ISubscriptionResult"/> /// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription. /// </returns> ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage, Action<ISubscriptionConfiguration> configure) where T : class; /// <summary> /// Makes an RPC style request /// </summary> /// <typeparam name="TRequest">The request type.</typeparam> /// <typeparam name="TResponse">The response type.</typeparam> /// <param name="request">The request message.</param> /// <returns>The response</returns> TResponse Request<TRequest, TResponse>(TRequest request) where TRequest : class where TResponse : class; /// <summary> /// Makes an RPC style request. /// </summary> /// <typeparam name="TRequest">The request type.</typeparam> /// <typeparam name="TResponse">The response type.</typeparam> /// <param name="request">The request message.</param> /// <returns>A task that completes when the response returns</returns> Task<TResponse> RequestAsync<TRequest, TResponse>(TRequest request) where TRequest : class where TResponse : class; /// <summary> /// Responds to an RPC request. /// </summary> /// <typeparam name="TRequest">The request type.</typeparam> /// <typeparam name="TResponse">The response type.</typeparam> /// <param name="responder"> /// A function to run when the request is received. It should return the response. /// </param> IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder) where TRequest : class where TResponse : class; /// <summary> /// Responds to an RPC request. /// </summary> /// <typeparam name="TRequest">The request type.</typeparam> /// <typeparam name="TResponse">The response type.</typeparam> /// <param name="responder"> /// A function to run when the request is received. It should return the response. /// </param> /// <param name="configure"> /// A function for responder configuration /// </param> IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder, Action<IResponderConfiguration> configure) where TRequest : class where TResponse : class; /// <summary> /// Responds to an RPC request asynchronously. /// </summary> /// <typeparam name="TRequest">The request type.</typeparam> /// <typeparam name="TResponse">The response type</typeparam> /// <param name="responder"> /// A function to run when the request is received. /// </param> IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder) where TRequest : class where TResponse : class; /// <summary> /// Responds to an RPC request asynchronously. /// </summary> /// <typeparam name="TRequest">The request type.</typeparam> /// <typeparam name="TResponse">The response type</typeparam> /// <param name="responder"> /// A function to run when the request is received. /// </param> /// <param name="configure"> /// A function for responder configuration /// </param> IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder, Action<IResponderConfiguration> configure) where TRequest : class where TResponse : class; /// <summary> /// Send a message directly to a queue /// </summary> /// <typeparam name="T">The type of message to send</typeparam> /// <param name="queue">The queue to send to</param> /// <param name="message">The message</param> void Send<T>(string queue, T message) where T : class; /// <summary> /// Send a message directly to a queue /// </summary> /// <typeparam name="T">The type of message to send</typeparam> /// <param name="queue">The queue to send to</param> /// <param name="message">The message</param> Task SendAsync<T>(string queue, T message) where T : class; /// <summary> /// Receive messages from a queue. /// Multiple calls to Receive for the same queue, but with different message types /// will add multiple message handlers to the same consumer. /// </summary> /// <typeparam name="T">The type of message to receive</typeparam> /// <param name="queue">The queue to receive from</param> /// <param name="onMessage">The message handler</param> IDisposable Receive<T>(string queue, Action<T> onMessage) where T : class; /// <summary> /// Receive messages from a queue. /// Multiple calls to Receive for the same queue, but with different message types /// will add multiple message handlers to the same consumer. /// </summary> /// <typeparam name="T">The type of message to receive</typeparam> /// <param name="queue">The queue to receive from</param> /// <param name="onMessage">The message handler</param> /// <param name="configure">Action to configure consumer with</param> IDisposable Receive<T>(string queue, Action<T> onMessage, Action<IConsumerConfiguration> configure) where T : class; /// <summary> /// Receive messages from a queue. /// Multiple calls to Receive for the same queue, but with different message types /// will add multiple message handlers to the same consumer. /// </summary> /// <typeparam name="T">The type of message to receive</typeparam> /// <param name="queue">The queue to receive from</param> /// <param name="onMessage">The asychronous message handler</param> IDisposable Receive<T>(string queue, Func<T, Task> onMessage) where T : class; /// <summary> /// Receive messages from a queue. /// Multiple calls to Receive for the same queue, but with different message types /// will add multiple message handlers to the same consumer. /// </summary> /// <typeparam name="T">The type of message to receive</typeparam> /// <param name="queue">The queue to receive from</param> /// <param name="onMessage">The asychronous message handler</param> /// <param name="configure">Action to configure consumer with</param> IDisposable Receive<T>(string queue, Func<T, Task> onMessage, Action<IConsumerConfiguration> configure) where T : class; /// <summary> /// Receive a message from the specified queue. Dispatch them to the given handlers /// </summary> /// <param name="queue">The queue to take messages from</param> /// <param name="addHandlers">A function to add handlers</param> /// <returns>Consumer cancellation. Call Dispose to stop consuming</returns> IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers); /// <summary> /// Receive a message from the specified queue. Dispatch them to the given handlers /// </summary> /// <param name="queue">The queue to take messages from</param> /// <param name="addHandlers">A function to add handlers</param> /// <param name="configure">Action to configure consumer with</param> /// <returns>Consumer cancellation. Call Dispose to stop consuming</returns> IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers, Action<IConsumerConfiguration> configure); /// <summary> /// True if the bus is connected, False if it is not. /// </summary> bool IsConnected { get; } /// <summary> /// Return the advanced EasyNetQ advanced API. /// </summary> IAdvancedBus Advanced { get; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcdv = Google.Cloud.DataCatalog.V1; using sys = System; namespace Google.Cloud.DataCatalog.V1 { /// <summary>Resource name for the <c>Taxonomy</c> resource.</summary> public sealed partial class TaxonomyName : gax::IResourceName, sys::IEquatable<TaxonomyName> { /// <summary>The possible contents of <see cref="TaxonomyName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </summary> ProjectLocationTaxonomy = 1, } private static gax::PathTemplate s_projectLocationTaxonomy = new gax::PathTemplate("projects/{project}/locations/{location}/taxonomies/{taxonomy}"); /// <summary>Creates a <see cref="TaxonomyName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TaxonomyName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static TaxonomyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TaxonomyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TaxonomyName"/> with the pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TaxonomyName"/> constructed from the provided ids.</returns> public static TaxonomyName FromProjectLocationTaxonomy(string projectId, string locationId, string taxonomyId) => new TaxonomyName(ResourceNameType.ProjectLocationTaxonomy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), taxonomyId: gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TaxonomyName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TaxonomyName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </returns> public static string Format(string projectId, string locationId, string taxonomyId) => FormatProjectLocationTaxonomy(projectId, locationId, taxonomyId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TaxonomyName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TaxonomyName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c>. /// </returns> public static string FormatProjectLocationTaxonomy(string projectId, string locationId, string taxonomyId) => s_projectLocationTaxonomy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId))); /// <summary>Parses the given resource name string into a new <see cref="TaxonomyName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c></description> /// </item> /// </list> /// </remarks> /// <param name="taxonomyName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TaxonomyName"/> if successful.</returns> public static TaxonomyName Parse(string taxonomyName) => Parse(taxonomyName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TaxonomyName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="taxonomyName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TaxonomyName"/> if successful.</returns> public static TaxonomyName Parse(string taxonomyName, bool allowUnparsed) => TryParse(taxonomyName, allowUnparsed, out TaxonomyName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TaxonomyName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c></description> /// </item> /// </list> /// </remarks> /// <param name="taxonomyName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TaxonomyName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string taxonomyName, out TaxonomyName result) => TryParse(taxonomyName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TaxonomyName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="taxonomyName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TaxonomyName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string taxonomyName, bool allowUnparsed, out TaxonomyName result) { gax::GaxPreconditions.CheckNotNull(taxonomyName, nameof(taxonomyName)); gax::TemplatedResourceName resourceName; if (s_projectLocationTaxonomy.TryParseName(taxonomyName, out resourceName)) { result = FromProjectLocationTaxonomy(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(taxonomyName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TaxonomyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string taxonomyId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; TaxonomyId = taxonomyId; } /// <summary> /// Constructs a new instance of a <see cref="TaxonomyName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> public TaxonomyName(string projectId, string locationId, string taxonomyId) : this(ResourceNameType.ProjectLocationTaxonomy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), taxonomyId: gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Taxonomy</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TaxonomyId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationTaxonomy: return s_projectLocationTaxonomy.Expand(ProjectId, LocationId, TaxonomyId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TaxonomyName); /// <inheritdoc/> public bool Equals(TaxonomyName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TaxonomyName a, TaxonomyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TaxonomyName a, TaxonomyName b) => !(a == b); } /// <summary>Resource name for the <c>PolicyTag</c> resource.</summary> public sealed partial class PolicyTagName : gax::IResourceName, sys::IEquatable<PolicyTagName> { /// <summary>The possible contents of <see cref="PolicyTagName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </summary> ProjectLocationTaxonomyPolicyTag = 1, } private static gax::PathTemplate s_projectLocationTaxonomyPolicyTag = new gax::PathTemplate("projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}"); /// <summary>Creates a <see cref="PolicyTagName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="PolicyTagName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static PolicyTagName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new PolicyTagName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="PolicyTagName"/> with the pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="policyTagId">The <c>PolicyTag</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="PolicyTagName"/> constructed from the provided ids.</returns> public static PolicyTagName FromProjectLocationTaxonomyPolicyTag(string projectId, string locationId, string taxonomyId, string policyTagId) => new PolicyTagName(ResourceNameType.ProjectLocationTaxonomyPolicyTag, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), taxonomyId: gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId)), policyTagId: gax::GaxPreconditions.CheckNotNullOrEmpty(policyTagId, nameof(policyTagId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="PolicyTagName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="policyTagId">The <c>PolicyTag</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PolicyTagName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </returns> public static string Format(string projectId, string locationId, string taxonomyId, string policyTagId) => FormatProjectLocationTaxonomyPolicyTag(projectId, locationId, taxonomyId, policyTagId); /// <summary> /// Formats the IDs into the string representation of this <see cref="PolicyTagName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="policyTagId">The <c>PolicyTag</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PolicyTagName"/> with pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c>. /// </returns> public static string FormatProjectLocationTaxonomyPolicyTag(string projectId, string locationId, string taxonomyId, string policyTagId) => s_projectLocationTaxonomyPolicyTag.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId)), gax::GaxPreconditions.CheckNotNullOrEmpty(policyTagId, nameof(policyTagId))); /// <summary>Parses the given resource name string into a new <see cref="PolicyTagName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="policyTagName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="PolicyTagName"/> if successful.</returns> public static PolicyTagName Parse(string policyTagName) => Parse(policyTagName, false); /// <summary> /// Parses the given resource name string into a new <see cref="PolicyTagName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="policyTagName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="PolicyTagName"/> if successful.</returns> public static PolicyTagName Parse(string policyTagName, bool allowUnparsed) => TryParse(policyTagName, allowUnparsed, out PolicyTagName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="PolicyTagName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="policyTagName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="PolicyTagName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string policyTagName, out PolicyTagName result) => TryParse(policyTagName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="PolicyTagName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="policyTagName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="PolicyTagName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string policyTagName, bool allowUnparsed, out PolicyTagName result) { gax::GaxPreconditions.CheckNotNull(policyTagName, nameof(policyTagName)); gax::TemplatedResourceName resourceName; if (s_projectLocationTaxonomyPolicyTag.TryParseName(policyTagName, out resourceName)) { result = FromProjectLocationTaxonomyPolicyTag(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(policyTagName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private PolicyTagName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string policyTagId = null, string projectId = null, string taxonomyId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; PolicyTagId = policyTagId; ProjectId = projectId; TaxonomyId = taxonomyId; } /// <summary> /// Constructs a new instance of a <see cref="PolicyTagName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="taxonomyId">The <c>Taxonomy</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="policyTagId">The <c>PolicyTag</c> ID. Must not be <c>null</c> or empty.</param> public PolicyTagName(string projectId, string locationId, string taxonomyId, string policyTagId) : this(ResourceNameType.ProjectLocationTaxonomyPolicyTag, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), taxonomyId: gax::GaxPreconditions.CheckNotNullOrEmpty(taxonomyId, nameof(taxonomyId)), policyTagId: gax::GaxPreconditions.CheckNotNullOrEmpty(policyTagId, nameof(policyTagId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>PolicyTag</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string PolicyTagId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Taxonomy</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TaxonomyId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationTaxonomyPolicyTag: return s_projectLocationTaxonomyPolicyTag.Expand(ProjectId, LocationId, TaxonomyId, PolicyTagId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as PolicyTagName); /// <inheritdoc/> public bool Equals(PolicyTagName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(PolicyTagName a, PolicyTagName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(PolicyTagName a, PolicyTagName b) => !(a == b); } public partial class Taxonomy { /// <summary> /// <see cref="gcdv::TaxonomyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::TaxonomyName TaxonomyName { get => string.IsNullOrEmpty(Name) ? null : gcdv::TaxonomyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class PolicyTag { /// <summary> /// <see cref="gcdv::PolicyTagName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::PolicyTagName PolicyTagName { get => string.IsNullOrEmpty(Name) ? null : gcdv::PolicyTagName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateTaxonomyRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteTaxonomyRequest { /// <summary> /// <see cref="gcdv::TaxonomyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::TaxonomyName TaxonomyName { get => string.IsNullOrEmpty(Name) ? null : gcdv::TaxonomyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListTaxonomiesRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetTaxonomyRequest { /// <summary> /// <see cref="gcdv::TaxonomyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::TaxonomyName TaxonomyName { get => string.IsNullOrEmpty(Name) ? null : gcdv::TaxonomyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreatePolicyTagRequest { /// <summary> /// <see cref="TaxonomyName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public TaxonomyName ParentAsTaxonomyName { get => string.IsNullOrEmpty(Parent) ? null : TaxonomyName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeletePolicyTagRequest { /// <summary> /// <see cref="gcdv::PolicyTagName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::PolicyTagName PolicyTagName { get => string.IsNullOrEmpty(Name) ? null : gcdv::PolicyTagName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListPolicyTagsRequest { /// <summary> /// <see cref="TaxonomyName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public TaxonomyName ParentAsTaxonomyName { get => string.IsNullOrEmpty(Parent) ? null : TaxonomyName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetPolicyTagRequest { /// <summary> /// <see cref="gcdv::PolicyTagName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::PolicyTagName PolicyTagName { get => string.IsNullOrEmpty(Name) ? null : gcdv::PolicyTagName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using Gwen.Input; namespace Gwen.Control { public class MultilineTextBox : Label { private readonly ScrollControl m_ScrollControl; private bool m_SelectAll; private Point m_CursorPos; private Point m_CursorEnd; protected Rectangle m_CaretBounds; private float m_LastInputTime; private List<string> m_TextLines = new List<string>(); private Point StartPoint { get { if (CursorPosition.Y == m_CursorEnd.Y) { return CursorPosition.X < CursorEnd.X ? CursorPosition : CursorEnd; } else { return CursorPosition.Y < CursorEnd.Y ? CursorPosition : CursorEnd; } } } private Point EndPoint { get { if (CursorPosition.Y == m_CursorEnd.Y) { return CursorPosition.X > CursorEnd.X ? CursorPosition : CursorEnd; } else { return CursorPosition.Y > CursorEnd.Y ? CursorPosition : CursorEnd; } } } /// <summary> /// Indicates whether the text has active selection. /// </summary> public bool HasSelection { get { return m_CursorPos != m_CursorEnd; } } /// <summary> /// Invoked when the text has changed. /// </summary> public event GwenEventHandler<EventArgs> TextChanged; /// <summary> /// Get a point representing where the cursor physically appears on the screen. /// Y is line number, X is character position on that line. /// </summary> public Point CursorPosition { get { if (m_TextLines == null || m_TextLines.Count() == 0) return new Point(0, 0); int Y = m_CursorPos.Y; Y = Math.Max(Y, 0); Y = Math.Min(Y, m_TextLines.Count() - 1); int X = m_CursorPos.X; //X may be beyond the last character, but we will want to draw it at the end of line. X = Math.Max(X, 0); X = Math.Min(X, m_TextLines[Y].Length); return new Point(X, Y); } set { m_CursorPos.X = value.X; m_CursorPos.Y = value.Y; RefreshCursorBounds(); } } /// <summary> /// Get a point representing where the endpoint of text selection. /// Y is line number, X is character position on that line. /// </summary> public Point CursorEnd { get { if (m_TextLines == null || m_TextLines.Count() == 0) return new Point(0, 0); int Y = m_CursorEnd.Y; Y = Math.Max(Y, 0); Y = Math.Min(Y, m_TextLines.Count() - 1); int X = m_CursorEnd.X; //X may be beyond the last character, but we will want to draw it at the end of line. X = Math.Max(X, 0); X = Math.Min(X, m_TextLines[Y].Length); return new Point(X, Y); } set { m_CursorEnd.X = value.X; m_CursorEnd.Y = value.Y; RefreshCursorBounds(); } } /// <summary> /// Indicates whether the control will accept Tab characters as input. /// </summary> public bool AcceptTabs { get; set; } /// <summary> /// Returns the number of lines that are in the Multiline Text Box. /// </summary> public int TotalLines { get { return m_TextLines.Count; } } /// <summary> /// Gets and sets the text to display to the user. Each line is seperated by /// an Environment.NetLine character. /// </summary> public override string Text { get { string ret = ""; for (int i = 0; i < TotalLines; i++){ ret += m_TextLines[i]; if (i != TotalLines - 1) { ret += Environment.NewLine; } } return ret; } set { //Label (base) calls SetText. //SetText is overloaded to dump value into TextLines. //We're cool. base.Text = value; } } /// <summary> /// Initializes a new instance of the <see cref="TextBox"/> class. /// </summary> /// <param name="parent">Parent control.</param> public MultilineTextBox(Base parent) : base(parent) { AutoSizeToContents = false; SetSize(200, 20); MouseInputEnabled = true; KeyboardInputEnabled = true; Alignment = Pos.Left | Pos.Top; TextPadding = new Padding(4, 2, 4, 2); m_CursorPos = new Point(0, 0); m_CursorEnd = new Point(0, 0); m_SelectAll = false; TextColor = Color.FromArgb(255, 50, 50, 50); // TODO: From Skin IsTabable = false; AcceptTabs = true; m_ScrollControl = new ScrollControl(this); m_ScrollControl.Dock = Pos.Fill; m_ScrollControl.EnableScroll(true, true); m_ScrollControl.AutoHideBars = true; m_ScrollControl.Margin = Margin.One; m_InnerPanel = m_ScrollControl; m_Text.Parent = m_InnerPanel; m_ScrollControl.InnerPanel.BoundsChanged += new GwenEventHandler<EventArgs>(ScrollChanged); m_TextLines.Add(String.Empty); // [halfofastaple] TODO Figure out where these numbers come from. See if we can remove the magic numbers. // This should be as simple as 'm_ScrollControl.AutoSizeToContents = true' or 'm_ScrollControl.NoBounds()' m_ScrollControl.SetInnerSize(1000, 1000); AddAccelerator("Ctrl + C", OnCopy); AddAccelerator("Ctrl + X", OnCut); AddAccelerator("Ctrl + V", OnPaste); AddAccelerator("Ctrl + A", OnSelectAll); } public string GetTextLine(int index) { return m_TextLines[index]; } public void SetTextLine(int index, string value) { m_TextLines[index] = value; } /// <summary> /// Refreshes the cursor location and selected area when the inner panel scrolls /// </summary> /// <param name="control">The inner panel the text is embedded in</param> private void ScrollChanged(Base control, EventArgs args) { RefreshCursorBounds(); } /// <summary> /// Handler for text changed event. /// </summary> protected override void OnTextChanged() { base.OnTextChanged(); if (TextChanged != null) TextChanged.Invoke(this, EventArgs.Empty); } /// <summary> /// Handler for character input event. /// </summary> /// <param name="chr">Character typed.</param> /// <returns> /// True if handled. /// </returns> protected override bool OnChar(char chr) { //base.OnChar(chr); if (chr == '\t' && !AcceptTabs) return false; InsertText(chr.ToString()); return true; } /// <summary> /// Inserts text at current cursor position, erasing selection if any. /// </summary> /// <param name="text">Text to insert.</param> protected void InsertText(string text) { // TODO: Make sure fits (implement maxlength) if (HasSelection) { EraseSelection(); } string str = m_TextLines[m_CursorPos.Y]; str = str.Insert(CursorPosition.X, text); m_TextLines[m_CursorPos.Y] = str; m_CursorPos.X = CursorPosition.X + text.Length; m_CursorEnd = m_CursorPos; Invalidate(); RefreshCursorBounds(); } /// <summary> /// Renders the control using specified skin. /// </summary> /// <param name="skin">Skin to use.</param> protected override void Render(Skin.Base skin) { base.Render(skin); if (ShouldDrawBackground) skin.DrawTextBox(this); if (!HasFocus) return; int VerticalOffset = 2 - m_ScrollControl.VerticalScroll; int VerticalSize = Font.Size + 6; // Draw selection.. if selected.. if (m_CursorPos != m_CursorEnd) { if (StartPoint.Y == EndPoint.Y) { Point pA = GetCharacterPosition(StartPoint); Point pB = GetCharacterPosition(EndPoint); Rectangle SelectionBounds = new Rectangle(); SelectionBounds.X = Math.Min(pA.X, pB.X); SelectionBounds.Y = pA.Y - VerticalOffset; SelectionBounds.Width = Math.Max(pA.X, pB.X) - SelectionBounds.X; SelectionBounds.Height = VerticalSize; skin.Renderer.DrawColor = Color.FromArgb(200, 50, 170, 255); skin.Renderer.DrawFilledRect(SelectionBounds); } else { /* Start */ Point pA = GetCharacterPosition(StartPoint); Point pB = GetCharacterPosition(new Point(m_TextLines[StartPoint.Y].Length, StartPoint.Y)); Rectangle SelectionBounds = new Rectangle(); SelectionBounds.X = Math.Min(pA.X, pB.X); SelectionBounds.Y = pA.Y - VerticalOffset; SelectionBounds.Width = Math.Max(pA.X, pB.X) - SelectionBounds.X; SelectionBounds.Height = VerticalSize; skin.Renderer.DrawColor = Color.FromArgb(200, 50, 170, 255); skin.Renderer.DrawFilledRect(SelectionBounds); /* Middle */ for (int i = 1; i < EndPoint.Y - StartPoint.Y; i++) { pA = GetCharacterPosition(new Point(0, StartPoint.Y + i)); pB = GetCharacterPosition(new Point(m_TextLines[StartPoint.Y + i].Length, StartPoint.Y + i)); SelectionBounds = new Rectangle(); SelectionBounds.X = Math.Min(pA.X, pB.X); SelectionBounds.Y = pA.Y - VerticalOffset; SelectionBounds.Width = Math.Max(pA.X, pB.X) - SelectionBounds.X; SelectionBounds.Height = VerticalSize; skin.Renderer.DrawColor = Color.FromArgb(200, 50, 170, 255); skin.Renderer.DrawFilledRect(SelectionBounds); } /* End */ pA = GetCharacterPosition(new Point(0, EndPoint.Y)); pB = GetCharacterPosition(EndPoint); SelectionBounds = new Rectangle(); SelectionBounds.X = Math.Min(pA.X, pB.X); SelectionBounds.Y = pA.Y - VerticalOffset; SelectionBounds.Width = Math.Max(pA.X, pB.X) - SelectionBounds.X; SelectionBounds.Height = VerticalSize; skin.Renderer.DrawColor = Color.FromArgb(200, 50, 170, 255); skin.Renderer.DrawFilledRect(SelectionBounds); } } // Draw caret float time = Platform.Neutral.GetTimeInSeconds() - m_LastInputTime; if ((time % 1.0f) <= 0.5f) { skin.Renderer.DrawColor = Color.Black; skin.Renderer.DrawFilledRect(m_CaretBounds); } } protected void RefreshCursorBounds() { m_LastInputTime = Platform.Neutral.GetTimeInSeconds(); MakeCaretVisible(); Point pA = GetCharacterPosition(CursorPosition); Point pB = GetCharacterPosition(m_CursorEnd); //m_SelectionBounds.X = Math.Min(pA.X, pB.X); //m_SelectionBounds.Y = TextY - 1; //m_SelectionBounds.Width = Math.Max(pA.X, pB.X) - m_SelectionBounds.X; //m_SelectionBounds.Height = TextHeight + 2; m_CaretBounds.X = pA.X; m_CaretBounds.Y = (pA.Y + 1); m_CaretBounds.Y += m_ScrollControl.VerticalScroll; m_CaretBounds.Width = 1; m_CaretBounds.Height = Font.Size + 2; Redraw(); } /// <summary> /// Handler for Paste event. /// </summary> /// <param name="from">Source control.</param> protected override void OnPaste(Base from, EventArgs args) { base.OnPaste(from, args); InsertText(Platform.Neutral.GetClipboardText()); } /// <summary> /// Handler for Copy event. /// </summary> /// <param name="from">Source control.</param> protected override void OnCopy(Base from, EventArgs args) { if (!HasSelection) return; base.OnCopy(from, args); Platform.Neutral.SetClipboardText(GetSelection()); } /// <summary> /// Handler for Cut event. /// </summary> /// <param name="from">Source control.</param> protected override void OnCut(Base from, EventArgs args) { if (!HasSelection) return; base.OnCut(from, args); Platform.Neutral.SetClipboardText(GetSelection()); EraseSelection(); } /// <summary> /// Handler for Select All event. /// </summary> /// <param name="from">Source control.</param> protected override void OnSelectAll(Base from, EventArgs args) { //base.OnSelectAll(from); m_CursorEnd = new Point(0, 0); m_CursorPos = new Point(m_TextLines.Last().Length, m_TextLines.Count()); RefreshCursorBounds(); } /// <summary> /// Handler invoked on mouse double click (left) event. /// </summary> /// <param name="x">X coordinate.</param> /// <param name="y">Y coordinate.</param> protected override void OnMouseDoubleClickedLeft(int x, int y) { //base.OnMouseDoubleClickedLeft(x, y); OnSelectAll(this, EventArgs.Empty); } /// <summary> /// Handler for Return keyboard event. /// </summary> /// <param name="down">Indicates whether the key was pressed or released.</param> /// <returns> /// True if handled. /// </returns> protected override bool OnKeyReturn(bool down) { if (down) return true; //Split current string, putting the rhs on a new line string CurrentLine = m_TextLines[m_CursorPos.Y]; string lhs = CurrentLine.Substring(0, CursorPosition.X); string rhs = CurrentLine.Substring(CursorPosition.X); m_TextLines[m_CursorPos.Y] = lhs; m_TextLines.Insert(m_CursorPos.Y + 1, rhs); OnKeyDown(true); OnKeyHome(true); if (m_CursorPos.Y == TotalLines - 1) { m_ScrollControl.ScrollToBottom(); } Invalidate(); RefreshCursorBounds(); return true; } /// <summary> /// Handler for Backspace keyboard event. /// </summary> /// <param name="down">Indicates whether the key was pressed or released.</param> /// <returns> /// True if handled. /// </returns> protected override bool OnKeyBackspace(bool down) { if (!down) return true; if (HasSelection) { EraseSelection(); return true; } if (m_CursorPos.X == 0) { if (m_CursorPos.Y == 0) { return true; //Nothing left to delete } else { string lhs = m_TextLines[m_CursorPos.Y - 1]; string rhs = m_TextLines[m_CursorPos.Y]; m_TextLines.RemoveAt(m_CursorPos.Y); OnKeyUp(true); OnKeyEnd(true); m_TextLines[m_CursorPos.Y] = lhs + rhs; } } else { string CurrentLine = m_TextLines[m_CursorPos.Y]; string lhs = CurrentLine.Substring(0, CursorPosition.X - 1); string rhs = CurrentLine.Substring(CursorPosition.X); m_TextLines[m_CursorPos.Y] = lhs + rhs; OnKeyLeft(true); } Invalidate(); RefreshCursorBounds(); return true; } /// <summary> /// Handler for Delete keyboard event. /// </summary> /// <param name="down">Indicates whether the key was pressed or released.</param> /// <returns> /// True if handled. /// </returns> protected override bool OnKeyDelete(bool down) { if (!down) return true; if (HasSelection) { EraseSelection(); return true; } if (m_CursorPos.X == m_TextLines[m_CursorPos.Y].Length) { if (m_CursorPos.Y == m_TextLines.Count - 1) { return true; //Nothing left to delete } else { string lhs = m_TextLines[m_CursorPos.Y]; string rhs = m_TextLines[m_CursorPos.Y + 1]; m_TextLines.RemoveAt(m_CursorPos.Y + 1); OnKeyEnd(true); m_TextLines[m_CursorPos.Y] = lhs + rhs; } } else { string CurrentLine = m_TextLines[m_CursorPos.Y]; string lhs = CurrentLine.Substring(0, CursorPosition.X); string rhs = CurrentLine.Substring(CursorPosition.X + 1); m_TextLines[m_CursorPos.Y] = lhs + rhs; } Invalidate(); RefreshCursorBounds(); return true; } /// <summary> /// Handler for Up Arrow keyboard event. /// </summary> /// <param name="down">Indicates whether the key was pressed or released.</param> /// <returns> /// True if handled. /// </returns> protected override bool OnKeyUp(bool down) { if (!down) return true; if (m_CursorPos.Y > 0) { m_CursorPos.Y -= 1; } if (!Input.InputHandler.IsShiftDown) { m_CursorEnd = m_CursorPos; } Invalidate(); RefreshCursorBounds(); return true; } /// <summary> /// Handler for Down Arrow keyboard event. /// </summary> /// <param name="down">Indicates whether the key was pressed or released.</param> /// <returns> /// True if handled. /// </returns> protected override bool OnKeyDown(bool down) { if (!down) return true; if (m_CursorPos.Y < TotalLines - 1) { m_CursorPos.Y += 1; } if (!Input.InputHandler.IsShiftDown) { m_CursorEnd = m_CursorPos; } Invalidate(); RefreshCursorBounds(); return true; } /// <summary> /// Handler for Left Arrow keyboard event. /// </summary> /// <param name="down">Indicates whether the key was pressed or released.</param> /// <returns> /// True if handled. /// </returns> protected override bool OnKeyLeft(bool down) { if (!down) return true; if (m_CursorPos.X > 0) { m_CursorPos.X = Math.Min(m_CursorPos.X - 1, m_TextLines[m_CursorPos.Y].Length); } else { if (m_CursorPos.Y > 0) { OnKeyUp(down); OnKeyEnd(down); } } if (!Input.InputHandler.IsShiftDown) { m_CursorEnd = m_CursorPos; } Invalidate(); RefreshCursorBounds(); return true; } /// <summary> /// Handler for Right Arrow keyboard event. /// </summary> /// <param name="down">Indicates whether the key was pressed or released.</param> /// <returns> /// True if handled. /// </returns> protected override bool OnKeyRight(bool down) { if (!down) return true; if (m_CursorPos.X < m_TextLines[m_CursorPos.Y].Length) { m_CursorPos.X = Math.Min(m_CursorPos.X + 1, m_TextLines[m_CursorPos.Y].Length); } else { if (m_CursorPos.Y < m_TextLines.Count - 1) { OnKeyDown(down); OnKeyHome(down); } } if (!Input.InputHandler.IsShiftDown) { m_CursorEnd = m_CursorPos; } Invalidate(); RefreshCursorBounds(); return true; } /// <summary> /// Handler for Home Key keyboard event. /// </summary> /// <param name="down">Indicates whether the key was pressed or released.</param> /// <returns> /// True if handled. /// </returns> protected override bool OnKeyHome(bool down) { if (!down) return true; m_CursorPos.X = 0; if (!Input.InputHandler.IsShiftDown) { m_CursorEnd = m_CursorPos; } Invalidate(); RefreshCursorBounds(); return true; } /// <summary> /// Handler for End Key keyboard event. /// </summary> /// <param name="down">Indicates whether the key was pressed or released.</param> /// <returns> /// True if handled. /// </returns> protected override bool OnKeyEnd(bool down) { if (!down) return true; m_CursorPos.X = m_TextLines[m_CursorPos.Y].Length; if (!Input.InputHandler.IsShiftDown) { m_CursorEnd = m_CursorPos; } Invalidate(); RefreshCursorBounds(); return true; } /// <summary> /// Handler for Tab Key keyboard event. /// </summary> /// <param name="down">Indicates whether the key was pressed or released.</param> /// <returns> /// True if handled. /// </returns> protected override bool OnKeyTab(bool down) { if (!AcceptTabs) return base.OnKeyTab(down); if (!down) return false; OnChar('\t'); return true; } /// <summary> /// Returns currently selected text. /// </summary> /// <returns>Current selection.</returns> public string GetSelection() { if (!HasSelection) return String.Empty; string str = String.Empty; if (StartPoint.Y == EndPoint.Y) { int start = StartPoint.X; int end = EndPoint.X; str = m_TextLines[m_CursorPos.Y]; str = str.Substring(start, end - start); } else { str = String.Empty; str += m_TextLines[StartPoint.Y].Substring(StartPoint.X); //Copy start for (int i = 1; i < EndPoint.Y - StartPoint.Y; i++) { str += m_TextLines[StartPoint.Y + i]; //Copy middle } str += m_TextLines[EndPoint.Y].Substring(0, EndPoint.X); //Copy end } return str; } //[halfofastaple] TODO Implement this and use it. The end user can work around not having it, but it is terribly convenient. // See the delete key handler for help. Eventually, the delete key should use this. ///// <summary> ///// Deletes text. ///// </summary> ///// <param name="startPos">Starting cursor position.</param> ///// <param name="length">Length in characters.</param> //public void DeleteText(Point StartPos, int length) { // /* Single Line Delete */ // if (StartPos.X + length <= m_TextLines[StartPos.Y].Length) { // string str = m_TextLines[StartPos.Y]; // str = str.Remove(StartPos.X, length); // m_TextLines[StartPos.Y] = str; // if (CursorPosition.X > StartPos.X) { // m_CursorPos.X = CursorPosition.X - length; // } // m_CursorEnd = m_CursorPos; // /* Multiline Delete */ // } else { // } //} /// <summary> /// Deletes selected text. /// </summary> public void EraseSelection() { if (StartPoint.Y == EndPoint.Y) { int start = StartPoint.X; int end = EndPoint.X; m_TextLines[StartPoint.Y] = m_TextLines[StartPoint.Y].Remove(start, end - start); } else { /* Remove Start */ if (StartPoint.X < m_TextLines[StartPoint.Y].Length) { m_TextLines[StartPoint.Y] = m_TextLines[StartPoint.Y].Remove(StartPoint.X); } /* Remove Middle */ for (int i = 1; i < EndPoint.Y - StartPoint.Y; i++) { m_TextLines.RemoveAt(StartPoint.Y + 1); } /* Remove End */ if (EndPoint.X < m_TextLines[StartPoint.Y + 1].Length) { m_TextLines[StartPoint.Y] += m_TextLines[StartPoint.Y + 1].Substring(EndPoint.X); } m_TextLines.RemoveAt(StartPoint.Y + 1); } // Move the cursor to the start of the selection, // since the end is probably outside of the string now. m_CursorPos = StartPoint; m_CursorEnd = StartPoint; Invalidate(); RefreshCursorBounds(); } /// <summary> /// Handler invoked on mouse click (left) event. /// </summary> /// <param name="x">X coordinate.</param> /// <param name="y">Y coordinate.</param> /// <param name="down">If set to <c>true</c> mouse button is down.</param> protected override void OnMouseClickedLeft(int x, int y, bool down) { base.OnMouseClickedLeft(x, y, down); if (m_SelectAll) { OnSelectAll(this, EventArgs.Empty); //m_SelectAll = false; return; } Point coords = GetClosestCharacter(x, y); if (down) { CursorPosition = coords; if (!Input.InputHandler.IsShiftDown) CursorEnd = coords; InputHandler.MouseFocus = this; } else { if (InputHandler.MouseFocus == this) { CursorPosition = coords; InputHandler.MouseFocus = null; } } Invalidate(); RefreshCursorBounds(); } /// <summary> /// Returns index of the character closest to specified point (in canvas coordinates). /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> protected override Point GetClosestCharacter(int px, int py) { Point p = CanvasPosToLocal(new Point(px, py)); double distance = Double.MaxValue; Point Best = new Point(0, 0); string sub = String.Empty; /* Find the appropriate Y row (always pick whichever y the mouse currently is on) */ for (int y = 0; y < m_TextLines.Count(); y++) { sub += m_TextLines[y] + Environment.NewLine; Point cp = Skin.Renderer.MeasureText(Font, sub); double YDist = Math.Abs(cp.Y - p.Y); if (YDist < distance) { distance = YDist; Best.Y = y; } } /* Find the best X row, closest char */ sub = String.Empty; distance = Double.MaxValue; for (int x = 0; x <= m_TextLines[Best.Y].Count(); x++) { if (x < m_TextLines[Best.Y].Count()) { sub += m_TextLines[Best.Y][x]; } else { sub += " "; } Point cp = Skin.Renderer.MeasureText(Font, sub); double XDiff = Math.Abs(cp.X - p.X); if (XDiff < distance){ distance = XDiff; Best.X = x; } } return Best; } /// <summary> /// Handler invoked on mouse moved event. /// </summary> /// <param name="x">X coordinate.</param> /// <param name="y">Y coordinate.</param> /// <param name="dx">X change.</param> /// <param name="dy">Y change.</param> protected override void OnMouseMoved(int x, int y, int dx, int dy) { base.OnMouseMoved(x, y, dx, dy); if (InputHandler.MouseFocus != this) return; Point c = GetClosestCharacter(x, y); CursorPosition = c; Invalidate(); RefreshCursorBounds(); } protected virtual void MakeCaretVisible() { int caretPos = GetCharacterPosition(CursorPosition).X - TextX; // If the caret is already in a semi-good position, leave it. { int realCaretPos = caretPos + TextX; if (realCaretPos > Width * 0.1f && realCaretPos < Width * 0.9f) return; } // The ideal position is for the caret to be right in the middle int idealx = (int)(-caretPos + Width * 0.5f); // Don't show too much whitespace to the right if (idealx + TextWidth < Width - TextPadding.Right) idealx = -TextWidth + (Width - TextPadding.Right); // Or the left if (idealx > TextPadding.Left) idealx = TextPadding.Left; SetTextPosition(idealx, TextY); } /// <summary> /// Handler invoked when control children's bounds change. /// </summary> /// <param name="oldChildBounds"></param> /// <param name="child"></param> protected override void OnChildBoundsChanged(System.Drawing.Rectangle oldChildBounds, Base child) { if (m_ScrollControl != null) { m_ScrollControl.UpdateScrollBars(); } } /// <summary> /// Sets the label text. /// </summary> /// <param name="str">Text to set.</param> /// <param name="doEvents">Determines whether to invoke "text changed" event.</param> public override void SetText(string str, bool doEvents = true) { string EasySplit = str.Replace("\r\n", "\n").Replace("\r", "\n"); string[] Lines = EasySplit.Split('\n'); m_TextLines = new List<string>(Lines); Invalidate(); RefreshCursorBounds(); } /// <summary> /// Invalidates the control. /// </summary> /// <remarks> /// Causes layout, repaint, invalidates cached texture. /// </remarks> public override void Invalidate() { if (m_Text != null) { m_Text.String = Text; } if (AutoSizeToContents) SizeToContents(); base.Invalidate(); InvalidateParent(); OnTextChanged(); } private Point GetCharacterPosition(Point CursorPosition) { if (m_TextLines.Count == 0) { return new Point(0, 0); } string CurrLine = m_TextLines[CursorPosition.Y].Substring(0, Math.Min(CursorPosition.X, m_TextLines[CursorPosition.Y].Length)); string sub = ""; for (int i = 0; i < CursorPosition.Y; i++) { sub += m_TextLines[i] + "\n"; } Point p = new Point(Skin.Renderer.MeasureText(Font, CurrLine).X, Skin.Renderer.MeasureText(Font, sub).Y); return new Point(p.X + m_Text.X, p.Y + m_Text.Y + TextPadding.Top); } protected override bool OnMouseWheeled(int delta) { return m_ScrollControl.InputMouseWheeled(delta); } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * 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 library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.IO; using System.Globalization; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using MLifter.DAL; using MLifter.DAL.Interfaces; using System.Diagnostics; namespace MLifterTest.DAL { /// <summary> /// Summary Description for IWords /// </summary> [TestClass] public class IWordsTests { public IWordsTests() { } #region Additional test attributes // // You can use the following additional attributes as you write your tests: // // Use ClassInitialize to run code before running the first test in the class // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // Use ClassCleanup to run code after all tests in a class have run [ClassCleanup()] public static void Cleanup() { TestInfrastructure.MyClassCleanup(); } // Use TestInitialize to run code before running each test // [TestInitialize()] // public void MyTestInitialize() { } // // Use TestCleanup to run code after each test has run // [TestCleanup()] // public void MyTestCleanup() { } // #endregion #region TestContext private TestContext testContextInstance; public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #endregion /// <summary> /// Test the culture property. /// </summary> /// <remarks>Documented by Dev03, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void CultureTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary target = TestInfrastructure.GetLMConnection(TestContext, string.Empty)) { CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures); CultureInfo ai = (CultureInfo)cultures.GetValue(TestInfrastructure.Random.Next(1, cultures.Length)); CultureInfo qi = (CultureInfo)cultures.GetValue(TestInfrastructure.Random.Next(1, cultures.Length)); target.UserSettings.AnswerCulture = ai; Assert.AreEqual<CultureInfo>(target.UserSettings.AnswerCulture, ai, "The culture does not match for AnswerCulture."); target.UserSettings.QuestionCulture = qi; Assert.AreEqual<CultureInfo>(target.UserSettings.QuestionCulture, qi, "The culture does not match for QuestionCulture."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Test the words property. /// </summary> /// <remarks>Documented by Dev03, 2008-07-28</remarks> [TestMethod] public void WordsTest() { // // TODO: Add test logic here // } /// <summary> /// Basic tests for CreateWord(). /// </summary> /// <remarks>Documented by Dev03, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void CreateWordTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary target = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { ICard card = target.Cards.AddNew(); IWord word = card.Question.CreateWord("test", WordType.Word, false); Assert.AreEqual<string>(word.Word, "test", "The values for word do not match."); Assert.AreEqual<WordType>(word.Type, WordType.Word, "The values for word do not match."); Assert.AreEqual<Boolean>(word.Default, false, "The values for word do not match."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Tests an empty value for CreateWord(). /// </summary> /// <remarks>Documented by Dev03, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void CreateEmptyWordTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary target = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { ICard card = target.Cards.AddNew(); IWord word = card.Question.CreateWord(String.Empty, WordType.Word, false); Assert.AreEqual<string>(word.Word, String.Empty, "The value for word should be empty."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Tests an empty value for CreateWord(). /// </summary> /// <remarks>Documented by Dev03, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void CreateNullWordTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary target = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { ICard card = target.Cards.AddNew(); IWord word = card.Question.CreateWord(null, WordType.Word, false); Assert.AreEqual<string>(word.Word, String.Empty, "The value for word should be empty."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Basic tests for AddWord(). /// </summary> /// <remarks>Documented by Dev03, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void AddWordTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary target = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { ICard card = target.Cards.AddNew(); IWord word = card.Question.CreateWord("test", WordType.Word, false); card.Question.AddWord(word); Assert.IsTrue(card.Question.Words.Count == 1, "Word count should be 1 but is " + card.Question.Words.Count.ToString()); Assert.AreEqual<string>(card.Question.Words[0].Word, "test", "The values for word do not match."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Tests a null value for AddWord(). /// </summary> /// <remarks>Documented by Dev03, 2008-07-28</remarks> [TestMethod] [ExpectedException(typeof(System.NullReferenceException), "Adding a null value should throw an exception.")] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void AddWordNullTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary target = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { ICard card = target.Cards.AddNew(); card.Question.AddWord(null); } } else throw new System.NullReferenceException(); TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Basic tests for AddWords(WordList). /// </summary> /// <remarks>Documented by Dev03, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void AddWordsWordListTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { IChapter chapter = writeLM.Chapters.AddNew(); chapter.Title = "A chapter"; ICard card = writeLM.Cards.AddNew(); card.Chapter = chapter.Id; List<string> wordList = new List<string>(); for (int i = 0; i < TestInfrastructure.Random.Next(10, 50); i++) wordList.Add("Word " + i.ToString()); card.Question.AddWords(wordList.ToArray()); for (int i = 0; i < writeLM.Cards.Cards[0].Question.Words.Count; i++) Assert.AreEqual<string>("Word " + i.ToString(), writeLM.Cards.Cards[0].Question.Words[i].Word, "IWords.AddWords(WordList) does not add a list of words."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Tests AddWords(WordList) with a null WordList. /// </summary> /// <remarks>Documented by Dev03, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] [ExpectedException(typeof(System.NullReferenceException), "Adding a null value should throw an exception.")] public void AddWordsNullWordListTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { ICard card = writeLM.Cards.AddNew(); card.Question.AddWords((string[])null); } } else throw new System.NullReferenceException(); TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Tests AddWords(WordList) with an empty WordList. /// </summary> /// <remarks>Documented by Dev03, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void AddWordsEmptyWordListTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { IChapter chapter = writeLM.Chapters.AddNew(); chapter.Title = "A chapter"; ICard card = writeLM.Cards.AddNew(); card.Chapter = chapter.Id; List<string> wordList = new List<string>(); card.Question.AddWords(wordList.ToArray()); Assert.AreEqual<int>(0, writeLM.Cards.Cards[0].Question.Words.Count, "IWords.AddWords(empty WordList) does something strange."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Basic tests for AddWords(List&lt;IWord&gt;). /// </summary> /// <remarks>Documented by Dev08, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void AddWordsListTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { IChapter chapter = writeLM.Chapters.AddNew(); chapter.Title = "A chapter"; ICard card = writeLM.Cards.AddNew(); card.Chapter = chapter.Id; List<IWord> wordList = new List<IWord>(); for (int i = 0; i < TestInfrastructure.Random.Next(10, 50); i++) { IWord word = card.Question.CreateWord("Word " + i.ToString(), WordType.Word, true); wordList.Add(word); } card.Question.AddWords(wordList); for (int i = 0; i < wordList.Count; i++) Assert.AreEqual<string>("Word " + i.ToString(), writeLM.Cards.Get(card.Id).Question.Words[i].Word, "IWords.AddWords(List) does not add a list of words."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Tests AddWords(List&lt;IWord&gt;) with a null List. /// </summary> /// <remarks>Documented by Dev08, 2008-07-28</remarks> [TestMethod] [ExpectedException(typeof(System.NullReferenceException), "Adding a null value should throw an exception.")] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void AddWordsNullListTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { ICard card = writeLM.Cards.AddNew(); card.Question.AddWords((List<IWord>)null); Assert.AreEqual<int>(0, writeLM.Cards.Cards[0].Question.Words.Count, "IWords.AddWords((List<IWord>)null) does something strange."); } } else throw new System.NullReferenceException(); TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Tests AddWords(List&lt;IWord&gt;) with an empty List. /// </summary> /// <remarks>Documented by Dev08, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void AddWordsEmptyListTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { IChapter chapter = writeLM.Chapters.AddNew(); chapter.Title = "A chapter"; ICard card = writeLM.Cards.AddNew(); card.Chapter = chapter.Id; List<IWord> wordList = new List<IWord>(); wordList.Clear(); card.Question.AddWords(wordList); Assert.AreEqual<int>(0, writeLM.Cards.Cards[0].Question.Words.Count, "IWords.AddWords(empty list) does something strange."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Tests ClearWords() which should delete all words. /// </summary> /// <remarks>Documented by Dev08, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void ClearWordsTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { ICard card = writeLM.Cards.AddNew(); IWords words = card.Question; for (int i = 0; i < TestInfrastructure.Random.Next(10, 50); i++) { IWord word = words.CreateWord("Word " + i.ToString(), WordType.Word, true); words.AddWord(word); } words.ClearWords(); Assert.IsTrue(words.Words.Count == 0, "IWords.ClearWords does not delete all words."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Tests ToString(). /// </summary> /// <remarks>Documented by Dev08, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void ToStringTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { ICard card = writeLM.Cards.AddNew(); IWords words = card.Question; for (int i = 0; i < TestInfrastructure.Random.Next(10, 50); i++) { IWord word = words.CreateWord("Word " + i.ToString(), WordType.Word, true); words.AddWord(word); } string quotedStringClone = string.Empty; foreach (IWord var in words.Words) quotedStringClone += var.Word + ", "; quotedStringClone = quotedStringClone.Substring(0, quotedStringClone.Length - 2); Assert.AreEqual<string>(quotedStringClone, words.ToString(), "IWords.ToString does not match with expected output."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Tests ToQuotedString(). /// </summary> /// <remarks>Documented by Dev08, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void ToQuotedStringTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { ICard card = writeLM.Cards.AddNew(); IWords words = card.Question; for (int i = 0; i < TestInfrastructure.Random.Next(10, 50); i++) { IWord word = words.CreateWord("Word " + i.ToString(), WordType.Word, true); words.AddWord(word); } string quotedStringClone = string.Empty; foreach (IWord var in words.Words) quotedStringClone += "\"" + var.Word + "\", "; quotedStringClone = quotedStringClone.Substring(0, quotedStringClone.Length - 2); Assert.AreEqual<string>(quotedStringClone, words.ToQuotedString(), "IWords.ToQuotedString does not match with expected output."); } } TestInfrastructure.DebugLineEnd(TestContext); } /// <summary> /// Tests ToNewlineString(). /// </summary> /// <remarks>Documented by Dev08, 2008-07-28</remarks> [TestMethod] [TestProperty("TestCategory", "Developer"), DataSource("TestSources")] public void ToNewlineStringTest() { TestInfrastructure.DebugLineStart(TestContext); if (TestInfrastructure.IsActive(TestContext)) { using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser)) { ICard card = writeLM.Cards.AddNew(); IWords words = card.Question; for (int i = 0; i < TestInfrastructure.Random.Next(10, 50); i++) { IWord word = words.CreateWord("Word " + i.ToString(), WordType.Word, true); words.AddWord(word); } string newLineStringClone = string.Empty; foreach (IWord var in words.Words) newLineStringClone += var.Word + "\r\n"; newLineStringClone = newLineStringClone.Substring(0, newLineStringClone.Length - 2); Assert.AreEqual<string>(newLineStringClone, words.ToNewlineString(), "IWords.ToNewlineStringTest does not match with expected output."); } } TestInfrastructure.DebugLineEnd(TestContext); } } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * 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. */ //****************** XmlOASISCatalog class was branched from TFS development version and logging was removed ******************// //********* We branched from the version in DEV - Changeset 6388 dated 30/01/2012 - File date was 19/02/2012 ******************// using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Net; namespace Trisoft.ISHRemote.HelperClasses { /// <summary> /// This class can resolve Public/System indentifiers to one Uri DTD path and supports nextCatalog statements. /// </summary> public class XmlOASISCatalog { #region Constants /// <summary> /// Fixed user reference when logging /// </summary> private const string UserReference = "ISHCNFG"; /// <summary> /// Fixed separator for the UserReference /// The UserReference is created by a combination of the UserReference and the ProcessId. /// </summary> private const string UserReferenceSeparator = ":"; /// <summary> /// Namespace of the OASIS catalog /// </summary> private const string CatalogNamespace = "urn:oasis:names:tc:entity:xmlns:xml:catalog"; /// <summary> /// Namespace prefix of the OASIS catalog /// </summary> private const string CatalogPrefix = "cat"; /// <summary> /// Attribute with the PublicId /// </summary> private const string PublicIdAttribute = "publicId"; /// <summary> /// Attribute with the SystemId /// </summary> private const string SystemIdAttribute = "systemId"; /// <summary> /// Attribute with the Uri /// </summary> private const string UriAttribute = "uri"; #region XPath Constants /// <summary> /// XPath to find references to other catalogs (= NextCatalog) /// </summary> private const string NextCatalogXPath = "/cat:catalog/cat:nextCatalog"; /// <summary> /// XPath to find public defined DTD's /// </summary> private const string PublicXPath = "/cat:catalog/cat:public"; /// <summary> /// XPath to find DTD's that are defined with a SystemId /// </summary> private const string SystemXPath = "/cat:catalog/cat:system"; /// <summary> /// XPath to find the xml:base attribute starting from a specified XmlNode /// </summary> private const string BaseUriXPath = "ancestor-or-self::*[@xml:base][1]/@xml:base"; #endregion #endregion #region Members /// <summary> /// XMLCatalogFile in the TriDKApp of the current InfoShare project /// </summary> private string _catalogUri; /// <summary> /// Dictionary with the PublicIds. /// The key of the dictionary is the PublicId and the value is the absoluteUri. /// </summary> private Dictionary<string, string> _publicIds; /// <summary> /// Dictionary with the SystemIds. /// The key of the dictionary is the SystemId and the value is the absoluteUri. /// </summary> private Dictionary<string, string> _systemIds; /// <summary> /// XmlNamespaceManager stores the prefixe and namespace of the OASIS catalog /// </summary> private XmlNamespaceManager _nameSpaceManager; /// <summary> /// The XmlUrlResolver is internally used to append the relative uri with the base uri. /// </summary> private XmlUrlResolver _xmlUrlResolver; /// <summary> /// User reference string (inclusive ProcessId) /// </summary> private string _userReference; #endregion #region Constructor /// <summary> /// Initializes an instance of the XmlOASISCatalog with the given CatalogUri /// </summary> /// <param name="catalogUri">Filename (and path) of the XMLCatalogFile</param> public XmlOASISCatalog(string catalogUri) { _userReference = UserReference + UserReferenceSeparator + System.Diagnostics.Process.GetCurrentProcess().Id.ToString(); // Initialize the dictionaries _publicIds = new Dictionary<string, string>(); _systemIds = new Dictionary<string, string>(); // Initialize the XmlNamespaceManager _nameSpaceManager = new XmlNamespaceManager(new NameTable()); _nameSpaceManager.AddNamespace(CatalogPrefix, CatalogNamespace); // Initialize the XmlUrlResolver (for internal usage only) _xmlUrlResolver = new XmlUrlResolver(); _xmlUrlResolver.Credentials = CredentialCache.DefaultCredentials; // Resolve the Catalog and load the dictionaries if (catalogUri != string.Empty) { _catalogUri = catalogUri; // Load the XML Catalog File XmlDocument catalog = new XmlDocument(); try { catalog.Load(_catalogUri); } catch (Exception ex) { throw ex; } if (catalog != null) { // Make one large catalog that includes all references to other catalogs ResolveNextCatalog(catalog); // Make a dictionary with the PublicIds LoadPublicIds(catalog); // Make a dictionary with the SystemIds LoadSystemIds(catalog); } } } #endregion #region Public methods /// <summary> /// Returns the absolute Uri of the given SystemId. /// </summary> /// <param name="systemId">The SystemId</param> public string ResolveSystemId(string systemId) { string id = Normalize(systemId); string absoluteUri; if (!_systemIds.TryGetValue(id, out absoluteUri)) { absoluteUri = id; } return absoluteUri; } /// <summary> /// Returns the absolute Uri of the given PublicId. /// </summary> /// <param name="publicId">The PublicId</param> public string ResolvePublicId(string publicId) { string absoluteUri; if (!_publicIds.TryGetValue(publicId, out absoluteUri)) { absoluteUri = publicId; } return absoluteUri; } /// <summary> /// Returns whether a matching entry for the given systemId was found in the catalog /// </summary> /// <param name="systemId">The SystemId</param> /// <param name="resolvedSystemId">The systemId corresponding to the matching publicId entry in the catalog</param> public bool TryResolveSystemId(string systemId, out string resolvedSystemId) { string id = Normalize(systemId); return _systemIds.TryGetValue(id, out resolvedSystemId); } /// <summary> /// Returns whether a matching entry for the given publicId was found in the catalog /// </summary> /// <param name="publicId">The PublicId</param> /// <param name="resolvedSystemId">The systemId corresponding to the matching publicId entry in the catalog</param> public bool TryResolvePublicId(string publicId, out string resolvedSystemId) { return _publicIds.TryGetValue(publicId, out resolvedSystemId); } #endregion #region Private methods /// <summary> /// Resolve references to other catalogs (= NextCatalog) and include the full catalog. /// This method results in one large catalog with all information. /// </summary> /// <param name="catalog">The main catalog</param> private void ResolveNextCatalog(XmlDocument catalog) { XmlNodeList nextCatalogList = catalog.SelectNodes(NextCatalogXPath, _nameSpaceManager); foreach (XmlElement nextCatalog in nextCatalogList) { XmlNode refNode = nextCatalog; InsertNextCatalog(catalog, GetNextCatalog(nextCatalog), refNode); nextCatalog.ParentNode.RemoveChild(nextCatalog); } } /// <summary> /// Insert all childnodes of the NextCatalog after the reference node. /// </summary> /// <param name="catalog">The current Catalog</param> /// <param name="nextCatalog">The NextCatalog</param> /// <param name="refNode">The reference node</param> private void InsertNextCatalog(XmlDocument catalog, XmlDocument nextCatalog, XmlNode refNode) { foreach (XmlNode childNode in nextCatalog.DocumentElement.ChildNodes) { if (childNode.LocalName == "nextCatalog") { InsertNextCatalog(catalog, GetNextCatalog(childNode), refNode); } else { if (childNode.GetType() == typeof(System.Xml.XmlElement)) { XmlNode uriAttribute = childNode.Attributes.GetNamedItem(UriAttribute); if (uriAttribute != null) { Uri baseUri = GetBaseUri(uriAttribute); string absoluteUri = _xmlUrlResolver.ResolveUri(baseUri, uriAttribute.InnerText).AbsoluteUri; uriAttribute.InnerText = absoluteUri; } XmlNode newNode = catalog.ImportNode(childNode, true); refNode = catalog.DocumentElement.InsertAfter(newNode, refNode); } } } } /// <summary> /// Load the XML document of the referenced catalog /// </summary> /// <param name="nextCatalogNode">NextCatalog node</param> /// <returns>XML document with the NextCatalog</returns> private XmlDocument GetNextCatalog(XmlNode nextCatalogNode) { XmlDocument nextCatalog = new XmlDocument(); XmlNode catalogAttribute = nextCatalogNode.Attributes.GetNamedItem("catalog"); if (catalogAttribute != null) { string absoluteUri = _xmlUrlResolver.ResolveUri(GetBaseUri(catalogAttribute), catalogAttribute.InnerText).AbsoluteUri; try { nextCatalog.Load(absoluteUri); } catch (Exception ex) { throw ex; } } return nextCatalog; } /// <summary> /// Return the xml:base attribute in the catalog. /// First try to find the BaseUri attribute on the start node. /// If there is no BaseUri attribute on the start node, try to find the attribute on the ancestor nodes. /// </summary> /// <param name="node">Startnode</param> /// <returns> /// BaseUri of the catalog. /// When no xml:base attribute is specified, null is returned. /// </returns> private Uri GetBaseUri(XmlNode node) { // Code copied from AuthoringClient\...\Xml\XmlCommon\GetBaseUri. if (node != null) { XmlNode baseNode = node.SelectSingleNode(BaseUriXPath,_nameSpaceManager); if (baseNode != null) { if (baseNode.InnerText != string.Empty) { if (baseNode.BaseURI == node.BaseURI) { if (baseNode.BaseURI != string.Empty) { return new Uri(new Uri(node.BaseURI), baseNode.InnerText); } else { return new Uri(baseNode.InnerText); } } } } if (node.BaseURI != String.Empty) { return new Uri(node.BaseURI); } } return null; } /// <summary> /// Initialize the dictionary with all PublicIds and their AbsoluteUri from the complete catalog /// </summary> /// <param name="catalog">XML document with the catalog</param> private void LoadPublicIds(XmlDocument catalog) { string publicId; string relativeUri; Uri baseUri; string absoluteUri; foreach (XmlNode node in catalog.SelectNodes(PublicXPath, _nameSpaceManager)) { XmlNode publicNode = node.Attributes.GetNamedItem(PublicIdAttribute); if (publicNode != null) { publicId = publicNode.InnerText; if (publicId != string.Empty) { if (!_publicIds.ContainsKey(publicId)) { XmlNode uriNode = node.Attributes.GetNamedItem(UriAttribute); if (uriNode != null) { relativeUri = uriNode.InnerText; baseUri = GetBaseUri(uriNode); absoluteUri = _xmlUrlResolver.ResolveUri(baseUri, relativeUri).AbsoluteUri; if (absoluteUri != string.Empty) { _publicIds.Add(publicId, absoluteUri); } } } } } } } /// <summary> /// Initialize the dictionary with all SystemIds and their AbsoluteUri from the complete catalog /// </summary> /// <param name="catalog">XML document with the catalog</param> private void LoadSystemIds(XmlDocument catalog) { string systemId; string relativeUri; Uri baseUri; string absoluteUri; foreach (XmlNode node in catalog.SelectNodes(SystemXPath, _nameSpaceManager)) { XmlNode systemNode = node.Attributes.GetNamedItem(SystemIdAttribute); if (systemNode != null) { systemId = Normalize(systemNode.InnerText); if (systemId != string.Empty) { if (!_systemIds.ContainsKey(systemId)) { XmlNode uriNode = node.Attributes.GetNamedItem(UriAttribute); if (uriNode != null) { relativeUri = uriNode.InnerText; baseUri = GetBaseUri(uriNode); absoluteUri = _xmlUrlResolver.ResolveUri(baseUri, relativeUri).AbsoluteUri; if (absoluteUri != string.Empty) { _systemIds.Add(systemId, absoluteUri); } } } } } } } /// <summary> /// To normalize the given FilePath by creating a Uri and returning the AbsoluteUri. /// When the normalizatin fails, the FilePath is returned. /// </summary> /// <param name="filePath">A FilePath</param> private string Normalize(string filePath) { try { Uri path = new Uri(filePath); return path.AbsoluteUri; } catch { return filePath; } } #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. /****************************************************************************** * 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 InsertUInt641() { var test = new SimpleUnaryOpTest__InsertUInt641(); try { if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } } catch (PlatformNotSupportedException) { test.Succeeded = true; } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__InsertUInt641 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt64); private const int RetElementCount = VectorSize / sizeof(UInt64); private static UInt64[] _data = new UInt64[Op1ElementCount]; private static Vector128<UInt64> _clsVar; private Vector128<UInt64> _fld; private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable; static SimpleUnaryOpTest__InsertUInt641() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__InsertUInt641() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)0; } _dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.Insert( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), (ulong)2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.Insert( Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), (ulong)2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.Insert( Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)), (ulong)2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<UInt64>), typeof(UInt64), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), (ulong)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<UInt64>), typeof(UInt64), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), (ulong)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<UInt64>), typeof(UInt64), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)), (ulong)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.Insert( _clsVar, (ulong)2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr); var result = Sse41.Insert(firstOp, (ulong)2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, (ulong)2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, (ulong)2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__InsertUInt641(); var result = Sse41.Insert(test._fld, (ulong)2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.Insert(_fld, (ulong)2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { for (var i = 0; i < RetElementCount; i++) { if ((i == 1 ? result[i] != 2 : result[i] != 0)) { Succeeded = false; break; } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<UInt64>(Vector128<UInt64><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// // Copyright 2011-2013, Xamarin 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.Threading.Tasks; using Windows.Devices.Geolocation; using Windows.Foundation; using Geolocator.Plugin.Abstractions; using Timeout = Geolocator.Plugin.Timeout; using System.Threading; namespace Geolocator.Plugin { /// <summary> /// Implementation for Geolocator /// </summary> public class GeolocatorImplementation : IGeolocator { public GeolocatorImplementation() { DesiredAccuracy = 50; } /// <inheritdoc/> public event EventHandler<PositionEventArgs> PositionChanged; /// <inheritdoc/> public event EventHandler<PositionErrorEventArgs> PositionError; /// <inheritdoc/> public bool SupportsHeading { get { return false; } } /// <inheritdoc/> public bool IsGeolocationAvailable { get { PositionStatus status = GetGeolocatorStatus(); while (status == PositionStatus.Initializing) { Task.Delay (10).Wait(); status = GetGeolocatorStatus(); } return status != PositionStatus.NotAvailable; } } /// <inheritdoc/> public bool IsGeolocationEnabled { get { PositionStatus status = GetGeolocatorStatus(); while (status == PositionStatus.Initializing) { Task.Delay (10).Wait(); status = GetGeolocatorStatus(); } return status != PositionStatus.Disabled && status != PositionStatus.NotAvailable; } } /// <inheritdoc/> public double DesiredAccuracy { get { return this.desiredAccuracy; } set { this.desiredAccuracy = value; GetGeolocator().DesiredAccuracy = (value < 100) ? PositionAccuracy.High : PositionAccuracy.Default; } } /// <inheritdoc/> public bool IsListening { get { return this.isListening; } } /// <inheritdoc/> public Task<Position> GetPositionAsync (int timeout = Timeout.Infite, CancellationToken? token = null, bool includeHeading = false) { if (timeout < 0) throw new ArgumentOutOfRangeException ("timeout"); if(!token.HasValue) token = CancellationToken.None; IAsyncOperation<Geoposition> pos = GetGeolocator().GetGeopositionAsync (TimeSpan.FromTicks (0), TimeSpan.FromDays (365)); token.Value.Register (o => ((IAsyncOperation<Geoposition>)o).Cancel(), pos); var timer = new Timeout (timeout, pos.Cancel); var tcs = new TaskCompletionSource<Position>(); pos.Completed = (op, s) => { timer.Cancel(); switch (s) { case AsyncStatus.Canceled: tcs.SetCanceled(); break; case AsyncStatus.Completed: tcs.SetResult (GetPosition (op.GetResults())); break; case AsyncStatus.Error: Exception ex = op.ErrorCode; if (ex is UnauthorizedAccessException) ex = new GeolocationException (GeolocationError.Unauthorized, ex); tcs.SetException (ex); break; } }; return tcs.Task; } /// <inheritdoc/> public void StartListening (int minTime, double minDistance, bool includeHeading = false) { if (minTime < 0) throw new ArgumentOutOfRangeException ("minTime"); if (minTime < minDistance) throw new ArgumentOutOfRangeException ("minDistance"); if (this.isListening) throw new InvalidOperationException(); this.isListening = true; var loc = GetGeolocator(); loc.ReportInterval = (uint)minTime; loc.MovementThreshold = minDistance; loc.PositionChanged += OnLocatorPositionChanged; loc.StatusChanged += OnLocatorStatusChanged; } /// <inheritdoc/> public void StopListening() { if (!this.isListening) return; this.locator.PositionChanged -= OnLocatorPositionChanged; this.isListening = false; } private bool isListening; private double desiredAccuracy; private Windows.Devices.Geolocation.Geolocator locator = new Windows.Devices.Geolocation.Geolocator(); private void OnLocatorStatusChanged (Windows.Devices.Geolocation.Geolocator sender, StatusChangedEventArgs e) { GeolocationError error; switch (e.Status) { case PositionStatus.Disabled: error = GeolocationError.Unauthorized; break; case PositionStatus.NoData: error = GeolocationError.PositionUnavailable; break; default: return; } if (this.isListening) { StopListening(); OnPositionError (new PositionErrorEventArgs (error)); } this.locator = null; } private void OnLocatorPositionChanged (Windows.Devices.Geolocation.Geolocator sender, PositionChangedEventArgs e) { OnPositionChanged (new PositionEventArgs (GetPosition (e.Position))); } private void OnPositionChanged (PositionEventArgs e) { var handler = this.PositionChanged; if (handler != null) handler (this, e); } private void OnPositionError (PositionErrorEventArgs e) { var handler = this.PositionError; if (handler != null) handler (this, e); } private Windows.Devices.Geolocation.Geolocator GetGeolocator() { var loc = this.locator; if (loc == null) { this.locator = new Windows.Devices.Geolocation.Geolocator(); this.locator.StatusChanged += OnLocatorStatusChanged; loc = this.locator; } return loc; } private PositionStatus GetGeolocatorStatus() { var loc = GetGeolocator(); return loc.LocationStatus; } private static Position GetPosition (Geoposition position) { var pos = new Position { Accuracy = position.Coordinate.Accuracy, Latitude = position.Coordinate.Point.Position.Latitude, Longitude = position.Coordinate.Point.Position.Longitude, Timestamp = position.Coordinate.Timestamp, }; if (position.Coordinate.Heading != null) pos.Heading = position.Coordinate.Heading.Value; if (position.Coordinate.Speed != null) pos.Speed = position.Coordinate.Speed.Value; if (position.Coordinate.AltitudeAccuracy.HasValue) pos.AltitudeAccuracy = position.Coordinate.AltitudeAccuracy.Value; pos.Altitude = position.Coordinate.Point.Position.Altitude; return pos; } } }
#if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif using System; using System.Runtime.InteropServices; namespace Godot { /// <summary> /// A unit quaternion used for representing 3D rotations. /// Quaternions need to be normalized to be used for rotation. /// /// It is similar to <see cref="Basis"/>, which implements matrix /// representation of rotations, and can be parametrized using both /// an axis-angle pair or Euler angles. Basis stores rotation, scale, /// and shearing, while Quaternion only stores rotation. /// /// Due to its compactness and the way it is stored in memory, certain /// operations (obtaining axis-angle and performing SLERP, in particular) /// are more efficient and robust against floating-point errors. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Quaternion : IEquatable<Quaternion> { /// <summary> /// X component of the quaternion (imaginary <c>i</c> axis part). /// Quaternion components should usually not be manipulated directly. /// </summary> public real_t x; /// <summary> /// Y component of the quaternion (imaginary <c>j</c> axis part). /// Quaternion components should usually not be manipulated directly. /// </summary> public real_t y; /// <summary> /// Z component of the quaternion (imaginary <c>k</c> axis part). /// Quaternion components should usually not be manipulated directly. /// </summary> public real_t z; /// <summary> /// W component of the quaternion (real part). /// Quaternion components should usually not be manipulated directly. /// </summary> public real_t w; /// <summary> /// Access quaternion components using their index. /// </summary> /// <value> /// <c>[0]</c> is equivalent to <see cref="x"/>, /// <c>[1]</c> is equivalent to <see cref="y"/>, /// <c>[2]</c> is equivalent to <see cref="z"/>, /// <c>[3]</c> is equivalent to <see cref="w"/>. /// </value> public real_t this[int index] { get { switch (index) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; default: throw new IndexOutOfRangeException(); } } set { switch (index) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; case 3: w = value; break; default: throw new IndexOutOfRangeException(); } } } /// <summary> /// Returns the length (magnitude) of the quaternion. /// </summary> /// <seealso cref="LengthSquared"/> /// <value>Equivalent to <c>Mathf.Sqrt(LengthSquared)</c>.</value> public real_t Length { get { return Mathf.Sqrt(LengthSquared); } } /// <summary> /// Returns the squared length (squared magnitude) of the quaternion. /// This method runs faster than <see cref="Length"/>, so prefer it if /// you need to compare quaternions or need the squared length for some formula. /// </summary> /// <value>Equivalent to <c>Dot(this)</c>.</value> public real_t LengthSquared { get { return Dot(this); } } /// <summary> /// Returns the angle between this quaternion and <paramref name="to"/>. /// This is the magnitude of the angle you would need to rotate /// by to get from one to the other. /// /// Note: This method has an abnormally high amount /// of floating-point error, so methods such as /// <see cref="Mathf.IsZeroApprox"/> will not work reliably. /// </summary> /// <param name="to">The other quaternion.</param> /// <returns>The angle between the quaternions.</returns> public real_t AngleTo(Quaternion to) { real_t dot = Dot(to); return Mathf.Acos(Mathf.Clamp(dot * dot * 2 - 1, -1, 1)); } /// <summary> /// Performs a cubic spherical interpolation between quaternions <paramref name="preA"/>, this quaternion, /// <paramref name="b"/>, and <paramref name="postB"/>, by the given amount <paramref name="weight"/>. /// </summary> /// <param name="b">The destination quaternion.</param> /// <param name="preA">A quaternion before this quaternion.</param> /// <param name="postB">A quaternion after <paramref name="b"/>.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The interpolated quaternion.</returns> public Quaternion CubicSlerp(Quaternion b, Quaternion preA, Quaternion postB, real_t weight) { real_t t2 = (1.0f - weight) * weight * 2f; Quaternion sp = Slerp(b, weight); Quaternion sq = preA.Slerpni(postB, weight); return sp.Slerpni(sq, t2); } /// <summary> /// Returns the dot product of two quaternions. /// </summary> /// <param name="b">The other quaternion.</param> /// <returns>The dot product.</returns> public real_t Dot(Quaternion b) { return (x * b.x) + (y * b.y) + (z * b.z) + (w * b.w); } /// <summary> /// Returns Euler angles (in the YXZ convention: when decomposing, /// first Z, then X, and Y last) corresponding to the rotation /// represented by the unit quaternion. Returned vector contains /// the rotation angles in the format (X angle, Y angle, Z angle). /// </summary> /// <returns>The Euler angle representation of this quaternion.</returns> public Vector3 GetEuler() { #if DEBUG if (!IsNormalized()) { throw new InvalidOperationException("Quaternion is not normalized"); } #endif var basis = new Basis(this); return basis.GetEuler(); } /// <summary> /// Returns the inverse of the quaternion. /// </summary> /// <returns>The inverse quaternion.</returns> public Quaternion Inverse() { #if DEBUG if (!IsNormalized()) { throw new InvalidOperationException("Quaternion is not normalized"); } #endif return new Quaternion(-x, -y, -z, w); } /// <summary> /// Returns whether the quaternion is normalized or not. /// </summary> /// <returns>A <see langword="bool"/> for whether the quaternion is normalized or not.</returns> public bool IsNormalized() { return Mathf.Abs(LengthSquared - 1) <= Mathf.Epsilon; } /// <summary> /// Returns a copy of the quaternion, normalized to unit length. /// </summary> /// <returns>The normalized quaternion.</returns> public Quaternion Normalized() { return this / Length; } /// <summary> /// Returns the result of the spherical linear interpolation between /// this quaternion and <paramref name="to"/> by amount <paramref name="weight"/>. /// /// Note: Both quaternions must be normalized. /// </summary> /// <param name="to">The destination quaternion for interpolation. Must be normalized.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The resulting quaternion of the interpolation.</returns> public Quaternion Slerp(Quaternion to, real_t weight) { #if DEBUG if (!IsNormalized()) { throw new InvalidOperationException("Quaternion is not normalized"); } if (!to.IsNormalized()) { throw new ArgumentException("Argument is not normalized", nameof(to)); } #endif // Calculate cosine. real_t cosom = x * to.x + y * to.y + z * to.z + w * to.w; var to1 = new Quaternion(); // Adjust signs if necessary. if (cosom < 0.0) { cosom = -cosom; to1.x = -to.x; to1.y = -to.y; to1.z = -to.z; to1.w = -to.w; } else { to1.x = to.x; to1.y = to.y; to1.z = to.z; to1.w = to.w; } real_t sinom, scale0, scale1; // Calculate coefficients. if (1.0 - cosom > Mathf.Epsilon) { // Standard case (Slerp). real_t omega = Mathf.Acos(cosom); sinom = Mathf.Sin(omega); scale0 = Mathf.Sin((1.0f - weight) * omega) / sinom; scale1 = Mathf.Sin(weight * omega) / sinom; } else { // Quaternions are very close so we can do a linear interpolation. scale0 = 1.0f - weight; scale1 = weight; } // Calculate final values. return new Quaternion ( (scale0 * x) + (scale1 * to1.x), (scale0 * y) + (scale1 * to1.y), (scale0 * z) + (scale1 * to1.z), (scale0 * w) + (scale1 * to1.w) ); } /// <summary> /// Returns the result of the spherical linear interpolation between /// this quaternion and <paramref name="to"/> by amount <paramref name="weight"/>, but without /// checking if the rotation path is not bigger than 90 degrees. /// </summary> /// <param name="to">The destination quaternion for interpolation. Must be normalized.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The resulting quaternion of the interpolation.</returns> public Quaternion Slerpni(Quaternion to, real_t weight) { real_t dot = Dot(to); if (Mathf.Abs(dot) > 0.9999f) { return this; } real_t theta = Mathf.Acos(dot); real_t sinT = 1.0f / Mathf.Sin(theta); real_t newFactor = Mathf.Sin(weight * theta) * sinT; real_t invFactor = Mathf.Sin((1.0f - weight) * theta) * sinT; return new Quaternion ( (invFactor * x) + (newFactor * to.x), (invFactor * y) + (newFactor * to.y), (invFactor * z) + (newFactor * to.z), (invFactor * w) + (newFactor * to.w) ); } /// <summary> /// Returns a vector transformed (multiplied) by this quaternion. /// </summary> /// <param name="v">A vector to transform.</param> /// <returns>The transformed vector.</returns> public Vector3 Xform(Vector3 v) { #if DEBUG if (!IsNormalized()) { throw new InvalidOperationException("Quaternion is not normalized"); } #endif var u = new Vector3(x, y, z); Vector3 uv = u.Cross(v); return v + (((uv * w) + u.Cross(uv)) * 2); } // Constants private static readonly Quaternion _identity = new Quaternion(0, 0, 0, 1); /// <summary> /// The identity quaternion, representing no rotation. /// Equivalent to an identity <see cref="Basis"/> matrix. If a vector is transformed by /// an identity quaternion, it will not change. /// </summary> /// <value>Equivalent to <c>new Quaternion(0, 0, 0, 1)</c>.</value> public static Quaternion Identity { get { return _identity; } } /// <summary> /// Constructs a <see cref="Quaternion"/> defined by the given values. /// </summary> /// <param name="x">X component of the quaternion (imaginary <c>i</c> axis part).</param> /// <param name="y">Y component of the quaternion (imaginary <c>j</c> axis part).</param> /// <param name="z">Z component of the quaternion (imaginary <c>k</c> axis part).</param> /// <param name="w">W component of the quaternion (real part).</param> public Quaternion(real_t x, real_t y, real_t z, real_t w) { this.x = x; this.y = y; this.z = z; this.w = w; } /// <summary> /// Constructs a <see cref="Quaternion"/> from the given <see cref="Quaternion"/>. /// </summary> /// <param name="q">The existing quaternion.</param> public Quaternion(Quaternion q) { this = q; } /// <summary> /// Constructs a <see cref="Quaternion"/> from the given <see cref="Basis"/>. /// </summary> /// <param name="basis">The <see cref="Basis"/> to construct from.</param> public Quaternion(Basis basis) { this = basis.Quaternion(); } /// <summary> /// Constructs a <see cref="Quaternion"/> that will perform a rotation specified by /// Euler angles (in the YXZ convention: when decomposing, first Z, then X, and Y last), /// given in the vector format as (X angle, Y angle, Z angle). /// </summary> /// <param name="eulerYXZ">Euler angles that the quaternion will be rotated by.</param> public Quaternion(Vector3 eulerYXZ) { real_t halfA1 = eulerYXZ.y * 0.5f; real_t halfA2 = eulerYXZ.x * 0.5f; real_t halfA3 = eulerYXZ.z * 0.5f; // R = Y(a1).X(a2).Z(a3) convention for Euler angles. // Conversion to quaternion as listed in https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf (page A-6) // a3 is the angle of the first rotation, following the notation in this reference. real_t cosA1 = Mathf.Cos(halfA1); real_t sinA1 = Mathf.Sin(halfA1); real_t cosA2 = Mathf.Cos(halfA2); real_t sinA2 = Mathf.Sin(halfA2); real_t cosA3 = Mathf.Cos(halfA3); real_t sinA3 = Mathf.Sin(halfA3); x = (sinA1 * cosA2 * sinA3) + (cosA1 * sinA2 * cosA3); y = (sinA1 * cosA2 * cosA3) - (cosA1 * sinA2 * sinA3); z = (cosA1 * cosA2 * sinA3) - (sinA1 * sinA2 * cosA3); w = (sinA1 * sinA2 * sinA3) + (cosA1 * cosA2 * cosA3); } /// <summary> /// Constructs a <see cref="Quaternion"/> that will rotate around the given axis /// by the specified angle. The axis must be a normalized vector. /// </summary> /// <param name="axis">The axis to rotate around. Must be normalized.</param> /// <param name="angle">The angle to rotate, in radians.</param> public Quaternion(Vector3 axis, real_t angle) { #if DEBUG if (!axis.IsNormalized()) { throw new ArgumentException("Argument is not normalized", nameof(axis)); } #endif real_t d = axis.Length(); if (d == 0f) { x = 0f; y = 0f; z = 0f; w = 0f; } else { real_t sinAngle = Mathf.Sin(angle * 0.5f); real_t cosAngle = Mathf.Cos(angle * 0.5f); real_t s = sinAngle / d; x = axis.x * s; y = axis.y * s; z = axis.z * s; w = cosAngle; } } public static Quaternion operator *(Quaternion left, Quaternion right) { return new Quaternion ( (left.w * right.x) + (left.x * right.w) + (left.y * right.z) - (left.z * right.y), (left.w * right.y) + (left.y * right.w) + (left.z * right.x) - (left.x * right.z), (left.w * right.z) + (left.z * right.w) + (left.x * right.y) - (left.y * right.x), (left.w * right.w) - (left.x * right.x) - (left.y * right.y) - (left.z * right.z) ); } public static Quaternion operator +(Quaternion left, Quaternion right) { return new Quaternion(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w); } public static Quaternion operator -(Quaternion left, Quaternion right) { return new Quaternion(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w); } public static Quaternion operator -(Quaternion left) { return new Quaternion(-left.x, -left.y, -left.z, -left.w); } public static Quaternion operator *(Quaternion left, Vector3 right) { return new Quaternion ( (left.w * right.x) + (left.y * right.z) - (left.z * right.y), (left.w * right.y) + (left.z * right.x) - (left.x * right.z), (left.w * right.z) + (left.x * right.y) - (left.y * right.x), -(left.x * right.x) - (left.y * right.y) - (left.z * right.z) ); } public static Quaternion operator *(Vector3 left, Quaternion right) { return new Quaternion ( (right.w * left.x) + (right.y * left.z) - (right.z * left.y), (right.w * left.y) + (right.z * left.x) - (right.x * left.z), (right.w * left.z) + (right.x * left.y) - (right.y * left.x), -(right.x * left.x) - (right.y * left.y) - (right.z * left.z) ); } public static Quaternion operator *(Quaternion left, real_t right) { return new Quaternion(left.x * right, left.y * right, left.z * right, left.w * right); } public static Quaternion operator *(real_t left, Quaternion right) { return new Quaternion(right.x * left, right.y * left, right.z * left, right.w * left); } public static Quaternion operator /(Quaternion left, real_t right) { return left * (1.0f / right); } public static bool operator ==(Quaternion left, Quaternion right) { return left.Equals(right); } public static bool operator !=(Quaternion left, Quaternion right) { return !left.Equals(right); } /// <summary> /// Returns <see langword="true"/> if this quaternion and <paramref name="obj"/> are equal. /// </summary> /// <param name="obj">The other object to compare.</param> /// <returns>Whether or not the quaternion and the other object are equal.</returns> public override bool Equals(object obj) { if (obj is Quaternion) { return Equals((Quaternion)obj); } return false; } /// <summary> /// Returns <see langword="true"/> if this quaternion and <paramref name="other"/> are equal. /// </summary> /// <param name="other">The other quaternion to compare.</param> /// <returns>Whether or not the quaternions are equal.</returns> public bool Equals(Quaternion other) { return x == other.x && y == other.y && z == other.z && w == other.w; } /// <summary> /// Returns <see langword="true"/> if this quaternion and <paramref name="other"/> are approximately equal, /// by running <see cref="Mathf.IsEqualApprox(real_t, real_t)"/> on each component. /// </summary> /// <param name="other">The other quaternion to compare.</param> /// <returns>Whether or not the quaternions are approximately equal.</returns> public bool IsEqualApprox(Quaternion other) { return Mathf.IsEqualApprox(x, other.x) && Mathf.IsEqualApprox(y, other.y) && Mathf.IsEqualApprox(z, other.z) && Mathf.IsEqualApprox(w, other.w); } /// <summary> /// Serves as the hash function for <see cref="Quaternion"/>. /// </summary> /// <returns>A hash code for this quaternion.</returns> public override int GetHashCode() { return y.GetHashCode() ^ x.GetHashCode() ^ z.GetHashCode() ^ w.GetHashCode(); } /// <summary> /// Converts this <see cref="Quaternion"/> to a string. /// </summary> /// <returns>A string representation of this quaternion.</returns> public override string ToString() { return $"({x}, {y}, {z}, {w})"; } /// <summary> /// Converts this <see cref="Quaternion"/> to a string with the given <paramref name="format"/>. /// </summary> /// <returns>A string representation of this quaternion.</returns> public string ToString(string format) { return $"({x.ToString(format)}, {y.ToString(format)}, {z.ToString(format)}, {w.ToString(format)})"; } } }
namespace LuaInterface { using System; using System.IO; using System.Collections; using System.Reflection; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Diagnostics; /* * Passes objects from the CLR to Lua and vice-versa * * Author: Fabio Mascarenhas * Version: 1.0 */ public class ObjectTranslator { internal CheckType typeChecker; // object # to object (FIXME - it should be possible to get object address as an object #) public readonly Dictionary<int, object> objects = new Dictionary<int, object>(); // object to object # public readonly Dictionary<object, int> objectsBackMap = new Dictionary<object, int>(); internal LuaState interpreter; public MetaFunctions metaFunctions; public List<Assembly> assemblies = new List<Assembly>(); private LuaCSFunction registerTableFunction,unregisterTableFunction,getMethodSigFunction, getConstructorSigFunction,importTypeFunction,loadAssemblyFunction, ctypeFunction, enumFromIntFunction; internal EventHandlerContainer pendingEvents = new EventHandlerContainer(); static int indexTranslator = 0; static List<GCHandle> list = new List<GCHandle>(); public static ObjectTranslator FromState(IntPtr luaState) { LuaDLL.lua_getglobal(luaState, "_translator"); int pos = (int)LuaDLL.lua_tonumber(luaState, -1); LuaDLL.lua_pop(luaState, 1); GCHandle handle = list[pos]; ObjectTranslator translator = (ObjectTranslator)handle.Target; return translator; } public static void PushTranslator(IntPtr L, GCHandle handle) { list.Add( handle ); LuaDLL.lua_pushnumber(L, indexTranslator); LuaDLL.lua_setglobal(L, "_translator"); ++indexTranslator; } public ObjectTranslator(LuaState interpreter,IntPtr luaState) { this.interpreter=interpreter; typeChecker=new CheckType(this); metaFunctions=new MetaFunctions(this); assemblies.Add(Assembly.GetExecutingAssembly()); importTypeFunction=new LuaCSFunction(importType); loadAssemblyFunction=new LuaCSFunction(loadAssembly); registerTableFunction=new LuaCSFunction(registerTable); unregisterTableFunction=new LuaCSFunction(unregisterTable); getMethodSigFunction=new LuaCSFunction(getMethodSignature); getConstructorSigFunction=new LuaCSFunction(getConstructorSignature); ctypeFunction = new LuaCSFunction(ctype); enumFromIntFunction = new LuaCSFunction(enumFromInt); createLuaObjectList(luaState); createIndexingMetaFunction(luaState); createBaseClassMetatable(luaState); createClassMetatable(luaState); createFunctionMetatable(luaState); setGlobalFunctions(luaState); } /* * Sets up the list of objects in the Lua side */ private void createLuaObjectList(IntPtr luaState) { LuaDLL.lua_pushstring(luaState,"luaNet_objects"); LuaDLL.lua_newtable(luaState); LuaDLL.lua_newtable(luaState); LuaDLL.lua_pushstring(luaState,"__mode"); LuaDLL.lua_pushstring(luaState,"v"); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_setmetatable(luaState,-2); LuaDLL.lua_settable(luaState, (int) LuaIndexes.LUA_REGISTRYINDEX); } /* * Registers the indexing function of CLR objects * passed to Lua */ private void createIndexingMetaFunction(IntPtr luaState) { LuaDLL.lua_pushstring(luaState,"luaNet_indexfunction"); LuaDLL.luaL_dostring(luaState,MetaFunctions.luaIndexFunction); //LuaDLL.lua_pushstdcallcfunction(luaState,indexFunction); LuaDLL.lua_rawset(luaState, (int) LuaIndexes.LUA_REGISTRYINDEX); } /* * Creates the metatable for superclasses (the base * field of registered tables) */ private void createBaseClassMetatable(IntPtr luaState) { LuaDLL.luaL_newmetatable(luaState,"luaNet_searchbase"); LuaDLL.lua_pushstring(luaState,"__gc"); LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.gcFunction); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_pushstring(luaState,"__tostring"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.toStringFunction); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_pushstring(luaState,"__index"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.baseIndexFunction); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_pushstring(luaState,"__newindex"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.newindexFunction); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_settop(luaState,-2); } /* * Creates the metatable for type references */ private void createClassMetatable(IntPtr luaState) { LuaDLL.luaL_newmetatable(luaState,"luaNet_class"); LuaDLL.lua_pushstring(luaState,"__gc"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.gcFunction); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_pushstring(luaState,"__tostring"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.toStringFunction); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_pushstring(luaState,"__index"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.classIndexFunction); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_pushstring(luaState,"__newindex"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.classNewindexFunction); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_pushstring(luaState,"__call"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.callConstructorFunction); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_settop(luaState,-2); } /* * Registers the global functions used by LuaInterface */ private void setGlobalFunctions(IntPtr luaState) { LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.indexFunction); LuaDLL.lua_setglobal(luaState,"get_object_member"); LuaDLL.lua_pushstdcallcfunction(luaState,importTypeFunction); LuaDLL.lua_setglobal(luaState,"import_type"); LuaDLL.lua_pushstdcallcfunction(luaState,loadAssemblyFunction); LuaDLL.lua_setglobal(luaState,"load_assembly"); LuaDLL.lua_pushstdcallcfunction(luaState,registerTableFunction); LuaDLL.lua_setglobal(luaState,"make_object"); LuaDLL.lua_pushstdcallcfunction(luaState,unregisterTableFunction); LuaDLL.lua_setglobal(luaState,"free_object"); LuaDLL.lua_pushstdcallcfunction(luaState,getMethodSigFunction); LuaDLL.lua_setglobal(luaState,"get_method_bysig"); LuaDLL.lua_pushstdcallcfunction(luaState,getConstructorSigFunction); LuaDLL.lua_setglobal(luaState,"get_constructor_bysig"); LuaDLL.lua_pushstdcallcfunction(luaState,ctypeFunction); LuaDLL.lua_setglobal(luaState,"ctype"); LuaDLL.lua_pushstdcallcfunction(luaState,enumFromIntFunction); LuaDLL.lua_setglobal(luaState,"enum"); } /* * Creates the metatable for delegates */ private void createFunctionMetatable(IntPtr luaState) { LuaDLL.luaL_newmetatable(luaState,"luaNet_function"); LuaDLL.lua_pushstring(luaState,"__gc"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.gcFunction); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_pushstring(luaState,"__call"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.execDelegateFunction); LuaDLL.lua_settable(luaState,-3); LuaDLL.lua_settop(luaState,-2); } /* * Passes errors (argument e) to the Lua interpreter */ internal void throwError(IntPtr luaState, object e) { // We use this to remove anything pushed by luaL_where int oldTop = LuaDLL.lua_gettop(luaState); // Stack frame #1 is our C# wrapper, so not very interesting to the user // Stack frame #2 must be the lua code that called us, so that's what we want to use LuaDLL.luaL_where(luaState, 1); object[] curlev = popValues(luaState, oldTop); // Determine the position in the script where the exception was triggered string errLocation = ""; if (curlev.Length > 0) errLocation = curlev[0].ToString(); string message = e as string; if (message != null) { // Wrap Lua error (just a string) and store the error location e = new LuaScriptException(message, errLocation); } else { Exception ex = e as Exception; if (ex != null) { // Wrap generic .NET exception as an InnerException and store the error location e = new LuaScriptException(ex, errLocation); } } push(luaState, e); LuaDLL.lua_error(luaState); } /* * Implementation of load_assembly. Throws an error * if the assembly is not found. */ [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static int loadAssembly(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); try { string assemblyName=LuaDLL.lua_tostring(luaState,1); Assembly assembly = null; //assembly = Assembly.GetExecutingAssembly(); try { assembly = Assembly.Load(assemblyName); } catch (BadImageFormatException) { // The assemblyName was invalid. It is most likely a path. } if (assembly == null) { assembly = Assembly.Load(AssemblyName.GetAssemblyName(assemblyName)); } if (assembly != null && !translator.assemblies.Contains(assembly)) { translator.assemblies.Add(assembly); } } catch(Exception e) { translator.throwError(luaState,e); } return 0; } internal Type FindType(string className) { foreach(Assembly assembly in assemblies) { Type klass=assembly.GetType(className); if(klass!=null) { return klass; } } return null; } /* * Implementation of import_type. Returns nil if the * type is not found. */ [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static int importType(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); string className=LuaDLL.lua_tostring(luaState,1); Type klass=translator.FindType(className); if(klass!=null) translator.pushType(luaState,klass); else LuaDLL.lua_pushnil(luaState); return 1; } /* * Implementation of make_object. Registers a table (first * argument in the stack) as an object subclassing the * type passed as second argument in the stack. */ [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static int registerTable(IntPtr luaState) { #if __NOGEN__ throwError(luaState,"Tables as Objects not implemnented"); #else ObjectTranslator translator = ObjectTranslator.FromState(luaState); if(LuaDLL.lua_type(luaState,1)==LuaTypes.LUA_TTABLE) { LuaTable luaTable=translator.getTable(luaState,1); string superclassName = LuaDLL.lua_tostring(luaState, 2); if (superclassName != null) { Type klass = translator.FindType(superclassName); if (klass != null) { // Creates and pushes the object in the stack, setting // it as the metatable of the first argument object obj = CodeGeneration.Instance.GetClassInstance(klass, luaTable); translator.pushObject(luaState, obj, "luaNet_metatable"); LuaDLL.lua_newtable(luaState); LuaDLL.lua_pushstring(luaState, "__index"); LuaDLL.lua_pushvalue(luaState, -3); LuaDLL.lua_settable(luaState, -3); LuaDLL.lua_pushstring(luaState, "__newindex"); LuaDLL.lua_pushvalue(luaState, -3); LuaDLL.lua_settable(luaState, -3); LuaDLL.lua_setmetatable(luaState, 1); // Pushes the object again, this time as the base field // of the table and with the luaNet_searchbase metatable LuaDLL.lua_pushstring(luaState, "base"); int index = translator.addObject(obj); translator.pushNewObject(luaState, obj, index, "luaNet_searchbase"); LuaDLL.lua_rawset(luaState, 1); } else translator.throwError(luaState, "register_table: can not find superclass '" + superclassName + "'"); } else translator.throwError(luaState, "register_table: superclass name can not be null"); } else translator.throwError(luaState,"register_table: first arg is not a table"); #endif return 0; } /* * Implementation of free_object. Clears the metatable and the * base field, freeing the created object for garbage-collection */ [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static int unregisterTable(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); try { if(LuaDLL.lua_getmetatable(luaState,1)!=0) { LuaDLL.lua_pushstring(luaState,"__index"); LuaDLL.lua_gettable(luaState,-2); object obj=translator.getRawNetObject(luaState,-1); if(obj==null) translator.throwError(luaState,"unregister_table: arg is not valid table"); FieldInfo luaTableField=obj.GetType().GetField("__luaInterface_luaTable"); if(luaTableField==null) translator.throwError(luaState,"unregister_table: arg is not valid table"); luaTableField.SetValue(obj,null); LuaDLL.lua_pushnil(luaState); LuaDLL.lua_setmetatable(luaState,1); LuaDLL.lua_pushstring(luaState,"base"); LuaDLL.lua_pushnil(luaState); LuaDLL.lua_settable(luaState,1); } else translator.throwError(luaState,"unregister_table: arg is not valid table"); } catch(Exception e) { translator.throwError(luaState,e.Message); } return 0; } /* * Implementation of get_method_bysig. Returns nil * if no matching method is not found. */ [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static int getMethodSignature(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); IReflect klass; object target; int udata=LuaDLL.luanet_checkudata(luaState,1,"luaNet_class"); if(udata!=-1) { klass=(IReflect)translator.objects[udata]; target=null; } else { target=translator.getRawNetObject(luaState,1); if(target==null) { translator.throwError(luaState,"get_method_bysig: first arg is not type or object reference"); LuaDLL.lua_pushnil(luaState); return 1; } klass=target.GetType(); } string methodName=LuaDLL.lua_tostring(luaState,2); Type[] signature=new Type[LuaDLL.lua_gettop(luaState)-2]; for(int i=0;i<signature.Length;i++) signature[i]=translator.FindType(LuaDLL.lua_tostring(luaState,i+3)); try { //CP: Added ignore case MethodInfo method=klass.GetMethod(methodName,BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase, null, signature, null); translator.pushFunction(luaState,new LuaCSFunction((new LuaMethodWrapper(translator,target,klass,method)).call)); } catch(Exception e) { translator.throwError(luaState,e); LuaDLL.lua_pushnil(luaState); } return 1; } /* * Implementation of get_constructor_bysig. Returns nil * if no matching constructor is found. */ [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static int getConstructorSignature(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); IReflect klass=null; int udata=LuaDLL.luanet_checkudata(luaState,1,"luaNet_class"); if(udata!=-1) { klass=(IReflect)translator.objects[udata]; } if(klass==null) { translator.throwError(luaState,"get_constructor_bysig: first arg is invalid type reference"); } Type[] signature=new Type[LuaDLL.lua_gettop(luaState)-1]; for(int i=0;i<signature.Length;i++) signature[i]=translator.FindType(LuaDLL.lua_tostring(luaState,i+2)); try { ConstructorInfo constructor=klass.UnderlyingSystemType.GetConstructor(signature); translator.pushFunction(luaState,new LuaCSFunction((new LuaMethodWrapper(translator,null,klass,constructor)).call)); } catch(Exception e) { translator.throwError(luaState,e); LuaDLL.lua_pushnil(luaState); } return 1; } private Type typeOf(IntPtr luaState, int idx) { int udata=LuaDLL.luanet_checkudata(luaState,1,"luaNet_class"); if (udata == -1) { return null; } else { ProxyType pt = (ProxyType)objects[udata]; return pt.UnderlyingSystemType; } } public int pushError(IntPtr luaState, string msg) { LuaDLL.lua_pushnil(luaState); LuaDLL.lua_pushstring(luaState,msg); return 2; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static int ctype(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); Type t = translator.typeOf(luaState,1); if (t == null) { return translator.pushError(luaState,"not a CLR class"); } translator.pushObject(luaState,t,"luaNet_metatable"); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static int enumFromInt(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); Type t = translator.typeOf(luaState,1); if (t == null || ! t.IsEnum) { return translator.pushError(luaState,"not an enum"); } object res = null; LuaTypes lt = LuaDLL.lua_type(luaState,2); if (lt == LuaTypes.LUA_TNUMBER) { int ival = (int)LuaDLL.lua_tonumber(luaState,2); res = Enum.ToObject(t,ival); } else if (lt == LuaTypes.LUA_TSTRING) { string sflags = LuaDLL.lua_tostring(luaState,2); string err = null; try { res = Enum.Parse(t,sflags); } catch (ArgumentException e) { err = e.Message; } if (err != null) { return translator.pushError(luaState,err); } } else { return translator.pushError(luaState,"second argument must be a integer or a string"); } translator.pushObject(luaState,res,"luaNet_metatable"); return 1; } /* * Pushes a type reference into the stack */ internal void pushType(IntPtr luaState, Type t) { pushObject(luaState,new ProxyType(t),"luaNet_class"); } /* * Pushes a delegate into the stack */ internal void pushFunction(IntPtr luaState, LuaCSFunction func) { pushObject(luaState,func,"luaNet_function"); } /* * Pushes a CLR object into the Lua stack as an userdata * with the provided metatable */ internal void pushObject(IntPtr luaState, object o, string metatable) { int index = -1; // Pushes nil if(o==null) { LuaDLL.lua_pushnil(luaState); return; } // Object already in the list of Lua objects? Push the stored reference. bool found = (!o.GetType().IsValueType) && objectsBackMap.TryGetValue(o, out index); if(found) { LuaDLL.luaL_getmetatable(luaState,"luaNet_objects"); LuaDLL.lua_rawgeti(luaState,-1,index); // Note: starting with lua5.1 the garbage collector may remove weak reference items (such as our luaNet_objects values) when the initial GC sweep // occurs, but the actual call of the __gc finalizer for that object may not happen until a little while later. During that window we might call // this routine and find the element missing from luaNet_objects, but collectObject() has not yet been called. In that case, we go ahead and call collect // object here // did we find a non nil object in our table? if not, we need to call collect object LuaTypes type = LuaDLL.lua_type(luaState, -1); if (type != LuaTypes.LUA_TNIL) { LuaDLL.lua_remove(luaState, -2); // drop the metatable - we're going to leave our object on the stack return; } // MetaFunctions.dumpStack(this, luaState); LuaDLL.lua_remove(luaState, -1); // remove the nil object value LuaDLL.lua_remove(luaState, -1); // remove the metatable collectObject(o, index); // Remove from both our tables and fall out to get a new ID } index = addObject(o); pushNewObject(luaState,o,index,metatable); } /* * Pushes a new object into the Lua stack with the provided * metatable */ private void pushNewObject(IntPtr luaState,object o,int index,string metatable) { if(metatable=="luaNet_metatable") { // Gets or creates the metatable for the object's type LuaDLL.luaL_getmetatable(luaState,o.GetType().AssemblyQualifiedName); if(LuaDLL.lua_isnil(luaState,-1)) { LuaDLL.lua_settop(luaState,-2); LuaDLL.luaL_newmetatable(luaState,o.GetType().AssemblyQualifiedName); LuaDLL.lua_pushstring(luaState,"cache"); LuaDLL.lua_newtable(luaState); LuaDLL.lua_rawset(luaState,-3); LuaDLL.lua_pushlightuserdata(luaState,LuaDLL.luanet_gettag()); LuaDLL.lua_pushnumber(luaState,1); LuaDLL.lua_rawset(luaState,-3); LuaDLL.lua_pushstring(luaState,"__index"); LuaDLL.lua_pushstring(luaState,"luaNet_indexfunction"); LuaDLL.lua_rawget(luaState, (int) LuaIndexes.LUA_REGISTRYINDEX); LuaDLL.lua_rawset(luaState,-3); LuaDLL.lua_pushstring(luaState,"__gc"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.gcFunction); LuaDLL.lua_rawset(luaState,-3); LuaDLL.lua_pushstring(luaState,"__tostring"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.toStringFunction); LuaDLL.lua_rawset(luaState,-3); LuaDLL.lua_pushstring(luaState,"__newindex"); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.newindexFunction); LuaDLL.lua_rawset(luaState,-3); } } else { LuaDLL.luaL_getmetatable(luaState,metatable); } // Stores the object index in the Lua list and pushes the // index into the Lua stack LuaDLL.luaL_getmetatable(luaState,"luaNet_objects"); LuaDLL.luanet_newudata(luaState,index); LuaDLL.lua_pushvalue(luaState,-3); LuaDLL.lua_remove(luaState,-4); LuaDLL.lua_setmetatable(luaState,-2); LuaDLL.lua_pushvalue(luaState,-1); LuaDLL.lua_rawseti(luaState,-3,index); LuaDLL.lua_remove(luaState,-2); } /* * Gets an object from the Lua stack with the desired type, if it matches, otherwise * returns null. */ internal object getAsType(IntPtr luaState,int stackPos,Type paramType) { ExtractValue extractor=typeChecker.checkType(luaState,stackPos,paramType); if(extractor!=null) return extractor(luaState,stackPos); return null; } /// <summary> /// Given the Lua int ID for an object remove it from our maps /// </summary> /// <param name="udata"></param> internal void collectObject(int udata) { object o; bool found = objects.TryGetValue(udata, out o); // The other variant of collectObject might have gotten here first, in that case we will silently ignore the missing entry if (found) { // Debug.WriteLine("Removing " + o.ToString() + " @ " + udata); collectObject(o, udata); } } /// <summary> /// Given an object reference, remove it from our maps /// </summary> /// <param name="udata"></param> void collectObject(object o, int udata) { // Debug.WriteLine("Removing " + o.ToString() + " @ " + udata); objects.Remove(udata); if (!o.GetType().IsValueType) { objectsBackMap.Remove(o); } } /// <summary> /// We want to ensure that objects always have a unique ID /// </summary> int nextObj = 0; int addObject(object obj) { // New object: inserts it in the list int index = nextObj++; // Debug.WriteLine("Adding " + obj.ToString() + " @ " + index); objects[index] = obj; if(!obj.GetType().IsValueType) { objectsBackMap[obj] = index; } return index; } /* * Gets an object from the Lua stack according to its Lua type. */ internal object getObject(IntPtr luaState,int index) { LuaTypes type=LuaDLL.lua_type(luaState,index); switch(type) { case LuaTypes.LUA_TNUMBER: { return LuaDLL.lua_tonumber(luaState,index); } case LuaTypes.LUA_TSTRING: { return LuaDLL.lua_tostring(luaState,index); } case LuaTypes.LUA_TBOOLEAN: { return LuaDLL.lua_toboolean(luaState,index); } case LuaTypes.LUA_TTABLE: { return getTable(luaState,index); } case LuaTypes.LUA_TFUNCTION: { return getFunction(luaState,index); } case LuaTypes.LUA_TUSERDATA: { int udata=LuaDLL.luanet_tonetobject(luaState,index); if(udata!=-1) return objects[udata]; else return getUserData(luaState,index); } default: return null; } } /* * Gets the table in the index positon of the Lua stack. */ internal LuaTable getTable(IntPtr luaState,int index) { LuaDLL.lua_pushvalue(luaState,index); return new LuaTable(LuaDLL.luaL_ref(luaState,LuaIndexes.LUA_REGISTRYINDEX),interpreter); } /* * Gets the userdata in the index positon of the Lua stack. */ internal LuaUserData getUserData(IntPtr luaState,int index) { LuaDLL.lua_pushvalue(luaState,index); return new LuaUserData(LuaDLL.luaL_ref(luaState,LuaIndexes.LUA_REGISTRYINDEX),interpreter); } /* * Gets the function in the index positon of the Lua stack. */ internal LuaFunction getFunction(IntPtr luaState,int index) { LuaDLL.lua_pushvalue(luaState,index); return new LuaFunction(LuaDLL.luaL_ref(luaState,LuaIndexes.LUA_REGISTRYINDEX),interpreter); } /* * Gets the CLR object in the index positon of the Lua stack. Returns * delegates as Lua functions. */ internal object getNetObject(IntPtr luaState,int index) { int idx=LuaDLL.luanet_tonetobject(luaState,index); if(idx!=-1) return objects[idx]; else return null; } /* * Gets the CLR object in the index positon of the Lua stack. Returns * delegates as is. */ internal object getRawNetObject(IntPtr luaState,int index) { int udata=LuaDLL.luanet_rawnetobj(luaState,index); if(udata!=-1) { return objects[udata]; } return null; } /* * Pushes the entire array into the Lua stack and returns the number * of elements pushed. */ internal int returnValues(IntPtr luaState, object[] returnValues) { if(LuaDLL.lua_checkstack(luaState,returnValues.Length+5)) { for(int i=0;i<returnValues.Length;i++) { push(luaState,returnValues[i]); } return returnValues.Length; } else return 0; } /* * Gets the values from the provided index to * the top of the stack and returns them in an array. */ internal object[] popValues(IntPtr luaState,int oldTop) { int newTop=LuaDLL.lua_gettop(luaState); if(oldTop==newTop) { return null; } else { ArrayList returnValues=new ArrayList(); for(int i=oldTop+1;i<=newTop;i++) { returnValues.Add(getObject(luaState,i)); } LuaDLL.lua_settop(luaState,oldTop); return returnValues.ToArray(); } } /* * Gets the values from the provided index to * the top of the stack and returns them in an array, casting * them to the provided types. */ internal object[] popValues(IntPtr luaState,int oldTop,Type[] popTypes) { int newTop=LuaDLL.lua_gettop(luaState); if(oldTop==newTop) { return null; } else { int iTypes; ArrayList returnValues=new ArrayList(); if(popTypes[0] == typeof(void)) iTypes=1; else iTypes=0; for(int i=oldTop+1;i<=newTop;i++) { returnValues.Add(getAsType(luaState,i,popTypes[iTypes])); iTypes++; } LuaDLL.lua_settop(luaState,oldTop); return returnValues.ToArray(); } } // kevinh - the following line doesn't work for remoting proxies - they always return a match for 'is' // else if(o is ILuaGeneratedType) static bool IsILua(object o) { #if ! __NOGEN__ if(o is ILuaGeneratedType) { // Make sure we are _really_ ILuaGenerated Type typ = o.GetType(); return (typ.GetInterface("ILuaGeneratedType") != null); } else #endif return false; } /* * Pushes the object into the Lua stack according to its type. */ internal void push(IntPtr luaState, object o) { if((object)o==(object)null) { LuaDLL.lua_pushnil(luaState); } else if (o is UnityEngine.GameObject && (UnityEngine.GameObject)o==null) { LuaDLL.lua_pushnil(luaState); } else if(o is sbyte || o is byte || o is short || o is ushort || o is int || o is uint || o is long || o is float || o is ulong || o is decimal || o is double) { double d=Convert.ToDouble(o); LuaDLL.lua_pushnumber(luaState,d); } else if(o is char) { double d = (char)o; LuaDLL.lua_pushnumber(luaState,d); } else if(o is string) { string str=(string)o; LuaDLL.lua_pushstring(luaState,str); } else if(o is bool) { bool b=(bool)o; LuaDLL.lua_pushboolean(luaState,b); } else if(IsILua(o)) { #if ! __NOGEN__ (((ILuaGeneratedType)o).__luaInterface_getLuaTable()).push(luaState); #endif } else if(o is LuaTable) { ((LuaTable)o).push(luaState); } else if(o is LuaCSFunction) { pushFunction(luaState,(LuaCSFunction)o); } else if(o is LuaFunction) { ((LuaFunction)o).push(luaState); } else { pushObject(luaState,o,"luaNet_metatable"); } } /* * Checks if the method matches the arguments in the Lua stack, getting * the arguments if it does. */ internal bool matchParameters(IntPtr luaState,MethodBase method,ref MethodCache methodCache) { return metaFunctions.matchParameters(luaState,method,ref methodCache); } internal Array tableToArray(object luaParamValue, Type paramArrayType) { return metaFunctions.TableToArray(luaParamValue,paramArrayType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using Task = System.Threading.Tasks.Task; namespace Microsoft.DotNet.Build.CloudTestTasks { public class UploadClient { private TaskLoggingHelper log; public UploadClient(TaskLoggingHelper loggingHelper) { log = loggingHelper; } public string EncodeBlockIds(int numberOfBlocks, int lengthOfId) { string numberOfBlocksString = numberOfBlocks.ToString("D" + lengthOfId); if (Encoding.UTF8.GetByteCount(numberOfBlocksString) <= 64) { byte[] bytes = Encoding.UTF8.GetBytes(numberOfBlocksString); return Convert.ToBase64String(bytes); } else { throw new Exception("Task failed - Could not encode block id."); } } public async Task UploadBlockBlobAsync( CancellationToken ct, string AccountName, string AccountKey, string ContainerName, string filePath, string destinationBlob, string contentType, int uploadTimeout, string leaseId = "") { string resourceUrl = AzureHelper.GetContainerRestUrl(AccountName, ContainerName); string fileName = destinationBlob; fileName = fileName.Replace("\\", "/"); string blobUploadUrl = resourceUrl + "/" + fileName; int size = (int)new FileInfo(filePath).Length; int blockSize = 4 * 1024 * 1024; //4MB max size of a block blob int bytesLeft = size; List<string> blockIds = new List<string>(); int numberOfBlocks = (size / blockSize) + 1; int countForId = 0; using (FileStream fileStreamTofilePath = new FileStream(filePath, FileMode.Open)) { int offset = 0; while (bytesLeft > 0) { int nextBytesToRead = (bytesLeft < blockSize) ? bytesLeft : blockSize; byte[] fileBytes = new byte[blockSize]; int read = fileStreamTofilePath.Read(fileBytes, 0, nextBytesToRead); if (nextBytesToRead != read) { throw new Exception(string.Format( "Number of bytes read ({0}) from file {1} isn't equal to the number of bytes expected ({2}) .", read, fileName, nextBytesToRead)); } string blockId = EncodeBlockIds(countForId, numberOfBlocks.ToString().Length); blockIds.Add(blockId); string blockUploadUrl = blobUploadUrl + "?comp=block&blockid=" + WebUtility.UrlEncode(blockId); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Clear(); // In random occassions the request fails if the network is slow and it takes more than 100 seconds to upload 4MB. client.Timeout = TimeSpan.FromMinutes(uploadTimeout); Func<HttpRequestMessage> createRequest = () => { DateTime dt = DateTime.UtcNow; var req = new HttpRequestMessage(HttpMethod.Put, blockUploadUrl); req.Headers.Add( AzureHelper.DateHeaderString, dt.ToString("R", CultureInfo.InvariantCulture)); req.Headers.Add(AzureHelper.VersionHeaderString, AzureHelper.StorageApiVersion); if (!string.IsNullOrWhiteSpace(leaseId)) { log.LogMessage($"Sending request: {leaseId} {blockUploadUrl}"); req.Headers.Add("x-ms-lease-id", leaseId); } req.Headers.Add( AzureHelper.AuthorizationHeaderString, AzureHelper.AuthorizationHeader( AccountName, AccountKey, "PUT", dt, req, string.Empty, string.Empty, nextBytesToRead.ToString(), string.Empty)); Stream postStream = new MemoryStream(); postStream.Write(fileBytes, 0, nextBytesToRead); postStream.Seek(0, SeekOrigin.Begin); req.Content = new StreamContent(postStream); return req; }; log.LogMessage(MessageImportance.Low, "Sending request to upload part {0} of file {1}", countForId, fileName); using (HttpResponseMessage response = await AzureHelper.RequestWithRetry(log, client, createRequest)) { log.LogMessage( MessageImportance.Low, "Received response to upload part {0} of file {1}: Status Code:{2} Status Desc: {3}", countForId, fileName, response.StatusCode, await response.Content.ReadAsStringAsync()); } } offset += read; bytesLeft -= nextBytesToRead; countForId += 1; } } string blockListUploadUrl = blobUploadUrl + "?comp=blocklist"; using (HttpClient client = new HttpClient()) { Func<HttpRequestMessage> createRequest = () => { DateTime dt1 = DateTime.UtcNow; var req = new HttpRequestMessage(HttpMethod.Put, blockListUploadUrl); req.Headers.Add(AzureHelper.DateHeaderString, dt1.ToString("R", CultureInfo.InvariantCulture)); req.Headers.Add(AzureHelper.VersionHeaderString, AzureHelper.StorageApiVersion); if (string.IsNullOrEmpty(contentType)) { contentType = DetermineContentTypeBasedOnFileExtension(filePath); } if (!string.IsNullOrEmpty(contentType)) { req.Headers.Add(AzureHelper.ContentTypeString, contentType); } string cacheControl = DetermineCacheControlBasedOnFileExtension(filePath); if (!string.IsNullOrEmpty(cacheControl)) { req.Headers.Add(AzureHelper.CacheControlString, cacheControl); } var body = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><BlockList>"); foreach (object item in blockIds) body.AppendFormat("<Latest>{0}</Latest>", item); body.Append("</BlockList>"); byte[] bodyData = Encoding.UTF8.GetBytes(body.ToString()); if (!string.IsNullOrWhiteSpace(leaseId)) { log.LogMessage($"Sending list request: {leaseId} {blockListUploadUrl}"); req.Headers.Add("x-ms-lease-id", leaseId); } req.Headers.Add( AzureHelper.AuthorizationHeaderString, AzureHelper.AuthorizationHeader( AccountName, AccountKey, "PUT", dt1, req, string.Empty, string.Empty, bodyData.Length.ToString(), string.Empty)); Stream postStream = new MemoryStream(); postStream.Write(bodyData, 0, bodyData.Length); postStream.Seek(0, SeekOrigin.Begin); req.Content = new StreamContent(postStream); return req; }; using (HttpResponseMessage response = await AzureHelper.RequestWithRetry(log, client, createRequest)) { log.LogMessage( MessageImportance.Low, "Received response to combine block list for file {0}: Status Code:{1} Status Desc: {2}", fileName, response.StatusCode, await response.Content.ReadAsStringAsync()); } } } private string DetermineContentTypeBasedOnFileExtension(string filename) { if (Path.GetExtension(filename) == ".svg") { return "image/svg+xml"; } else if (Path.GetExtension(filename) == ".version") { return "text/plain"; } return string.Empty; } private string DetermineCacheControlBasedOnFileExtension(string filename) { if (Path.GetExtension(filename) == ".svg") { return "No-Cache"; } return string.Empty; } } }
using System; using System.Collections.Generic; using System.Threading; using System.IO; using System.Drawing; using System.Globalization; using OpenMetaverse; using OpenMetaverse.Http; using OpenMetaverse.Imaging; namespace importprimscript { class Sculpt { public string Name; public string TextureFile; public UUID TextureID; public string SculptFile; public UUID SculptID; public Vector3 Scale; public Vector3 Offset; } class importprimscript { static GridClient Client = new GridClient(); static Sculpt CurrentSculpt = null; static AutoResetEvent RezzedEvent = new AutoResetEvent(false); static Vector3 RootPosition = Vector3.Zero; static List<uint> RezzedPrims = new List<uint>(); static UUID UploadFolderID = UUID.Zero; static void Main(string[] args) { if (args.Length != 8 && args.Length != 9) { Console.WriteLine("Usage: importprimscript.exe [firstname] [lastname] [password] " + "[loginuri] [Simulator] [x] [y] [z] [input.primscript]" + Environment.NewLine + "Example: importprimscript.exe My Bot password " + "Hooper 128 128 40 maya-export" + Path.DirectorySeparatorChar + "ant.primscript" + Environment.NewLine + "(the loginuri is optional and only used for logging in to another grid)"); Environment.Exit(-1); } // Strip quotes from any arguments for (int i = 0; i < args.Length; i++) args[i] = args[i].Trim(new char[] { '"' }); // Parse the primscript file string scriptfilename = args[args.Length - 1]; string error; List<Sculpt> sculpties = ParsePrimscript(scriptfilename, out error); scriptfilename = Path.GetFileNameWithoutExtension(scriptfilename); // Check for parsing errors if (error != String.Empty) { Console.WriteLine("An error was encountered reading the input file: " + error); Environment.Exit(-2); } else if (sculpties.Count == 0) { Console.WriteLine("No primitives were read from the input file"); Environment.Exit(-3); } // Add callback handlers for asset uploads finishing. new prims spotted, and logging Client.Objects.ObjectUpdate += new EventHandler<PrimEventArgs>(Objects_OnNewPrim); Logger.OnLogMessage += new Logger.LogCallback(Client_OnLogMessage); // Optimize the connection for our purposes Client.Self.Movement.Camera.Far = 64f; Client.Settings.MULTIPLE_SIMS = false; Client.Settings.SEND_AGENT_UPDATES = true; Settings.LOG_LEVEL = Helpers.LogLevel.None; Client.Settings.ALWAYS_REQUEST_OBJECTS = true; Client.Settings.ALWAYS_DECODE_OBJECTS = true; Client.Settings.THROTTLE_OUTGOING_PACKETS = false; Client.Throttle.Land = 0; Client.Throttle.Wind = 0; Client.Throttle.Cloud = 0; // Not sure if Asset or Texture will help with uploads, but it won't hurt Client.Throttle.Asset = 220000.0f; Client.Throttle.Texture = 446000.0f; Client.Throttle.Task = 446000.0f; // Create a handler for the event queue connecting, so we know when // it is safe to start uploading AutoResetEvent eventQueueEvent = new AutoResetEvent(false); EventHandler<EventQueueRunningEventArgs> eventQueueCallback = delegate(object sender, EventQueueRunningEventArgs e) { if (e.Simulator == Client.Network.CurrentSim) eventQueueEvent.Set(); }; Client.Network.EventQueueRunning += eventQueueCallback; int x = Int32.Parse(args[args.Length - 4]); int y = Int32.Parse(args[args.Length - 3]); int z = Int32.Parse(args[args.Length - 2]); string start = NetworkManager.StartLocation(args[args.Length - 5], x, y, z); LoginParams loginParams = Client.Network.DefaultLoginParams(args[0], args[1], args[2], "importprimscript", "1.4.0"); loginParams.Start = start; if (args.Length == 9) loginParams.URI = args[3]; // Attempt to login if (!Client.Network.Login(loginParams)) { Console.WriteLine("Login failed: " + Client.Network.LoginMessage); Environment.Exit(-4); } // Need to be connected to the event queue before we can upload Console.WriteLine("Login succeeded, waiting for the event handler to connect..."); if (!eventQueueEvent.WaitOne(1000 * 90, false)) { Console.WriteLine("Event queue connection timed out, disconnecting..."); Client.Network.Logout(); Environment.Exit(-5); } // Don't need this anymore Client.Network.EventQueueRunning -= eventQueueCallback; // Set the root position for the import RootPosition = Client.Self.SimPosition; RootPosition.Z += 3.0f; // TODO: Check if our account balance is high enough to upload everything // // Create a folder to hold all of our texture uploads UploadFolderID = Client.Inventory.CreateFolder(Client.Inventory.Store.RootFolder.UUID, scriptfilename); // Loop through each sculpty and do what we need to do for (int i = 0; i < sculpties.Count; i++) { // Upload the sculpt map and texture sculpties[i].SculptID = UploadImage(sculpties[i].SculptFile, true); sculpties[i].TextureID = UploadImage(sculpties[i].TextureFile, false); // Check for failed uploads if (sculpties[i].SculptID == UUID.Zero) { Console.WriteLine("Sculpt map " + sculpties[i].SculptFile + " failed to upload, skipping " + sculpties[i].Name); continue; } else if (sculpties[i].TextureID == UUID.Zero) { Console.WriteLine("Texture " + sculpties[i].TextureFile + " failed to upload, skipping " + sculpties[i].Name); continue; } // Create basic spherical volume parameters. It will be set to // a scultpy in the callback for new objects being created Primitive.ConstructionData volume = new Primitive.ConstructionData(); volume.PCode = PCode.Prim; volume.Material = Material.Wood; volume.PathScaleY = 0.5f; volume.PathCurve = PathCurve.Circle; volume.ProfileCurve = ProfileCurve.Circle; // Rez this prim CurrentSculpt = sculpties[i]; Client.Objects.AddPrim(Client.Network.CurrentSim, volume, UUID.Zero, RootPosition + CurrentSculpt.Offset, CurrentSculpt.Scale, Quaternion.Identity); // Wait for the prim to rez and the properties be set for it if (!RezzedEvent.WaitOne(1000 * 10, false)) { Console.WriteLine("Timed out waiting for prim " + CurrentSculpt.Name + " to rez, skipping"); continue; } } CurrentSculpt = null; lock (RezzedPrims) { // Set full permissions for all of the objects Client.Objects.SetPermissions(Client.Network.CurrentSim, RezzedPrims, PermissionWho.All, PermissionMask.All, true); // Link the entire object together Client.Objects.LinkPrims(Client.Network.CurrentSim, RezzedPrims); } Console.WriteLine("Rezzed, textured, and linked " + RezzedPrims.Count + " sculpted prims, logging out..."); Client.Network.Logout(); } static void Client_OnLogMessage(object message, Helpers.LogLevel level) { if (level >= Helpers.LogLevel.Warning) Console.WriteLine(level + ": " + message); } static UUID UploadImage(string filename, bool lossless) { UUID newAssetID = UUID.Zero; byte[] jp2data = null; try { Bitmap image = (Bitmap)Bitmap.FromFile(filename); jp2data = OpenJPEG.EncodeFromImage(image, lossless); } catch (Exception ex) { Console.WriteLine("Failed to encode image file " + filename + ": " + ex.ToString()); return UUID.Zero; } AutoResetEvent uploadEvent = new AutoResetEvent(false); Client.Inventory.RequestCreateItemFromAsset(jp2data, Path.GetFileNameWithoutExtension(filename), "Uploaded with importprimscript", AssetType.Texture, InventoryType.Texture, UploadFolderID, delegate(bool success, string status, UUID itemID, UUID assetID) { if (success) { Console.WriteLine("Finished uploading image " + filename + ", AssetID: " + assetID.ToString()); newAssetID = assetID; } else { Console.WriteLine("Failed to upload image file " + filename + ": " + status); } uploadEvent.Set(); } ); // The images are small, 60 seconds should be plenty uploadEvent.WaitOne(1000 * 60, false); return newAssetID; } static void Objects_OnNewPrim(object sender, PrimEventArgs e) { Primitive prim = e.Prim; if (CurrentSculpt != null && (prim.Flags & PrimFlags.CreateSelected) != 0 && !RezzedPrims.Contains(prim.LocalID)) { lock (RezzedPrims) RezzedPrims.Add(prim.LocalID); Console.WriteLine("Rezzed prim " + CurrentSculpt.Name + ", setting properties"); // Deselect the prim Client.Objects.DeselectObject(Client.Network.CurrentSim, prim.LocalID); // Set the prim position Client.Objects.SetPosition(Client.Network.CurrentSim, prim.LocalID, RootPosition + CurrentSculpt.Offset); // Set the texture Primitive.TextureEntry textures = new Primitive.TextureEntry(CurrentSculpt.TextureID); Client.Objects.SetTextures(Client.Network.CurrentSim, prim.LocalID, textures); // Turn it in to a sculpted prim Primitive.SculptData sculpt = new Primitive.SculptData(); sculpt.SculptTexture = CurrentSculpt.SculptID; sculpt.Type = SculptType.Sphere; Client.Objects.SetSculpt(Client.Network.CurrentSim, prim.LocalID, sculpt); // Set the prim name if (!String.IsNullOrEmpty(CurrentSculpt.Name)) Client.Objects.SetName(Client.Network.CurrentSim, prim.LocalID, CurrentSculpt.Name); RezzedEvent.Set(); } } static List<Sculpt> ParsePrimscript(string primscriptfile, out string error) { string line; Sculpt current = null; List<Sculpt> sculpties = new List<Sculpt>(); error = String.Empty; StreamReader primscript = null; // Parse a directory out of the primscriptfile string, if one exists string path = Path.GetDirectoryName(primscriptfile); if (!String.IsNullOrEmpty(path)) path += Path.DirectorySeparatorChar; else path = String.Empty; try { primscript = File.OpenText(primscriptfile); while ((line = primscript.ReadLine()) != null) { string[] words = line.Split(new char[] { ' ' }); if (words.Length > 0) { if (current != null) { switch (words[0]) { case "newPrim": if (current.Scale != Vector3.Zero && !String.IsNullOrEmpty(current.SculptFile) && !String.IsNullOrEmpty(current.TextureFile)) { // Add the previous prim to the list as it is now finalized sculpties.Add(current); } // Start a new prim current = new Sculpt(); break; case "prim": // The only useful bit of information here is the prim name if (words.Length >= 3) current.Name = words[2]; break; case "shape": // This line has the name of the sculpt texture if (words.Length >= 3) current.SculptFile = path + words[2] + ".bmp"; break; case "texture": // This line has the name of the actual texture if (words.Length >= 3) current.TextureFile = path + words[2] + ".bmp"; break; case "transform": // Get some primitive params if (words.Length >= 9) { float x, y, z; x = Single.Parse(words[2], CultureInfo.InvariantCulture); y = Single.Parse(words[3], CultureInfo.InvariantCulture); z = Single.Parse(words[4], CultureInfo.InvariantCulture); current.Scale = new Vector3(x, y, z); x = Single.Parse(words[6], CultureInfo.InvariantCulture); y = Single.Parse(words[7], CultureInfo.InvariantCulture); z = Single.Parse(words[8], CultureInfo.InvariantCulture); current.Offset = new Vector3(x, y, z); } break; } } else if (words[0] == "newPrim") { // Start a new prim current = new Sculpt(); } } } // Add the final prim if (current != null && current.Scale != Vector3.Zero && !String.IsNullOrEmpty(current.SculptFile) && !String.IsNullOrEmpty(current.TextureFile)) { // Add the previous prim to the list as it is now finalized sculpties.Add(current); } } catch (Exception ex) { error = ex.ToString(); } finally { if (primscript != null) primscript.Close(); } return sculpties; } } }
using FluentAssertions; using NUnit.Framework; namespace Facility.Definition.UnitTests; public sealed class FieldTests { [Test] public void InvalidName() { new ServiceFieldInfo(name: "4u", typeName: "int32").IsValid.Should().BeFalse(); } [TestCase("string", ServiceTypeKind.String)] [TestCase("boolean", ServiceTypeKind.Boolean)] [TestCase("double", ServiceTypeKind.Double)] [TestCase("int32", ServiceTypeKind.Int32)] [TestCase("int64", ServiceTypeKind.Int64)] [TestCase("decimal", ServiceTypeKind.Decimal)] [TestCase("bytes", ServiceTypeKind.Bytes)] [TestCase("object", ServiceTypeKind.Object)] [TestCase("error", ServiceTypeKind.Error)] public void PrimitiveFields(string name, ServiceTypeKind kind) { var service = TestUtility.ParseTestApi("service TestApi { data One { x: xyzzy; } }".Replace("xyzzy", name)); var dto = service.Dtos.Single(); var field = dto.Fields.Single(); field.Name.Should().Be("x"); field.Attributes.Count.Should().Be(0); field.Summary.Should().Be(""); var type = service.GetFieldType(field)!; type.Kind.Should().Be(kind); type.Dto.Should().BeNull(); type.Enum.Should().BeNull(); type.ValueType.Should().BeNull(); TestUtility.GenerateFsd(service).Should().Equal( "// DO NOT EDIT: generated by TestUtility", "", "service TestApi", "{", "\tdata One", "\t{", $"\t\tx: {name};", "\t}", "}", ""); } [Test] public void CaseSensitivePrimitive() { TestUtility.ParseInvalidTestApi("service TestApi { data One { x: Boolean; } }") .Message.Should().Be("TestApi.fsd(1,33): Unknown field type 'Boolean'."); } [Test] public void EnumField() { var service = TestUtility.ParseTestApi("service TestApi { enum MyEnum { X } data One { x: MyEnum; } }"); var dto = service.Dtos.Single(); var field = dto.Fields.Single(); field.Name.Should().Be("x"); field.Attributes.Count.Should().Be(0); field.Summary.Should().Be(""); var type = service.GetFieldType(field)!; type.Kind.Should().Be(ServiceTypeKind.Enum); type.Dto.Should().BeNull(); type.Enum!.Name.Should().Be("MyEnum"); type.ValueType.Should().BeNull(); TestUtility.GenerateFsd(service).Should().Equal( "// DO NOT EDIT: generated by TestUtility", "", "service TestApi", "{", "\tenum MyEnum", "\t{", "\t\tX,", "\t}", "", "\tdata One", "\t{", "\t\tx: MyEnum;", "\t}", "}", ""); } [Test] public void DtoField() { var service = TestUtility.ParseTestApi("service TestApi { data MyDto { x: int32; } data One { x: MyDto; } }"); var dto = service.Dtos.First(x => x.Name == "One"); var field = dto.Fields.Single(); field.Name.Should().Be("x"); field.Attributes.Count.Should().Be(0); field.Summary.Should().Be(""); var type = service.GetFieldType(field)!; type.Kind.Should().Be(ServiceTypeKind.Dto); type.Dto!.Name.Should().Be("MyDto"); type.Enum.Should().BeNull(); type.ValueType.Should().BeNull(); TestUtility.GenerateFsd(service).Should().Equal( "// DO NOT EDIT: generated by TestUtility", "", "service TestApi", "{", "\tdata MyDto", "\t{", "\t\tx: int32;", "\t}", "", "\tdata One", "\t{", "\t\tx: MyDto;", "\t}", "}", ""); } [Test] public void RecursiveDtoField() { var service = TestUtility.ParseTestApi("service TestApi { data MyDto { x: MyDto; } }"); var dto = service.Dtos.Single(); var field = dto.Fields.Single(); field.Name.Should().Be("x"); field.Attributes.Count.Should().Be(0); field.Summary.Should().Be(""); var type = service.GetFieldType(field)!; type.Kind.Should().Be(ServiceTypeKind.Dto); type.Dto!.Name.Should().Be("MyDto"); type.Enum.Should().BeNull(); type.ValueType.Should().BeNull(); TestUtility.GenerateFsd(service).Should().Equal( "// DO NOT EDIT: generated by TestUtility", "", "service TestApi", "{", "\tdata MyDto", "\t{", "\t\tx: MyDto;", "\t}", "}", ""); } [Test] public void TwoFieldsSameName() { TestUtility.ParseInvalidTestApi("service TestApi { data One { x: int32; x: int64;} }") .Message.Should().Be("TestApi.fsd(1,40): Duplicate field: x"); } [Test] public void InvalidFieldType() { TestUtility.ParseInvalidTestApi("service TestApi { data One { x: X; } }") .Message.Should().Be("TestApi.fsd(1,33): Unknown field type 'X'."); } [Test] public void ResultOfDto() { var service = TestUtility.ParseTestApi("service TestApi { data One { x: result<One>; } }"); var dto = service.Dtos.Single(); var field = dto.Fields.Single(); field.Name.Should().Be("x"); field.Attributes.Count.Should().Be(0); field.Summary.Should().Be(""); var type = service.GetFieldType(field)!; type.Kind.Should().Be(ServiceTypeKind.Result); type.ValueType!.Kind.Should().Be(ServiceTypeKind.Dto); type.ValueType.Dto!.Name.Should().Be("One"); } [Test] public void ResultOfEnumInvalid() { TestUtility.ParseInvalidTestApi("service TestApi { enum Xs { x, xx }; data One { x: result<Xs>; } }"); } [TestCase("string", ServiceTypeKind.String)] [TestCase("boolean", ServiceTypeKind.Boolean)] [TestCase("double", ServiceTypeKind.Double)] [TestCase("int32", ServiceTypeKind.Int32)] [TestCase("int64", ServiceTypeKind.Int64)] [TestCase("decimal", ServiceTypeKind.Decimal)] [TestCase("bytes", ServiceTypeKind.Bytes)] [TestCase("object", ServiceTypeKind.Object)] [TestCase("error", ServiceTypeKind.Error)] [TestCase("Dto", ServiceTypeKind.Dto)] [TestCase("Enum", ServiceTypeKind.Enum)] [TestCase("result<Dto>", ServiceTypeKind.Result)] [TestCase("int32[]", ServiceTypeKind.Array)] [TestCase("map<int32>", ServiceTypeKind.Map)] public void ArrayOfAnything(string name, ServiceTypeKind kind) { var service = TestUtility.ParseTestApi("service TestApi { enum Enum { x, y } data Dto { x: xyzzy[]; } }".Replace("xyzzy", name)); var dto = service.Dtos.Single(); var field = dto.Fields.Single(); field.Name.Should().Be("x"); field.Attributes.Count.Should().Be(0); field.Summary.Should().Be(""); var type = service.GetFieldType(field)!; type.Kind.Should().Be(ServiceTypeKind.Array); type.ValueType!.Kind.Should().Be(kind); } [TestCase("string", ServiceTypeKind.String)] [TestCase("boolean", ServiceTypeKind.Boolean)] [TestCase("double", ServiceTypeKind.Double)] [TestCase("int32", ServiceTypeKind.Int32)] [TestCase("int64", ServiceTypeKind.Int64)] [TestCase("decimal", ServiceTypeKind.Decimal)] [TestCase("bytes", ServiceTypeKind.Bytes)] [TestCase("object", ServiceTypeKind.Object)] [TestCase("error", ServiceTypeKind.Error)] [TestCase("Dto", ServiceTypeKind.Dto)] [TestCase("Enum", ServiceTypeKind.Enum)] [TestCase("result<Dto>", ServiceTypeKind.Result)] [TestCase("int32[]", ServiceTypeKind.Array)] [TestCase("map<int32>", ServiceTypeKind.Map)] public void MapOfAnything(string name, ServiceTypeKind kind) { var service = TestUtility.ParseTestApi("service TestApi { enum Enum { x, y } data Dto { x: map<xyzzy>; } }".Replace("xyzzy", name)); var dto = service.Dtos.Single(); var field = dto.Fields.Single(); field.Name.Should().Be("x"); field.Attributes.Count.Should().Be(0); field.Summary.Should().Be(""); var type = service.GetFieldType(field)!; type.Kind.Should().Be(ServiceTypeKind.Map); type.ValueType!.Kind.Should().Be(kind); } [TestCase("string", ServiceTypeKind.String)] [TestCase("boolean", ServiceTypeKind.Boolean)] [TestCase("double", ServiceTypeKind.Double)] [TestCase("int32", ServiceTypeKind.Int32)] [TestCase("int64", ServiceTypeKind.Int64)] [TestCase("decimal", ServiceTypeKind.Decimal)] [TestCase("bytes", ServiceTypeKind.Bytes)] [TestCase("object", ServiceTypeKind.Object)] [TestCase("error", ServiceTypeKind.Error)] [TestCase("Dto", ServiceTypeKind.Dto)] [TestCase("Enum", ServiceTypeKind.Enum)] [TestCase("result<Dto>", ServiceTypeKind.Result)] [TestCase("int32[]", ServiceTypeKind.Array)] [TestCase("map<int32>", ServiceTypeKind.Map)] public void ResultOfAnything(string name, ServiceTypeKind kind) { var service = TestUtility.ParseTestApi("service TestApi { enum Enum { x, y } data Dto { x: result<xyzzy>; } }".Replace("xyzzy", name)); var dto = service.Dtos.Single(); var field = dto.Fields.Single(); field.Name.Should().Be("x"); field.Attributes.Count.Should().Be(0); field.Summary.Should().Be(""); var type = service.GetFieldType(field)!; type.Kind.Should().Be(ServiceTypeKind.Result); type.ValueType!.Kind.Should().Be(kind); } [Test] public void FieldParts() { var service = TestUtility.ParseTestApi("service TestApi { data One { x: string; } }"); var field = service.Dtos.Single().Fields.Single(); field.Position!.LineNumber.Should().Be(1); field.Position.ColumnNumber.Should().Be(30); var namePart = field.GetPart(ServicePartKind.Name)!; namePart.Position.LineNumber.Should().Be(1); namePart.Position.ColumnNumber.Should().Be(30); namePart.EndPosition.LineNumber.Should().Be(1); namePart.EndPosition.ColumnNumber.Should().Be(31); var typePart = field.GetPart(ServicePartKind.TypeName)!; typePart.Position.LineNumber.Should().Be(1); typePart.Position.ColumnNumber.Should().Be(33); typePart.EndPosition.LineNumber.Should().Be(1); typePart.EndPosition.ColumnNumber.Should().Be(39); } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. #nullable disable using System.Collections.Generic; using System.Linq; using Scriban.Helpers; using Scriban.Parsing; using Scriban.Runtime; using System.Threading.Tasks; namespace Scriban.Syntax { /// <summary> /// Base class for a loop statement /// </summary> #if SCRIBAN_PUBLIC public #else internal #endif abstract partial class ScriptLoopStatementBase : ScriptStatement { protected virtual void BeforeLoop(TemplateContext context) { } /// <summary> /// Base implementation for a loop single iteration /// </summary> /// <param name="context">The context</param> /// <param name="state">The state of the loop</param> /// <returns></returns> protected abstract object LoopItem(TemplateContext context, LoopState state); protected virtual LoopState CreateLoopState() { return new LoopState(); } protected bool ContinueLoop(TemplateContext context) { // Return must bubble up to call site if (context.FlowState == ScriptFlowState.Return) { return false; } // If we need to break, restore to none state var result = context.FlowState != ScriptFlowState.Break; context.FlowState = ScriptFlowState.None; return result; } protected virtual void AfterLoop(TemplateContext context) { } public override object Evaluate(TemplateContext context) { // Notify the context that we enter a loop block (used for variable with scope Loop) object result = null; context.EnterLoop(this); try { result = EvaluateImpl(context); } finally { // Level scope block context.ExitLoop(this); if (context.FlowState != ScriptFlowState.Return) { // Revert to flow state to none unless we have a return that must be handled at a higher level context.FlowState = ScriptFlowState.None; } } return result; } protected abstract object EvaluateImpl(TemplateContext context); #if !SCRIBAN_NO_ASYNC protected abstract ValueTask<object> EvaluateImplAsync(TemplateContext context); protected abstract ValueTask<object> LoopItemAsync(TemplateContext context, LoopState state); protected virtual ValueTask BeforeLoopAsync(TemplateContext context) { return new ValueTask(); } protected virtual ValueTask AfterLoopAsync(TemplateContext context) { return new ValueTask(); } #endif /// <summary> /// Store the loop state /// </summary> protected class LoopState : IScriptObject { private int _length; private object _lengthObject; public int Index { get; set; } public int LocalIndex { get; set; } public bool IsFirst => Index == 0; public bool IsEven => (Index & 1) == 0; public bool IsOdd => !IsEven; public bool ValueChanged { get; set; } public bool IsLast { get; set; } public int Length { get => _length; set { _length = value; _lengthObject = value; } } public int Count { get; set; } public IEnumerable<string> GetMembers() { return Enumerable.Empty<string>(); } public virtual bool Contains(string member) { switch (member) { case "index": case "index0": case "first": case "even": case "odd": case "last": return true; case "length": return _lengthObject != null; case "rindex": case "rindex0": return _lengthObject != null; case "changed": return true; } return false; } public bool IsReadOnly { get; set; } public virtual bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value) { value = null; var isLiquid = context.IsLiquid; switch (member) { case "index": value = isLiquid ? Index + 1 : Index; return true; case "length": value = _lengthObject; return _lengthObject != null; case "first": value = IsFirst ? BoxHelper.TrueObject : BoxHelper.FalseObject; return true; case "even": value = IsEven ? BoxHelper.TrueObject : BoxHelper.FalseObject; return true; case "odd": value = IsOdd ? BoxHelper.TrueObject : BoxHelper.FalseObject; return true; case "last": value = IsLast ? BoxHelper.TrueObject : BoxHelper.FalseObject; return true; case "changed": value = ValueChanged ? BoxHelper.TrueObject : BoxHelper.FalseObject; return true; case "rindex": if (_lengthObject != null) { value = isLiquid ? _length - Index : _length - Index - 1; } return _lengthObject != null; default: if (isLiquid) { if (member == "index0") { value = Index; return true; } if (member == "rindex0") { value = _length - Index - 1; return true; } } return false; } } public bool CanWrite(string member) { throw new System.NotImplementedException(); } public bool TrySetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly) { return false; } public bool Remove(string member) { return false; } public void SetReadOnly(string member, bool readOnly) { } public IScriptObject Clone(bool deep) { return (IScriptObject)MemberwiseClone(); } } } }
using System; using System.Collections; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.CryptoPro; using Org.BouncyCastle.Asn1.Eac; using Org.BouncyCastle.Asn1.Iana; using Org.BouncyCastle.Asn1.Misc; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.Oiw; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.TeleTrust; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.X509; using Org.BouncyCastle.X509.Store; namespace Org.BouncyCastle.Cms { internal class CmsSignedHelper { internal static readonly CmsSignedHelper Instance = new CmsSignedHelper(); private static readonly Hashtable encryptionAlgs = new Hashtable(); private static readonly Hashtable digestAlgs = new Hashtable(); private static readonly Hashtable digestAliases = new Hashtable(); private static void AddEntries(DerObjectIdentifier oid, string digest, string encryption) { string alias = oid.Id; digestAlgs.Add(alias, digest); encryptionAlgs.Add(alias, encryption); } static CmsSignedHelper() { AddEntries(NistObjectIdentifiers.DsaWithSha224, "SHA224", "DSA"); AddEntries(NistObjectIdentifiers.DsaWithSha256, "SHA256", "DSA"); AddEntries(NistObjectIdentifiers.DsaWithSha384, "SHA384", "DSA"); AddEntries(NistObjectIdentifiers.DsaWithSha512, "SHA512", "DSA"); AddEntries(OiwObjectIdentifiers.DsaWithSha1, "SHA1", "DSA"); AddEntries(OiwObjectIdentifiers.MD4WithRsa, "MD4", "RSA"); AddEntries(OiwObjectIdentifiers.MD4WithRsaEncryption, "MD4", "RSA"); AddEntries(OiwObjectIdentifiers.MD5WithRsa, "MD5", "RSA"); AddEntries(OiwObjectIdentifiers.Sha1WithRsa, "SHA1", "RSA"); AddEntries(PkcsObjectIdentifiers.MD2WithRsaEncryption, "MD2", "RSA"); AddEntries(PkcsObjectIdentifiers.MD4WithRsaEncryption, "MD4", "RSA"); AddEntries(PkcsObjectIdentifiers.MD5WithRsaEncryption, "MD5", "RSA"); AddEntries(PkcsObjectIdentifiers.Sha1WithRsaEncryption, "SHA1", "RSA"); AddEntries(PkcsObjectIdentifiers.Sha224WithRsaEncryption, "SHA224", "RSA"); AddEntries(PkcsObjectIdentifiers.Sha256WithRsaEncryption, "SHA256", "RSA"); AddEntries(PkcsObjectIdentifiers.Sha384WithRsaEncryption, "SHA384", "RSA"); AddEntries(PkcsObjectIdentifiers.Sha512WithRsaEncryption, "SHA512", "RSA"); AddEntries(X9ObjectIdentifiers.ECDsaWithSha1, "SHA1", "ECDSA"); AddEntries(X9ObjectIdentifiers.ECDsaWithSha224, "SHA224", "ECDSA"); AddEntries(X9ObjectIdentifiers.ECDsaWithSha256, "SHA256", "ECDSA"); AddEntries(X9ObjectIdentifiers.ECDsaWithSha384, "SHA384", "ECDSA"); AddEntries(X9ObjectIdentifiers.ECDsaWithSha512, "SHA512", "ECDSA"); AddEntries(X9ObjectIdentifiers.IdDsaWithSha1, "SHA1", "DSA"); AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1", "ECDSA"); AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224", "ECDSA"); AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_256, "SHA256", "ECDSA"); AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_384, "SHA384", "ECDSA"); AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_512, "SHA512", "ECDSA"); AddEntries(EacObjectIdentifiers.id_TA_RSA_v1_5_SHA_1, "SHA1", "RSA"); AddEntries(EacObjectIdentifiers.id_TA_RSA_v1_5_SHA_256, "SHA256", "RSA"); AddEntries(EacObjectIdentifiers.id_TA_RSA_PSS_SHA_1, "SHA1", "RSAandMGF1"); AddEntries(EacObjectIdentifiers.id_TA_RSA_PSS_SHA_256, "SHA256", "RSAandMGF1"); encryptionAlgs.Add(X9ObjectIdentifiers.IdDsa.Id, "DSA"); encryptionAlgs.Add(PkcsObjectIdentifiers.RsaEncryption.Id, "RSA"); encryptionAlgs.Add(TeleTrusTObjectIdentifiers.TeleTrusTRsaSignatureAlgorithm, "RSA"); encryptionAlgs.Add(X509ObjectIdentifiers.IdEARsa.Id, "RSA"); encryptionAlgs.Add(CmsSignedGenerator.EncryptionRsaPss, "RSAandMGF1"); encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x94.Id, "GOST3410"); encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x2001.Id, "ECGOST3410"); encryptionAlgs.Add("1.3.6.1.4.1.5849.1.6.2", "ECGOST3410"); encryptionAlgs.Add("1.3.6.1.4.1.5849.1.1.5", "GOST3410"); digestAlgs.Add(PkcsObjectIdentifiers.MD2.Id, "MD2"); digestAlgs.Add(PkcsObjectIdentifiers.MD4.Id, "MD4"); digestAlgs.Add(PkcsObjectIdentifiers.MD5.Id, "MD5"); digestAlgs.Add(OiwObjectIdentifiers.IdSha1.Id, "SHA1"); digestAlgs.Add(NistObjectIdentifiers.IdSha224.Id, "SHA224"); digestAlgs.Add(NistObjectIdentifiers.IdSha256.Id, "SHA256"); digestAlgs.Add(NistObjectIdentifiers.IdSha384.Id, "SHA384"); digestAlgs.Add(NistObjectIdentifiers.IdSha512.Id, "SHA512"); digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD128.Id, "RIPEMD128"); digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD160.Id, "RIPEMD160"); digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD256.Id, "RIPEMD256"); digestAlgs.Add(CryptoProObjectIdentifiers.GostR3411.Id, "GOST3411"); digestAlgs.Add("1.3.6.1.4.1.5849.1.2.1", "GOST3411"); digestAliases.Add("SHA1", new string[] { "SHA-1" }); digestAliases.Add("SHA224", new string[] { "SHA-224" }); digestAliases.Add("SHA256", new string[] { "SHA-256" }); digestAliases.Add("SHA384", new string[] { "SHA-384" }); digestAliases.Add("SHA512", new string[] { "SHA-512" }); } /** * Return the digest algorithm using one of the standard JCA string * representations rather than the algorithm identifier (if possible). */ internal string GetDigestAlgName( string digestAlgOid) { string algName = (string)digestAlgs[digestAlgOid]; if (algName != null) { return algName; } return digestAlgOid; } internal string[] GetDigestAliases( string algName) { string[] aliases = (string[]) digestAliases[algName]; return aliases == null ? new String[0] : (string[]) aliases.Clone(); } /** * Return the digest encryption algorithm using one of the standard * JCA string representations rather than the algorithm identifier (if * possible). */ internal string GetEncryptionAlgName( string encryptionAlgOid) { string algName = (string) encryptionAlgs[encryptionAlgOid]; if (algName != null) { return algName; } return encryptionAlgOid; } internal IDigest GetDigestInstance( string algorithm) { try { return DigestUtilities.GetDigest(algorithm); } catch (SecurityUtilityException e) { // This is probably superfluous on C#, since no provider infrastructure, // assuming DigestUtilities already knows all the aliases foreach (string alias in GetDigestAliases(algorithm)) { try { return DigestUtilities.GetDigest(alias); } catch (SecurityUtilityException) {} } throw e; } } internal ISigner GetSignatureInstance( string algorithm) { return SignerUtilities.GetSigner(algorithm); } internal IX509Store CreateAttributeStore( string type, Asn1Set certSet) { IList certs = new ArrayList(); if (certSet != null) { foreach (Asn1Encodable ae in certSet) { try { Asn1Object obj = ae.ToAsn1Object(); if (obj is Asn1TaggedObject) { Asn1TaggedObject tagged = (Asn1TaggedObject)obj; if (tagged.TagNo == 2) { certs.Add( new X509V2AttributeCertificate( Asn1Sequence.GetInstance(tagged, false).GetEncoded())); } } } catch (Exception ex) { throw new CmsException("can't re-encode attribute certificate!", ex); } } } try { return X509StoreFactory.Create( "AttributeCertificate/" + type, new X509CollectionStoreParameters(certs)); } catch (ArgumentException e) { throw new CmsException("can't setup the X509Store", e); } } internal IX509Store CreateCertificateStore( string type, Asn1Set certSet) { IList certs = new ArrayList(); if (certSet != null) { AddCertsFromSet(certs, certSet); } try { return X509StoreFactory.Create( "Certificate/" + type, new X509CollectionStoreParameters(certs)); } catch (ArgumentException e) { throw new CmsException("can't setup the X509Store", e); } } internal IX509Store CreateCrlStore( string type, Asn1Set crlSet) { IList crls = new ArrayList(); if (crlSet != null) { AddCrlsFromSet(crls, crlSet); } try { return X509StoreFactory.Create( "CRL/" + type, new X509CollectionStoreParameters(crls)); } catch (ArgumentException e) { throw new CmsException("can't setup the X509Store", e); } } private void AddCertsFromSet( IList certs, Asn1Set certSet) { X509CertificateParser cf = new X509CertificateParser(); foreach (Asn1Encodable ae in certSet) { try { Asn1Object obj = ae.ToAsn1Object(); if (obj is Asn1Sequence) { // TODO Build certificate directly from sequence? certs.Add(cf.ReadCertificate(obj.GetEncoded())); } } catch (Exception ex) { throw new CmsException("can't re-encode certificate!", ex); } } } private void AddCrlsFromSet( IList crls, Asn1Set crlSet) { X509CrlParser cf = new X509CrlParser(); foreach (Asn1Encodable ae in crlSet) { try { // TODO Build CRL directly from ae.ToAsn1Object()? crls.Add(cf.ReadCrl(ae.GetEncoded())); } catch (Exception ex) { throw new CmsException("can't re-encode CRL!", ex); } } } internal AlgorithmIdentifier FixAlgID( AlgorithmIdentifier algId) { if (algId.Parameters == null) return new AlgorithmIdentifier(algId.ObjectID, DerNull.Instance); return algId; } private bool anyCertHasTypeOther() { // not supported return false; } private bool anyCertHasV1Attribute() { // obsolete return false; } private bool anyCertHasV2Attribute() { // TODO return false; } private bool anyCrlHasTypeOther() { // not supported return false; } } }
using System; using System.Reflection; using System.Web; using System.Web.UI; namespace umbraco.BusinessLogic { /// <summary> /// The StateHelper class provides general helper methods for handling sessions, context, viewstate and cookies. /// </summary> [Obsolete("DO NOT USE THIS ANYMORE! REPLACE ALL CALLS WITH NEW EXTENSION METHODS")] public class StateHelper { private static HttpContextBase _customHttpContext; /// <summary> /// Gets/sets the HttpContext object, this is generally used for unit testing. By default this will /// use the HttpContext.Current /// </summary> internal static HttpContextBase HttpContext { get { if (_customHttpContext == null && System.Web.HttpContext.Current != null) { //return the current HttpContxt, do NOT store this in the _customHttpContext field //as it will persist across reqeusts! return new HttpContextWrapper(System.Web.HttpContext.Current); } if (_customHttpContext == null && System.Web.HttpContext.Current == null) { throw new NullReferenceException("The HttpContext property has not been set or the object execution is not running inside of an HttpContext"); } return _customHttpContext; } set { _customHttpContext = value; } } #region Session Helpers /// <summary> /// Gets the session value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns></returns> public static T GetSessionValue<T>(string key) { return GetSessionValue<T>(HttpContext, key); } /// <summary> /// Gets the session value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> [Obsolete("Use the GetSessionValue accepting an HttpContextBase instead")] public static T GetSessionValue<T>(HttpContext context, string key) { return GetSessionValue<T>(new HttpContextWrapper(context), key); } /// <summary> /// Gets the session value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> public static T GetSessionValue<T>(HttpContextBase context, string key) { if (context == null) return default(T); object o = context.Session[key]; if (o == null) return default(T); return (T)o; } /// <summary> /// Sets a session value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetSessionValue(string key, object value) { SetSessionValue(HttpContext, key, value); } /// <summary> /// Sets the session value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> [Obsolete("Use the SetSessionValue accepting an HttpContextBase instead")] public static void SetSessionValue(HttpContext context, string key, object value) { SetSessionValue(new HttpContextWrapper(context), key, value); } /// <summary> /// Sets the session value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetSessionValue(HttpContextBase context, string key, object value) { if (context == null) return; context.Session[key] = value; } #endregion #region Context Helpers /// <summary> /// Gets the context value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns></returns> public static T GetContextValue<T>(string key) { return GetContextValue<T>(HttpContext, key); } /// <summary> /// Gets the context value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> [Obsolete("Use the GetContextValue accepting an HttpContextBase instead")] public static T GetContextValue<T>(HttpContext context, string key) { return GetContextValue<T>(new HttpContextWrapper(context), key); } /// <summary> /// Gets the context value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> public static T GetContextValue<T>(HttpContextBase context, string key) { if (context == null) return default(T); object o = context.Items[key]; if (o == null) return default(T); return (T)o; } /// <summary> /// Sets the context value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetContextValue(string key, object value) { SetContextValue(HttpContext, key, value); } /// <summary> /// Sets the context value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> [Obsolete("Use the SetContextValue accepting an HttpContextBase instead")] public static void SetContextValue(HttpContext context, string key, object value) { SetContextValue(new HttpContextWrapper(context), key, value); } /// <summary> /// Sets the context value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetContextValue(HttpContextBase context, string key, object value) { if (context == null) return; context.Items[key] = value; } #endregion #region ViewState Helpers /// <summary> /// Gets the state bag. /// </summary> /// <returns></returns> private static StateBag GetStateBag() { //if (HttpContext.Current == null) // return null; var page = HttpContext.CurrentHandler as Page; if (page == null) return null; var pageType = typeof(Page); var viewState = pageType.GetProperty("ViewState", BindingFlags.GetProperty | BindingFlags.Instance); if (viewState == null) return null; return viewState.GetValue(page, null) as StateBag; } /// <summary> /// Gets the view state value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns></returns> public static T GetViewStateValue<T>(string key) { return GetViewStateValue<T>(GetStateBag(), key); } /// <summary> /// Gets a view-state value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="bag">The bag.</param> /// <param name="key">The key.</param> /// <returns></returns> public static T GetViewStateValue<T>(StateBag bag, string key) { if (bag == null) return default(T); object o = bag[key]; if (o == null) return default(T); return (T)o; } /// <summary> /// Sets the view state value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetViewStateValue(string key, object value) { SetViewStateValue(GetStateBag(), key, value); } /// <summary> /// Sets the view state value. /// </summary> /// <param name="bag">The bag.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetViewStateValue(StateBag bag, string key, object value) { if (bag != null) bag[key] = value; } #endregion #region Cookie Helpers /// <summary> /// Determines whether a cookie has a value with a specified key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the cookie has a value with the specified key; otherwise, <c>false</c>. /// </returns> [Obsolete("Use !string.IsNullOrEmpty(GetCookieValue(key))", false)] public static bool HasCookieValue(string key) { return !string.IsNullOrEmpty(GetCookieValue(key)); } /// <summary> /// Gets the cookie value. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public static string GetCookieValue(string key) { if (!Cookies.HasCookies) return null; var cookie = HttpContext.Request.Cookies[key]; return cookie == null ? null : cookie.Value; } /// <summary> /// Sets the cookie value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetCookieValue(string key, string value) { SetCookieValue(key, value, 30d); // default Umbraco expires is 30 days } /// <summary> /// Sets the cookie value including the number of days to persist the cookie /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="daysToPersist">How long the cookie should be present in the browser</param> public static void SetCookieValue(string key, string value, double daysToPersist) { if (!Cookies.HasCookies) return; var context = HttpContext; HttpCookie cookie = new HttpCookie(key, value); cookie.Expires = DateTime.Now.AddDays(daysToPersist); context.Response.Cookies.Set(cookie); cookie = context.Request.Cookies[key]; if (cookie != null) cookie.Value = value; } // zb-00004 #29956 : refactor cookies names & handling public static class Cookies { /* * helper class to manage cookies * * beware! SetValue(string value) does _not_ set expires, unless the cookie has been * configured to have one. This allows us to have cookies w/out an expires timespan. * However, default behavior in Umbraco was to set expires to 30days by default. This * must now be managed in the Cookie constructor or by using an overriden SetValue(...). * * we currently reproduce this by configuring each cookie with a 30d expires, but does * that actually make sense? shouldn't some cookie have _no_ expires? */ static readonly Cookie _preview = new Cookie("UMB_PREVIEW", 30d); // was "PreviewSet" static readonly Cookie _userContext = new Cookie("UMB_UCONTEXT", 30d); // was "UserContext" static readonly Cookie _member = new Cookie("UMB_MEMBER", 30d); // was "umbracoMember" public static Cookie Preview { get { return _preview; } } public static Cookie UserContext { get { return _userContext; } } public static Cookie Member { get { return _member; } } public static bool HasCookies { get { var context = HttpContext; // although just checking context should be enough?! // but in some (replaced) umbraco code, everything is checked... return context != null && context.Request != null & context.Request.Cookies != null && context.Response != null && context.Response.Cookies != null; } } public static void ClearAll() { HttpContext.Response.Cookies.Clear(); } public class Cookie { const string cookiesExtensionConfigKey = "umbracoCookiesExtension"; static readonly string _ext; TimeSpan _expires; string _key; static Cookie() { var appSettings = System.Configuration.ConfigurationManager.AppSettings; _ext = appSettings[cookiesExtensionConfigKey] == null ? "" : "_" + (string)appSettings[cookiesExtensionConfigKey]; } public Cookie(string key) : this(key, TimeSpan.Zero, true) { } public Cookie(string key, double days) : this(key, TimeSpan.FromDays(days), true) { } public Cookie(string key, TimeSpan expires) : this(key, expires, true) { } public Cookie(string key, bool appendExtension) : this(key, TimeSpan.Zero, appendExtension) { } public Cookie(string key, double days, bool appendExtension) : this(key, TimeSpan.FromDays(days), appendExtension) { } public Cookie(string key, TimeSpan expires, bool appendExtension) { _key = appendExtension ? key + _ext : key; _expires = expires; } public string Key { get { return _key; } } public bool HasValue { get { return RequestCookie != null; } } public string GetValue() { return RequestCookie == null ? null : RequestCookie.Value; } public void SetValue(string value) { SetValueWithDate(value, DateTime.Now + _expires); } public void SetValue(string value, double days) { SetValue(value, DateTime.Now.AddDays(days)); } public void SetValue(string value, TimeSpan expires) { SetValue(value, DateTime.Now + expires); } public void SetValue(string value, DateTime expires) { SetValueWithDate(value, expires); } private void SetValueWithDate(string value, DateTime expires) { HttpCookie cookie = new HttpCookie(_key, value); if (GlobalSettings.UseSSL) cookie.Secure = true; //ensure http only, this should only be able to be accessed via the server cookie.HttpOnly = true; cookie.Expires = expires; ResponseCookie = cookie; // original Umbraco code also does this // so we can GetValue() back what we previously set cookie = RequestCookie; if (cookie != null) cookie.Value = value; } public void Clear() { if (RequestCookie != null || ResponseCookie != null) { HttpCookie cookie = new HttpCookie(_key); cookie.Expires = DateTime.Now.AddDays(-1); ResponseCookie = cookie; } } public void Remove() { // beware! will not clear browser's cookie // you probably want to use .Clear() HttpContext.Response.Cookies.Remove(_key); } public HttpCookie RequestCookie { get { return HttpContext.Request.Cookies[_key]; } } public HttpCookie ResponseCookie { get { return HttpContext.Response.Cookies[_key]; } set { // .Set() ensures the uniqueness of cookies in the cookie collection // ie it is the same as .Remove() + .Add() -- .Add() allows duplicates HttpContext.Response.Cookies.Set(value); } } } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using Analyzer = Lucene.Net.Analysis.Analyzer; using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer; using StandardAnalyzer = Lucene.Net.Analysis.Standard.StandardAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using Directory = Lucene.Net.Store.Directory; using FSDirectory = Lucene.Net.Store.FSDirectory; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Index { /// <summary> Tests for the "IndexModifier" class, including accesses from two threads at the /// same time. /// /// </summary> /// <deprecated> /// </deprecated> [TestFixture] public class TestIndexModifier:LuceneTestCase { private int docCount = 0; private Term allDocTerm = new Term("all", "x"); [Test] public virtual void TestIndex() { Directory ramDir = new RAMDirectory(); IndexModifier i = new IndexModifier(ramDir, new StandardAnalyzer(), true); i.AddDocument(GetDoc()); Assert.AreEqual(1, i.DocCount()); i.Flush(); i.AddDocument(GetDoc(), new SimpleAnalyzer()); Assert.AreEqual(2, i.DocCount()); i.Optimize(); Assert.AreEqual(2, i.DocCount()); i.Flush(); i.DeleteDocument(0); Assert.AreEqual(1, i.DocCount()); i.Flush(); Assert.AreEqual(1, i.DocCount()); i.AddDocument(GetDoc()); i.AddDocument(GetDoc()); i.Flush(); // depend on merge policy - Assert.AreEqual(3, i.docCount()); i.DeleteDocuments(allDocTerm); Assert.AreEqual(0, i.DocCount()); i.Optimize(); Assert.AreEqual(0, i.DocCount()); // Lucene defaults: Assert.IsNull(i.GetInfoStream()); Assert.IsTrue(i.GetUseCompoundFile()); Assert.AreEqual(IndexWriter.DISABLE_AUTO_FLUSH, i.GetMaxBufferedDocs()); Assert.AreEqual(10000, i.GetMaxFieldLength()); Assert.AreEqual(10, i.GetMergeFactor()); // test setting properties: i.SetMaxBufferedDocs(100); i.SetMergeFactor(25); i.SetMaxFieldLength(250000); i.AddDocument(GetDoc()); i.SetUseCompoundFile(false); i.Flush(); Assert.AreEqual(100, i.GetMaxBufferedDocs()); Assert.AreEqual(25, i.GetMergeFactor()); Assert.AreEqual(250000, i.GetMaxFieldLength()); Assert.IsFalse(i.GetUseCompoundFile()); // test setting properties when internally the reader is opened: i.DeleteDocuments(allDocTerm); i.SetMaxBufferedDocs(100); i.SetMergeFactor(25); i.SetMaxFieldLength(250000); i.AddDocument(GetDoc()); i.SetUseCompoundFile(false); i.Optimize(); Assert.AreEqual(100, i.GetMaxBufferedDocs()); Assert.AreEqual(25, i.GetMergeFactor()); Assert.AreEqual(250000, i.GetMaxFieldLength()); Assert.IsFalse(i.GetUseCompoundFile()); i.Close(); try { i.DocCount(); Assert.Fail(); } catch (System.SystemException e) { // expected exception } } [Test] public virtual void TestExtendedIndex() { Directory ramDir = new RAMDirectory(); PowerIndex powerIndex = new PowerIndex(this, ramDir, new StandardAnalyzer(), true); powerIndex.AddDocument(GetDoc()); powerIndex.AddDocument(GetDoc()); powerIndex.AddDocument(GetDoc()); powerIndex.AddDocument(GetDoc()); powerIndex.AddDocument(GetDoc()); powerIndex.Flush(); Assert.AreEqual(5, powerIndex.DocFreq(allDocTerm)); powerIndex.Close(); } private Document GetDoc() { Document doc = new Document(); doc.Add(new Field("body", System.Convert.ToString(docCount), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("all", "x", Field.Store.YES, Field.Index.NOT_ANALYZED)); docCount++; return doc; } [Test] public virtual void TestIndexWithThreads() { TestIndexInternal(0); TestIndexInternal(10); TestIndexInternal(50); } private void TestIndexInternal(int maxWait) { bool create = true; //Directory rd = new RAMDirectory(); // work on disk to make sure potential lock problems are tested: System.String tempDir = System.IO.Path.GetTempPath(); if (tempDir == null) throw new System.IO.IOException("java.io.tmpdir undefined, cannot run test"); System.IO.FileInfo indexDir = new System.IO.FileInfo(System.IO.Path.Combine(tempDir, "lucenetestindex")); Directory rd = FSDirectory.Open(indexDir); IndexThread.id = 0; IndexThread.idStack.Clear(); IndexModifier index = new IndexModifier(rd, new StandardAnalyzer(), create); IndexThread thread1 = new IndexThread(index, maxWait, 1); thread1.Start(); IndexThread thread2 = new IndexThread(index, maxWait, 2); thread2.Start(); while (thread1.IsAlive || thread2.IsAlive) { System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 100)); } index.Optimize(); int added = thread1.added + thread2.added; int deleted = thread1.deleted + thread2.deleted; Assert.AreEqual(added - deleted, index.DocCount()); index.Close(); try { index.Close(); Assert.Fail(); } catch (System.SystemException e) { // expected exception } RmDir(indexDir); } private void RmDir(System.IO.FileInfo dir) { System.IO.FileInfo[] files = SupportClass.FileSupport.GetFiles(dir); for (int i = 0; i < files.Length; i++) { bool tmpBool; if (System.IO.File.Exists(files[i].FullName)) { System.IO.File.Delete(files[i].FullName); tmpBool = true; } else if (System.IO.Directory.Exists(files[i].FullName)) { System.IO.Directory.Delete(files[i].FullName); tmpBool = true; } else tmpBool = false; bool generatedAux = tmpBool; } bool tmpBool2; if (System.IO.File.Exists(dir.FullName)) { System.IO.File.Delete(dir.FullName); tmpBool2 = true; } else if (System.IO.Directory.Exists(dir.FullName)) { System.IO.Directory.Delete(dir.FullName); tmpBool2 = true; } else tmpBool2 = false; bool generatedAux2 = tmpBool2; } private class PowerIndex:IndexModifier { private void InitBlock(TestIndexModifier enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestIndexModifier enclosingInstance; public TestIndexModifier Enclosing_Instance { get { return enclosingInstance; } } public PowerIndex(TestIndexModifier enclosingInstance, Directory dir, Analyzer analyzer, bool create):base(dir, analyzer, create) { InitBlock(enclosingInstance); } public virtual int DocFreq(Term term) { lock (directory) { AssureOpen(); CreateIndexReader(); return indexReader.DocFreq(term); } } } } class IndexThread:SupportClass.ThreadClass { private const int TEST_SECONDS = 3; // how many seconds to run each test internal static int id = 0; internal static System.Collections.ArrayList idStack = new System.Collections.ArrayList(); internal int added = 0; internal int deleted = 0; private int maxWait = 10; private IndexModifier index; private int threadNumber; private System.Random random; internal IndexThread(IndexModifier index, int maxWait, int threadNumber) { this.index = index; this.maxWait = maxWait; this.threadNumber = threadNumber; // TODO: test case is not reproducible despite pseudo-random numbers: random = new System.Random((System.Int32) (101 + threadNumber)); // constant seed for better reproducability } override public void Run() { long endTime = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000 * TEST_SECONDS; try { while ((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) < endTime) { int rand = random.Next(101); if (rand < 5) { index.Optimize(); } else if (rand < 60) { Document doc = GetDocument(); index.AddDocument(doc); idStack.Add(doc.Get("id")); added++; } else { // we just delete the last document added and remove it // from the id stack so that it won't be removed twice: System.String delId = null; try { delId = idStack[idStack.Count - 1] as System.String; idStack.RemoveAt(idStack.Count - 1); } catch (System.ArgumentOutOfRangeException e) { continue; } Term delTerm = new Term("id", System.Int32.Parse(delId).ToString()); int delCount = index.DeleteDocuments(delTerm); if (delCount != 1) { throw new System.SystemException("Internal error: " + threadNumber + " deleted " + delCount + " documents, term=" + delTerm); } deleted++; } if (maxWait > 0) { rand = random.Next(maxWait); //System.out.println("waiting " + rand + "ms"); try { System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * rand)); } catch (System.Threading.ThreadInterruptedException ie) { SupportClass.ThreadClass.Current().Interrupt(); throw new System.SystemException("", ie); } } } } catch (System.IO.IOException e) { throw new System.SystemException("", e); } } private Document GetDocument() { Document doc = new Document(); lock (GetType()) { doc.Add(new Field("id", System.Convert.ToString(id), Field.Store.YES, Field.Index.NOT_ANALYZED)); id++; } // add random stuff: doc.Add(new Field("content", System.Convert.ToString(random.Next(1000)), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("content", System.Convert.ToString(random.Next(1000)), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("all", "x", Field.Store.YES, Field.Index.ANALYZED)); return doc; } } }
//Copyright 2017 Sorin Miroiu //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.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Game { public partial class Game : Form { public Game() { InitializeComponent(); Player.SendToBack(); ground_02 = player_02.Top; ground = Player.Top; //For resolution x_ax = Screen.PrimaryScreen.Bounds.Width; y_ax = Screen.PrimaryScreen.Bounds.Height; limit_right = x_ax; set_resolution(x_ax_original, x_ax); x_ax_original = numar1; x_ax = numar2; set_resolution(y_ax_original, y_ax); y_ax_original = numar1; y_ax = numar2; if (x_ax != 1 || y_ax != 1) if_resolution_differs_set_resolution(); } //initialization Boolean left, right, jump; int ground; int velocity = 5; int G = 25; int Force; int move = 3; int platform_up = 200, platform_down = 650; int ticket_inventory = 0; bool finish = false; int miscare = 3, lovit = 50, inchide = 1000; // deplasare inamic int dieonce = 0; int enemy1left = 1000, enemy1right = 1300; int enemy2left = 1000, enemy2right = 1300; int enemy3left = 100, enemy3right = 300; int enemy4left = 100, enemy4right = 300; int enemy_hittime; int lovit_02=50, dieonce_02=0; const int capacity = 10000; PictureBox[] bullet = new PictureBox[capacity]; int bullet_number = 0; bool bullet_active = false; int direction = 1; int[] bullet_direction = new int[capacity]; //Resolution int x_ax, y_ax; int x_ax_original = 1366; int y_ax_original = 768; int numar1, numar2; int limit_right; //Animations Boolean walkleft; Boolean walkright; #region PLAYER 2 bool player_02_exist = false; bool left_02, right_02, jump_02; int Force_02, G_02 = 25; int ground_02; PictureBox[] bullet_02 = new PictureBox[capacity]; int bullet_number_02 = 0; bool bullet_active_02 = false; int direction_02 = 0; int[] bullet_direction_02 = new int[capacity]; #endregion void player_limits(PictureBox person) { if (person.Right > limit_right) person.Left = limit_right - person.Width; if (person.Left < 0) person.Left = 0; } void set_resolution(int x, int y) { int contor, a, b; contor = x; a = x; b = y; while (contor != 1) { while (a != b) if (a > b) a -= b; else b -= a; if (a > 1) { x /= a; y /= a; } contor = a; a = x; b = y; } numar1 = x; numar2 = y; } void if_resolution_differs_set_resolution() { G = x_ax * G / x_ax_original; Player.Height = y_ax * Player.Height / y_ax_original; Player.Width = x_ax * Player.Width / x_ax_original; Player.Top = y_ax * Player.Top / y_ax_original; Player.Left = x_ax * Player.Left / x_ax_original; Player.SizeMode = PictureBoxSizeMode.StretchImage; ground = Player.Top; block1.Height = y_ax * block1.Height / y_ax_original; block1.Width = x_ax * block1.Width / x_ax_original; block1.Top = y_ax * block1.Top / y_ax_original; block1.Left = x_ax * block1.Left / x_ax_original; block1.SizeMode = PictureBoxSizeMode.StretchImage; block2.Height = y_ax * block2.Height / y_ax_original; block2.Width = x_ax * block2.Width / x_ax_original; block2.Top = y_ax * block2.Top / y_ax_original; block2.Left = x_ax * block2.Left / x_ax_original; block2.SizeMode = PictureBoxSizeMode.StretchImage; block3.Height = y_ax * block3.Height / y_ax_original; block3.Width = x_ax * block3.Width / x_ax_original; block3.Top = y_ax * block3.Top / y_ax_original; block3.Left = x_ax * block3.Left / x_ax_original; block3.SizeMode = PictureBoxSizeMode.StretchImage; block4.Height = y_ax * block4.Height / y_ax_original; block4.Width = x_ax * block4.Width / x_ax_original; block4.Top = y_ax * block4.Top / y_ax_original; block4.Left = x_ax * block4.Left / x_ax_original; block4.SizeMode = PictureBoxSizeMode.StretchImage; platform.Height = y_ax * platform.Height / y_ax_original; platform.Width = x_ax * platform.Width / x_ax_original; platform.Top = y_ax * platform.Top / y_ax_original; platform.Left = x_ax * platform.Left / x_ax_original; platform.SizeMode = PictureBoxSizeMode.StretchImage; platform_up = y_ax * platform_up / y_ax_original; platform_down = y_ax * platform_down / y_ax_original; Life.Height = y_ax * Life.Height / y_ax_original; Life.Width = x_ax * Life.Width / x_ax_original; Life.Top = y_ax * Life.Top / y_ax_original; Life.Left = x_ax * Life.Left / x_ax_original; //inventory_1.Height = y_ax * inventory_1.Height / y_ax_original; //inventory_1.Width = x_ax * inventory_1.Width / x_ax_original; //inventory_1.Top = y_ax * inventory_1.Top / y_ax_original; //inventory_1.Left = x_ax * inventory_1.Left / x_ax_original; //inventory_1.SizeMode = PictureBoxSizeMode.StretchImage; //inventory_2.Height = y_ax * inventory_2.Height / y_ax_original; //inventory_2.Width = x_ax * inventory_2.Width / x_ax_original; //inventory_2.Top = y_ax * inventory_2.Top / y_ax_original; //inventory_2.Left = x_ax * inventory_2.Left / x_ax_original; //inventory_2.SizeMode = PictureBoxSizeMode.StretchImage; //inventory_3.Height = y_ax * inventory_3.Height / y_ax_original; //inventory_3.Width = x_ax * inventory_3.Width / x_ax_original; //inventory_3.Top = y_ax * inventory_3.Top / y_ax_original; //inventory_3.Left = x_ax * inventory_3.Left / x_ax_original; //inventory_3.SizeMode = PictureBoxSizeMode.StretchImage; //inventory_4.Height = y_ax * inventory_4.Height / y_ax_original; //inventory_4.Width = x_ax * inventory_4.Width / x_ax_original; //inventory_4.Top = y_ax * inventory_4.Top / y_ax_original; //inventory_4.Left = x_ax * inventory_4.Left / x_ax_original; //inventory_4.SizeMode = PictureBoxSizeMode.StretchImage; //food_1.Height = y_ax * food_1.Height / y_ax_original; //food_1.Width = x_ax * food_1.Width / x_ax_original; //food_1.Top = y_ax * food_1.Top / y_ax_original; //food_1.Left = x_ax * food_1.Left / x_ax_original; //food_1.SizeMode = PictureBoxSizeMode.StretchImage; //food_2.Height = y_ax * food_2.Height / y_ax_original; //food_2.Width = x_ax * food_2.Width / x_ax_original; //food_2.Top = y_ax * food_2.Top / y_ax_original; //food_2.Left = x_ax * food_2.Left / x_ax_original; //food_2.SizeMode = PictureBoxSizeMode.StretchImage; //food_3.Height = y_ax * food_3.Height / y_ax_original; //food_3.Width = x_ax * food_3.Width / x_ax_original; //food_3.Top = y_ax * food_3.Top / y_ax_original; //food_3.Left = x_ax * food_3.Left / x_ax_original; //food_3.SizeMode = PictureBoxSizeMode.StretchImage; //food_4.Height = y_ax * food_4.Height / y_ax_original; //food_4.Width = x_ax * food_4.Width / x_ax_original; //food_4.Top = y_ax * food_4.Top / y_ax_original; //food_4.Left = x_ax * food_4.Left / x_ax_original; //food_4.SizeMode = PictureBoxSizeMode.StretchImage; //solid_ground.Height = y_ax * solid_ground.Height / y_ax_original; //solid_ground.Width = x_ax * solid_ground.Width / x_ax_original; //solid_ground.Top = y_ax * solid_ground.Top / y_ax_original; //solid_ground.Left = x_ax * solid_ground.Left / x_ax_original; //solid_ground.SizeMode = PictureBoxSizeMode.StretchImage; } void if_resolution_differs_add_set_resolution_for_player_02() { G_02 = G; player_02.Height = y_ax * player_02.Height / y_ax_original; player_02.Width = x_ax * player_02.Width / x_ax_original; player_02.Top = y_ax * player_02.Top / y_ax_original; player_02.Left = x_ax * player_02.Left / x_ax_original; player_02.SizeMode = PictureBoxSizeMode.StretchImage; //ground_02 = solid_ground.Top - player_02.Height; //Lifebar_player_02.Height = y_ax * Lifebar_player_02.Height / y_ax_original; //Lifebar_player_02.Width = x_ax * Lifebar_player_02.Width / x_ax_original; //Lifebar_player_02.Top = y_ax * Lifebar_player_02.Top / y_ax_original; //Lifebar_player_02.Left = x_ax * Lifebar_player_02.Left / x_ax_original; //inventory_01_player_02.Height = y_ax * inventory_01_player_02.Height / y_ax_original; //inventory_01_player_02.Width = x_ax * inventory_01_player_02.Width / x_ax_original; //inventory_01_player_02.Top = y_ax * inventory_01_player_02.Top / y_ax_original; //inventory_01_player_02.Left = x_ax * inventory_01_player_02.Left / x_ax_original; //inventory_01_player_02.SizeMode = PictureBoxSizeMode.StretchImage; //inventory_02_player_02.Height = y_ax * inventory_02_player_02.Height / y_ax_original; //inventory_02_player_02.Width = x_ax * inventory_02_player_02.Width / x_ax_original; //inventory_02_player_02.Top = y_ax * inventory_02_player_02.Top / y_ax_original; //inventory_02_player_02.Left = x_ax * inventory_02_player_02.Left / x_ax_original; //inventory_02_player_02.SizeMode = PictureBoxSizeMode.StretchImage; //inventory_03_player_02.Height = y_ax * inventory_03_player_02.Height / y_ax_original; //inventory_03_player_02.Width = x_ax * inventory_03_player_02.Width / x_ax_original; //inventory_03_player_02.Top = y_ax * inventory_03_player_02.Top / y_ax_original; //inventory_03_player_02.Left = x_ax * inventory_03_player_02.Left / x_ax_original; //inventory_03_player_02.SizeMode = PictureBoxSizeMode.StretchImage; //inventory_04_player_02.Height = y_ax * inventory_04_player_02.Height / y_ax_original; //inventory_04_player_02.Width = x_ax * inventory_04_player_02.Width / x_ax_original; //inventory_04_player_02.Top = y_ax * inventory_04_player_02.Top / y_ax_original; //inventory_04_player_02.Left = x_ax * inventory_04_player_02.Left / x_ax_original; //inventory_04_player_02.SizeMode = PictureBoxSizeMode.StretchImage; player_02.Left = x_ax * player_02.Left / x_ax_original; player_02.Height = y_ax * player_02.Height / y_ax_original; } private void timer1_Tick_1(object sender, EventArgs e) { #region PLAYER 1 left_right_movement_player_1(); if (bullet_active == true) bullet_movement_for_player_1(enemy1); if (bullet_active == true) bullet_movement_for_player_1(enemy2); if (bullet_active == true) bullet_movement_for_player_1(enemy3); if (bullet_active == true) bullet_movement_for_player_1(enemy4); player_limits(Player); side_bottom_collision(block1); side_bottom_collision(block2); side_bottom_collision(block3); side_bottom_collision(block4); player_1_jumping(); top_collision(block1); top_collision(block2); top_collision(block3); top_collision(block4); platform_movement(platform, platform_up, platform_down); enemy_movement(enemy1, enemy1left, enemy1right); enemy_movement(enemy2, enemy2left, enemy2right); enemy_movement(enemy3, enemy3left, enemy3right); enemy_movement(enemy4, enemy4left, enemy4right); enemy_collision_player1(enemy1); enemy_collision_player1(enemy2); enemy_collision_player1(enemy3); enemy_collision_player1(enemy4); collect_item_player1(fly1); collect_item_player1(fly2); collect_item_player1(fly3); collect_item_player1(fly4); #endregion #region PLAYER 2 if (player_02_exist == true) { right_left_move_player_02(); if (bullet_active_02 == true) bullet_moving_player_02(enemy1); if (bullet_active_02 == true) bullet_moving_player_02(enemy2); if (bullet_active_02 == true) bullet_moving_player_02(enemy3); if (bullet_active_02 == true) bullet_moving_player_02(enemy4); player_limits(player_02); side_bottom_collision_player_02(block1); side_bottom_collision_player_02(block2); side_bottom_collision_player_02(block3); side_bottom_collision_player_02(block4); jumping_player_02(); top_collision_player_02(block1); top_collision_player_02(block2); top_collision_player_02(block3); top_collision_player_02(block4); //player_02 platform collision side_bottom_collision_player_02(platform); top_collision_player_02(platform); enemy_collision_player_02(enemy1); enemy_collision_player_02(enemy2); enemy_collision_player_02(enemy3); enemy_collision_player_02(enemy4); collect_item_player_02(fly1); collect_item_player_02(fly2); collect_item_player_02(fly3); collect_item_player_02(fly4); } #endregion } private void bullet_movement_for_player_1(PictureBox enemy) { int k = 0; for (int capacity = 1; capacity <= bullet_number; capacity++) { if (bullet_direction[capacity] == 0) { if (bullet[capacity].Bounds.IntersectsWith(block1.Bounds)) bullet[capacity].Dispose(); //bullet[i].Left = 3000; else if (bullet[capacity].Bounds.IntersectsWith(platform.Bounds)) bullet[capacity].Dispose();//bullet[i].Left = 3000; } else if (bullet[capacity].Left < 2000) { bullet[capacity].Left += 15; k++; } if (bullet_direction[capacity] == 1) { if (bullet[capacity].Bounds.IntersectsWith(block1.Bounds)) bullet[capacity].Dispose();//bullet[i].Left = -200; else if (bullet[capacity].Bounds.IntersectsWith(platform.Bounds)) bullet[capacity].Dispose(); //bullet[i].Left = -200; } else if (bullet[capacity].Left > -100) { bullet[capacity].Left -= 15; k++; } if (player_02_exist == true) { if (bullet[capacity].Bounds.IntersectsWith(player_02.Bounds)) { bullet[capacity].Left = 3000; if (Lifebar_player_02.Value > 30) { Lifebar_player_02.Value -= 30; } else { Lifebar_player_02.Value = 0; timer1.Stop(); MessageBox.Show("P1 castiga !"); Cursor.Show(); this.Close(); } } } if(bullet[capacity].Bounds.IntersectsWith(enemy.Bounds)) { enemy.Dispose(); } } if (k == 0) bullet_active = false; } private void platform_movement(PictureBox floating, int up, int down) { if (floating.Top <= up) move = 3; if (floating.Top >= down) move = -3; floating.Top += move; side_bottom_collision(platform); top_collision(platform); } private void player_1_jumping() { if (jump == true) { //falling(if player has jumped before) Player.Top -= Force; Force -= 1; } if (Player.Top >= ground) { Player.Top = ground; jump = false; } else Player.Top += 5; } private void left_right_movement_player_1() { if (left == true) { Player.Left -= velocity; walkleft = true; } if (right == true) { Player.Left += velocity; walkright = true; } } private void side_bottom_collision(PictureBox block) { #region collision_01 #region Head/Bottom of an object collision int k = 0;// reset, if jumped at block.bottom it resets in left/right if (Player.Left + Player.Width - 5 > block.Left) // blocked. bottom - limita if (Player.Left + Player.Width + 5 < block.Left + block.Width + Player.Width) if (Player.Top <= block.Bottom) // or k = 1; if (Player.Top > block.Top) { k = 1; // or if (player.Top <= block.Bottom+10); jump = false; Force = 0; jump = true; } #endregion //k = 1; #region side collision if (Player.Right > block.Left && Player.Left < block.Right - Player.Width / 2 && Player.Top < block.Bottom && Player.Bottom > block.Top + 25) if (k == 0) { right = false; Player.Left = block.Left - Player.Width; } if (Player.Left < block.Right && Player.Right > block.Left + Player.Width / 2 && Player.Top < block.Bottom && Player.Bottom > block.Top + 25) if (k == 0) { left = false; Player.Left = block.Right; } #endregion k = 0; //#region simple fall //if (!(Player.Left + Player.Width > block.Left // && Player.Left + Player.Width < block.Left + block.Width + Player.Width) && // Player.Top + Player.Height >= block.Top && Player.Top < block.Top) //{ // jump = false; //} //#endregion //#region Stop falling at bottom //if (Player.Top + Player.Height >= screen.Height) //{ // Player.Top = screen.Height - Player.Height; //Stop falling at bottom // jump = false; //} //else //{ // Player.Top += 5; //Falling //} //#endregion #endregion } private void top_collision(PictureBox block) { if (Player.Left + Player.Width - 5 > block.Left && Player.Left + Player.Width + 5 < block.Left + block.Width + Player.Width && Player.Top + Player.Height >= block.Top && Player.Top < block.Top) { Player.Top = block.Top - Player.Height; jump = false; } } private void Game_KeyUp(object sender, KeyEventArgs e) { #region PLAYER1 if (e.KeyCode == Keys.A) { left = false; //moves left Player.Image = Properties.Resources.standing_left; } if (e.KeyCode == Keys.D) { right = false; //moves right Player.Image = Properties.Resources.standing_right; } if (e.KeyCode == Keys.W) { if (direction == 0) { Player.Image = Properties.Resources.standing_left; } if (direction == 1) { Player.Image = Properties.Resources.standing_right; } } if (e.KeyCode == Keys.Space) //shooting { if (direction == 0) { Player.Image = Properties.Resources.standing_left; } if (direction == 1) { Player.Image = Properties.Resources.standing_right; } } if (e.KeyCode == Keys.S) //crouch { if (direction == 0) { Player.Image = Properties.Resources.standing_left; } if (direction == 1) { Player.Image = Properties.Resources.standing_right; } } #endregion #region PLAYER2 if (e.KeyCode == Keys.Right) { right_02 = false; } if (e.KeyCode == Keys.Left) { left_02 = false; } #endregion } private void Game_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { this.Close(); } //Esc-> to exit #region Movement PLAYER 1 if (e.KeyCode == Keys.A) //moves left { Player.Image = Properties.Resources.walk_left; direction = 0; walkleft = true; left = true; } if (e.KeyCode == Keys.D) //moves right { Player.Image = Properties.Resources.walk_right; direction = 1; walkright = true; right = true; } if(e.KeyCode==Keys.S) //crouch { if(direction==0) { Player.Image = Properties.Resources.crouchleft; } if(direction == 1) { Player.Image = Properties.Resources.crouchright; } } if (jump != true) { if (e.KeyCode == Keys.W) { jump = true; Force = G; if(direction==0) { Player.Image = Properties.Resources.jumpleft; } if(direction == 1) { Player.Image = Properties.Resources.jumpright; } } } if (e.KeyCode == Keys.Space) //shooting { //animation--> if (direction == 0) { Player.Image = Properties.Resources.standshootleft; } if (direction == 1) { Player.Image = Properties.Resources.standshootright; } if (walkleft==true && direction == 0) { Player.Image = Properties.Resources.walk_shootleft; } if (walkright==true && direction == 1) { Player.Image = Properties.Resources.walk_shoot_right; } //-->'till here bullet_number++; bullet[bullet_number] = new PictureBox(); bullet[bullet_number].Top = Player.Top + Player.Height / 3; bullet[bullet_number].Left = Player.Left; bullet[bullet_number].Height = 80;//original =14 bullet[bullet_number].Width = 38;//original=20 bullet[bullet_number].Image = Properties.Resources.bullet; bullet[bullet_number].SizeMode = PictureBoxSizeMode.AutoSize; Controls.Add(bullet[bullet_number]); bullet[bullet_number].BringToFront(); bullet[bullet_number].Show(); bullet_active = true; bullet_direction[bullet_number] = new int(); bullet_direction[bullet_number] = direction; //Resolution changed if (x_ax != 1 || y_ax != 1) { bullet[bullet_number].Height = y_ax * bullet[bullet_number].Height / y_ax_original; bullet[bullet_number].Width = x_ax * bullet[bullet_number].Width / x_ax_original; bullet[bullet_number].Top = Player.Top + Player.Height / 3; bullet[bullet_number].Left = Player.Left; bullet[bullet_number].SizeMode = PictureBoxSizeMode.AutoSize; } } #endregion //player_02 if (e.KeyCode == Keys.D2) { if (player_02_exist == false) { //add_player_02(); player_02_exist = true; } if (player_02_exist == true) { Controls.Add(player_02); player_02.Show(); player_02.BringToFront(); Controls.Add(Lifebar_player_02); Lifebar_player_02.Show(); Lifebar_player_02.BringToFront(); if (e.KeyCode == Keys.Right) { right_02 = true; direction_02 = 1; } if (e.KeyCode == Keys.Left) { left_02 = true; direction_02 = 0; } if (e.KeyCode == Keys.Up) // SARITURA if (jump_02 == false) { jump_02 = true; Force_02 = G_02; } if (e.KeyCode == Keys.NumPad5) { bullet_number_02++; bullet_02[bullet_number_02] = new PictureBox(); bullet_02[bullet_number_02].Top = player_02.Top + player_02.Height / 3; bullet_02[bullet_number_02].Left = player_02.Left; bullet_02[bullet_number_02].Height = 80; bullet_02[bullet_number_02].Width = 38; bullet_02[bullet_number_02].Image = Properties.Resources.bullet; bullet_02[bullet_number].SizeMode = PictureBoxSizeMode.AutoSize; Controls.Add(bullet_02[bullet_number_02]); bullet[bullet_number].BringToFront(); bullet[bullet_number].Show(); bullet_active_02 = true; bullet_direction_02[bullet_number_02] = new int(); bullet_direction_02[bullet_number_02] = direction_02; //Resolution changed if (x_ax != 1 || y_ax != 1) { bullet_02[bullet_number_02].Height = y_ax * bullet_02[bullet_number_02].Height / y_ax_original; bullet_02[bullet_number_02].Width = x_ax * bullet_02[bullet_number_02].Width / x_ax_original; bullet_02[bullet_number_02].Top = player_02.Top + player_02.Height / 3; bullet_02[bullet_number_02].Left = player_02.Left; bullet_02[bullet_number_02].SizeMode = PictureBoxSizeMode.StretchImage; } } } } void add_player_02() //ADD P2 IMAGES { //player_02.Show(); //player_02 = new PictureBox(); //player_02.Height = 75; //player_02.Width = 69; //player_02.Top = 607; //376; //player_02.Left = 1269; //player_02.Image = Properties.Resources.p2standright; //to be implemented //player_02.SizeMode = PictureBoxSizeMode.StretchImage; //Controls.Add(player_02); //player_02.Show(); //player_02.BringToFront(); //ground_02 = solid_ground.Top - player_02.Height; //int solid_ground; //solid_ground.Location = new Point(1269, 604); //ground_02 = new Point(1269, 604); player_02.SendToBack(); // lifebar //Lifebar_player_02 = new ProgressBar(); //Lifebar_player_02.Height = 30; //Lifebar_player_02.Width = 280; //Lifebar_player_02.Top = 13; //Lifebar_player_02.Left = 190; //Lifebar_player_02.Value = 100; //Controls.Add(Lifebar_player_02); //inventory creation //inventory_01_player_02 = new PictureBox(); //inventory_02_player_02 = new PictureBox(); //inventory_03_player_02 = new PictureBox(); //inventory_04_player_02 = new PictureBox(); //inventory_01_player_02.Top = 13; //inventory_01_player_02.Left = 13; //inventory_01_player_02.Height = 32; //inventory_01_player_02.Width = 32; //inventory_01_player_02.Image = Properties.Resources.inventory_slot; //Controls.Add(inventory_01_player_02); //inventory_02_player_02.Top = 13; //inventory_02_player_02.Left = 51; //inventory_02_player_02.Height = 32; //inventory_02_player_02.Width = 32; ////inventory_02_player_02.Image = Properties.Resources.inventory_slot; //Controls.Add(inventory_02_player_02); //inventory_03_player_02.Top = 13; //inventory_03_player_02.Left = 89; //inventory_03_player_02.Height = 32; //inventory_03_player_02.Width = 32; //inventory_03_player_02.Image = Properties.Resources.inventory_slot; //Controls.Add(inventory_03_player_02); //inventory_04_player_02.Top = 13; //inventory_04_player_02.Left = 127; //inventory_04_player_02.Height = 32; //inventory_04_player_02.Width = 32; //inventory_04_player_02.Image = Properties.Resources.inventory_slot; //Controls.Add(inventory_04_player_02); Player.Show(); player_02.Show(); if (x_ax != 1 || y_ax != 1) if_resolution_differs_add_set_resolution_for_player_02(); } } private void right_left_move_player_02() { if (right_02 == true) //move right { player_02.Left += velocity; //player_02.Image = Properties.Resources.player2_right; } else if (left_02 == true) //move left { player_02.Left -= velocity; //player_02.Image = Properties.Resources.player2_left; } } private void jumping_player_02() { if (jump_02 == true) { player_02.Top -= Force_02; Force_02 -= 1; } if (player_02.Top >= ground_02) { player_02.Top = ground_02; jump_02 = false; } else player_02.Top += 5; } private void side_bottom_collision_player_02(PictureBox block) { int k = 0;// resetare, daca sari la block.bottom atunci se reseteaza in stanga / dreapta if (player_02.Left + player_02.Width - 5 > block.Left) // blocked. bottom - limita if (player_02.Left + player_02.Width + 5 < block.Left + block.Width + player_02.Width) if (player_02.Top <= block.Bottom) // or k = 1; if (player_02.Top > block.Top) { k = 1; // or if (player.Top <= block.Bottom+10); //player_02.Image = Image.FromFile("chowder_small.png"); jump_02 = false; Force_02 = 0; jump_02 = true; } if (player_02.Right > block.Left) // blocked. left - limita if (player_02.Left < block.Right - player_02.Width / 2) if (player_02.Bottom > block.Top + 20) // +20 pentru platforma (sa nu se reseteze in stanga) if (player_02.Top < block.Bottom) if (k == 0) { right_02 = false; player_02.Left = block.Left - player_02.Width; } if (player_02.Left < block.Right) // blocked. right - limita if (player_02.Right > block.Left + player_02.Width / 2) if (player_02.Bottom > block.Top + 20) // +20 pentru platforma (sa nu se reseteze in dreapta) if (player_02.Top < block.Bottom) if (k == 0) { left_02 = false; player_02.Left = block.Right; } k = 0; //if (!(player.Left + player.Width > block.Left && // player.Left + player.Width < block.Left + block.Width + player.Width) && // player.Top + player.Height >= block.Top && player.Top < block.Top) // jump = true; } private void top_collision_player_02(PictureBox block) { if (player_02.Left + player_02.Width - 5 > block.Left) // blocked. top - limita if (player_02.Left + player_02.Width + 5 < block.Left + block.Width + player_02.Width) if (player_02.Top + player_02.Height >= block.Top) if (player_02.Top < block.Top) { player_02.Top = block.Top - player_02.Height; // block.top = block.location.Y jump_02 = false; // Force = 0; } } private void bullet_moving_player_02(PictureBox enemy) { int k = 0; for (int capacity = 1; capacity <= bullet_number; capacity++) { if (bullet_direction_02[capacity] == 0) { if (bullet_02[capacity].Bounds.IntersectsWith(block1.Bounds)) bullet_02[capacity].Dispose(); //bullet[i].Left = 3000; else if (bullet_02[capacity].Bounds.IntersectsWith(platform.Bounds)) bullet_02[capacity].Dispose();//bullet[i].Left = 3000; } else if (bullet_02[capacity].Left < 2000) { bullet_02[capacity].Left += 15; k++; } if (bullet_direction_02[capacity] == 1) { if (bullet_02[capacity].Bounds.IntersectsWith(block1.Bounds)) bullet_02[capacity].Dispose();//bullet[i].Left = -200; else if (bullet_02[capacity].Bounds.IntersectsWith(platform.Bounds)) bullet_02[capacity].Dispose(); //bullet[i].Left = -200; } else if (bullet_02[capacity].Left > -100) { bullet_02[capacity].Left -= 15; k++; } else if (bullet_02[capacity].Bounds.IntersectsWith(Player.Bounds)) { bullet_02[capacity].Left = -200; if (Life.Value > 30) { Life.Value -= 30; } else { Life.Value = 0; timer1.Stop(); MessageBox.Show("P2 castiga !"); Cursor.Show(); this.Close(); } } if (bullet_02[capacity].Bounds.IntersectsWith(enemy.Bounds)) { enemy.Dispose(); } } if (k == 0) bullet_active_02 = false; } private void collect_item_player1(PictureBox item) { if (Player.Bounds.IntersectsWith(item.Bounds)) ticket_inventory++; if (ticket_inventory == 1) { //slot1.Image = Properties.Resources.fly; //sau * = item.Image; slot1.Image = item.Image; fly1.Dispose(); if (Life.Value + 20 < 100) Life.Value += 20; //life increases else Life.Value = 100; } else if (ticket_inventory == 2) { slot2.Image = Properties.Resources.fly; fly2.Dispose(); if (Life.Value + 20 < 100) Life.Value += 20; else Life.Value = 100; } else if (ticket_inventory == 3) { slot3.Image = Properties.Resources.fly; fly3.Dispose(); if (Life.Value + 20 < 100) Life.Value += 20; else Life.Value = 100; } else if (ticket_inventory == 4) { slot4.Image = Properties.Resources.fly; fly4.Dispose(); if (Life.Value + 20 < 100) Life.Value += 20; else Life.Value = 100; } } private void collect_item_player_02(PictureBox item) { if (player_02.Bounds.IntersectsWith(item.Bounds)) ticket_inventory++; if (ticket_inventory == 1) { slot5.Image = Properties.Resources.fly; //sau * = item.Image; fly1.Dispose(); if (Lifebar_player_02.Value + 20 < 100) Lifebar_player_02.Value += 20; //life increases else Lifebar_player_02.Value = 100; } else if (ticket_inventory == 2) { slot6.Image = Properties.Resources.fly; //sau * = item.Image; fly2.Dispose(); if (Lifebar_player_02.Value + 20 < 100) Lifebar_player_02.Value += 20; //life increases else Lifebar_player_02.Value = 100; } else if (ticket_inventory == 3) { slot7.Image = Properties.Resources.fly; //sau * = item.Image; fly3.Dispose(); if (Lifebar_player_02.Value + 20 < 100) Lifebar_player_02.Value += 20; //life increases else Lifebar_player_02.Value = 100; } else if (ticket_inventory == 4) { slot8.Image = Properties.Resources.fly; //sau * = item.Image; fly4.Dispose(); if (Lifebar_player_02.Value + 20 < 100) Lifebar_player_02.Value += 20; //life increases else Lifebar_player_02.Value = 100; } } private void enemy_movement(PictureBox enemy, int lft, int rgt) { if (enemy.Left <= lft) miscare = 3; if (enemy.Right >= rgt) miscare = -3; enemy.Left += miscare; if (miscare == 3) enemy.Image = Properties.Resources.enemyright; if (miscare == -3) enemy.Image = Properties.Resources.enemyleft; } private void enemy_collision_player1(PictureBox enemy) { if (Player.Bounds.IntersectsWith(enemy.Bounds)) { enemy_hittime = 1; if (lovit > 100) { lovit = 0; if (Life.Value - 25 > 0) { Life.Value -= 25; } else { Life.Value = 0; jump = true; Force = G; ground += 2000; inchide = 150; dieonce++; if (dieonce == 1 && direction == 0) { Player.Image = Properties.Resources.faintleft; } else if (dieonce == 1 && direction == 1) { Player.Image = Properties.Resources.faintright; } if (dieonce == 1) MessageBox.Show("Player 1 a pierdut"); Cursor.Show(); this.Close(); } } } if (enemy_hittime != 0) enemy_hittime++; if (enemy_hittime > 200) { enemy_hittime = 0; } if (lovit < 210) lovit++; if (inchide <= lovit) Application.Exit(); } private void enemy_collision_player_02(PictureBox enemy) { if (player_02.Bounds.IntersectsWith(enemy.Bounds)) { if (lovit_02 > 100) { lovit_02 = 0; if (Lifebar_player_02.Value - 25 > 0) { Lifebar_player_02.Value -= 25; } else { Lifebar_player_02.Value = 0; jump_02 = true; Force_02 = G_02; ground_02 += 2000; dieonce_02++; if (dieonce_02 == 1) MessageBox.Show("Player 2 a pierdut"); Cursor.Show(); this.Close(); } } } if (enemy_hittime != 0) enemy_hittime++; if (enemy_hittime > 200) { enemy_hittime = 0; } if (lovit < 210) lovit++; if (inchide <= lovit) Application.Exit(); } private void Level_finish() { //TODO } private void Game_Load(object sender, EventArgs e) { } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System.Threading.Tasks; using System.Windows.Input; using Microsoft.PythonTools; using Microsoft.PythonTools.Editor.Core; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.Text; using TestUtilities; using TestUtilities.Mocks; using TestUtilities.Python; namespace PythonToolsTests { [TestClass] public class CommentBlockTests { [TestInitialize] public void TestInitialize() => TestEnvironmentImpl.TestInitialize(); [TestCleanup] public void TestCleanup() => TestEnvironmentImpl.TestCleanup(); [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestCommentCurrentLine() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"print 'hello' print 'goodbye' "); editorTestToolset.UIThread.Invoke(() => { view.Caret.MoveTo(view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(0).Start); view.CommentOrUncommentBlock(true); }); Assert.AreEqual(@"#print 'hello' print 'goodbye' ", view.GetText()); editorTestToolset.UIThread.Invoke(() => { view.Caret.MoveTo(view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(1).Start); view.CommentOrUncommentBlock(true); }); Assert.AreEqual(@"#print 'hello' #print 'goodbye' ", view.GetText()); } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestUnCommentCurrentLine() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"#print 'hello' #print 'goodbye'"); editorTestToolset.UIThread.Invoke(() => { view.Caret.MoveTo(view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(0).Start); view.CommentOrUncommentBlock(false); }); Assert.AreEqual(@"print 'hello' #print 'goodbye'", view.GetText()); editorTestToolset.UIThread.Invoke(() => { view.Caret.MoveTo(view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(1).Start); view.CommentOrUncommentBlock(false); }); Assert.AreEqual(@"print 'hello' print 'goodbye'", view.GetText()); } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestComment() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"print 'hello' print 'goodbye' "); editorTestToolset.UIThread.Invoke(() => { view.SelectAll(); view.CommentOrUncommentBlock(true); }); Assert.AreEqual(@"#print 'hello' #print 'goodbye' ", view.GetText()); } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestCommentEmptyLine() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"print 'hello' print 'goodbye' "); editorTestToolset.UIThread.Invoke(() => { view.SelectAll(); view.CommentOrUncommentBlock(true); }); Assert.AreEqual(@"#print 'hello' #print 'goodbye' ", view.GetText()); } private static MockTextBuffer MockTextBuffer(string code) { return new MockTextBuffer(code, PythonCoreConstants.ContentType, "C:\\fob.py"); } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestCommentWhiteSpaceLine() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"print 'hello' print 'goodbye' "); editorTestToolset.UIThread.Invoke(() => { view.SelectAll(); view.CommentOrUncommentBlock(true); }); Assert.AreEqual(@"#print 'hello' #print 'goodbye' ", view.GetText()); } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestCommentIndented() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"def f(): print 'hello' print 'still here' print 'goodbye'"); editorTestToolset.UIThread.Invoke(() => { view.Select(@" print 'hello' print 'still here'"); view.CommentOrUncommentBlock(true); }); Assert.AreEqual(@"def f(): #print 'hello' #print 'still here' print 'goodbye'", view.GetText()); } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestCommentIndentedBlankLine() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"def f(): print 'hello' print 'still here' print 'goodbye'"); editorTestToolset.UIThread.Invoke(() => { view.Select(@" print 'hello' print 'still here'"); view.CommentOrUncommentBlock(true); }); Assert.AreEqual(@"def f(): #print 'hello' #print 'still here' print 'goodbye'", view.GetText()); } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestCommentBlankLine() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"print('hi') print('bye')"); editorTestToolset.UIThread.Invoke(() => { view.Caret.MoveTo(view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(1).Start); view.CommentOrUncommentBlock(true); }); Assert.AreEqual(@"print('hi') print('bye')", view.GetText()); } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestCommentIndentedWhiteSpaceLine() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"def f(): print 'hello' print 'still here' print 'goodbye'"); editorTestToolset.UIThread.Invoke(() => { view.Select(@" print 'hello' print 'still here'"); view.CommentOrUncommentBlock(true); }); Assert.AreEqual(@"def f(): #print 'hello' #print 'still here' print 'goodbye'", view.GetText()); } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestUnCommentIndented() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"def f(): #print 'hello' #print 'still here' print 'goodbye'"); editorTestToolset.UIThread.Invoke(() => { view.Select(@" #print 'hello' #print 'still here'"); view.CommentOrUncommentBlock(false); }); Assert.AreEqual(@"def f(): print 'hello' print 'still here' print 'goodbye'", view.GetText()); } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestUnComment() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"#print 'hello' #print 'goodbye'"); editorTestToolset.UIThread.Invoke(() => { view.SelectAll(); view.CommentOrUncommentBlock(false); }); var expected = @"print 'hello' print 'goodbye'"; Assert.AreEqual(expected, view.GetText()); } /// <summary> /// http://pytools.codeplex.com/workitem/814 /// </summary> [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestCommentStartOfLastLine() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"print 'hello' print 'goodbye'"); editorTestToolset.UIThread.Invoke(() => { view.Select(@"print 'hello' "); view.CommentOrUncommentBlock(true); }); var expected = @"#print 'hello' print 'goodbye'"; Assert.AreEqual(expected, view.GetText()); } [TestMethod, Priority(UnitTestPriority.P1_FAILING)] public void TestCommentAfterCodeIsNotUncommented() { var editorTestToolset = new EditorTestToolset(); var view = editorTestToolset.CreatePythonTextView(@"print 'hello' #comment that should stay a comment #print 'still here' # another comment that should stay a comment print 'goodbye'"); editorTestToolset.UIThread.Invoke(() => { view.Select(0, view.GetText().IndexOf("print 'goodbye'")); view.CommentOrUncommentBlock(false); }); Assert.AreEqual(@"print 'hello' #comment that should stay a comment print 'still here' # another comment that should stay a comment print 'goodbye'", view.GetText()); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Kyoob.Entities; using Kyoob.Graphics; using Kyoob.VoxelData; // TODO : Input manager class to easily support keyboard+mouse and controllers? // TODO : Make the world (or something) a component so we don't need to manually call everything // TODO : Move most of the main code over to a separate library to facilitate plugins later // TODO : Get rid of heavy JSON dependency and write custom INI parser namespace Kyoob { /// <summary> /// The game class for Kyoob. /// </summary> public sealed class Game : Microsoft.Xna.Framework.Game { /// <summary> /// The path to the settings file. /// </summary> private const string SettingsFile = "settings.json"; private static Game _instance; private GraphicsDeviceManager _graphics; private PresentationParameters _pp; private WorldRenderer _renderer; private KeyboardState _oldKeys; private KeyboardState _newKeys; private FrameCounter _frameCounter; /// <summary> /// Gets the instance of the Kyoob game. /// </summary> public static Game Instance { get { if ( _instance == null ) { _instance = new Game(); } return _instance; } } /// <summary> /// Gets the settings for this game. /// </summary> public GameSettings Settings { get; private set; } /// <summary> /// Creates a new Kyoob game. /// </summary> private Game() { // handle when this game exits Exiting += OnGameExit; // create graphics device manager _graphics = new GraphicsDeviceManager( this ); // set content directory Content.RootDirectory = "content"; // load settings Settings = new GameSettings( this ); Settings.Load( SettingsFile ); // add our frame counter component _frameCounter = new FrameCounter( this ); Components.Add( _frameCounter ); } /// <summary> /// Centers the mouse on this game's window. /// </summary> public void CenterMouse() { Mouse.SetPosition( _pp.BackBufferWidth / 2, _pp.BackBufferHeight / 2 ); } /// <summary> /// Checks to see if the given key was pressed. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public bool WasKeyPressed( Keys key ) { return _oldKeys.IsKeyDown( key ) && _newKeys.IsKeyUp( key ); } /// <summary> /// Handles when this game is exiting. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnGameExit( object sender, EventArgs args ) { Settings.Save( SettingsFile ); } /// <summary> /// Initializes the Kyoob game. /// </summary> protected override void Initialize() { _graphics.PreferredBackBufferWidth = Settings.WindowWidth; _graphics.PreferredBackBufferHeight = Settings.WindowHeight; _graphics.PreferMultiSampling = false; if ( !Settings.VSync ) { IsFixedTimeStep = false; _graphics.SynchronizeWithVerticalRetrace = false; } _graphics.ApplyChanges(); Window.AllowUserResizing = Settings.WindowResizable; base.Initialize(); } /// <summary> /// Loads game-specific content. /// </summary> protected override void LoadContent() { // load the sprite sheet texture SpriteSheet.Instance.Texture = Content.Load<Texture2D>( "textures/spritesheet" ); _pp = GraphicsDevice.PresentationParameters; Mouse.WindowHandle = Window.Handle; // create the world and renderer World.CreateInstance( 279186598 ); //World.CreateInstance( (int)DateTime.Now.Ticks ); _renderer = new WorldRenderer( World.Instance ); } /// <summary> /// Disposes of this game. /// </summary> /// <param name="disposing"></param> protected override void Dispose( bool disposing ) { World.Instance.Dispose(); base.Dispose( disposing ); } /// <summary> /// Updates the Kyoob game. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update( GameTime gameTime ) { // if escape is being pressed, exit _newKeys = Keyboard.GetState(); if ( _newKeys.IsKeyDown( Keys.Escape ) ) { this.Exit(); } // check for keypresses if ( WasKeyPressed( Keys.P ) ) { var handleInput = Player.Instance.HandleInput; IsMouseVisible = handleInput; if ( !handleInput ) { CenterMouse(); } Player.Instance.HandleInput = !handleInput; } if ( WasKeyPressed( Keys.N ) ) { var canNoClip = Player.Instance.CanNoClip; Player.Instance.CanNoClip = !canNoClip; } // update the world _renderer.Update( gameTime ); // update old key state and update base game _oldKeys = _newKeys; base.Update( gameTime ); } /// <summary> /// Draws the Kyoob game. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw( GameTime gameTime ) { // draw the world (handles clearing) _renderer.Draw( gameTime ); // draw our GUI items GUI.Begin(); GUI.DrawText( 10, 10, "{0} FPS", _frameCounter.FPS ); #if DEBUG GUI.DrawText( 10, 24, "Eye Position: {0}", Player.Instance.EyePosition ); GUI.DrawText( 10, 38, "World Seed: {0}", Terrain.Instance.Seed ); #endif GUI.End(); base.Draw( gameTime ); } } }
using UnityEngine; namespace UnityEngine.UI.Windows.Extensions { public static partial class JSONTemplates { /* * Vector2 */ public static Vector2 ToVector2(JSONObject obj) { float x = obj["x"] ? obj["x"].f : 0; float y = obj["y"] ? obj["y"].f : 0; return new Vector2(x, y); } public static JSONObject FromVector2(Vector2 v) { JSONObject vdata = JSONObject.obj; if(v.x != 0) vdata.AddField("x", v.x); if(v.y != 0) vdata.AddField("y", v.y); return vdata; } /* * Vector3 */ public static JSONObject FromVector3(Vector3 v) { JSONObject vdata = JSONObject.obj; if(v.x != 0) vdata.AddField("x", v.x); if(v.y != 0) vdata.AddField("y", v.y); if(v.z != 0) vdata.AddField("z", v.z); return vdata; } public static Vector3 ToVector3(JSONObject obj) { float x = obj["x"] ? obj["x"].f : 0; float y = obj["y"] ? obj["y"].f : 0; float z = obj["z"] ? obj["z"].f : 0; return new Vector3(x, y, z); } /* * Vector4 */ public static JSONObject FromVector4(Vector4 v) { JSONObject vdata = JSONObject.obj; if(v.x != 0) vdata.AddField("x", v.x); if(v.y != 0) vdata.AddField("y", v.y); if(v.z != 0) vdata.AddField("z", v.z); if(v.w != 0) vdata.AddField("w", v.w); return vdata; } public static Vector4 ToVector4(JSONObject obj) { float x = obj["x"] ? obj["x"].f : 0; float y = obj["y"] ? obj["y"].f : 0; float z = obj["z"] ? obj["z"].f : 0; float w = obj["w"] ? obj["w"].f : 0; return new Vector4(x, y, z, w); } /* * Matrix4x4 */ public static JSONObject FromMatrix4x4(Matrix4x4 m) { JSONObject mdata = JSONObject.obj; if(m.m00 != 0) mdata.AddField("m00", m.m00); if(m.m01 != 0) mdata.AddField("m01", m.m01); if(m.m02 != 0) mdata.AddField("m02", m.m02); if(m.m03 != 0) mdata.AddField("m03", m.m03); if(m.m10 != 0) mdata.AddField("m10", m.m10); if(m.m11 != 0) mdata.AddField("m11", m.m11); if(m.m12 != 0) mdata.AddField("m12", m.m12); if(m.m13 != 0) mdata.AddField("m13", m.m13); if(m.m20 != 0) mdata.AddField("m20", m.m20); if(m.m21 != 0) mdata.AddField("m21", m.m21); if(m.m22 != 0) mdata.AddField("m22", m.m22); if(m.m23 != 0) mdata.AddField("m23", m.m23); if(m.m30 != 0) mdata.AddField("m30", m.m30); if(m.m31 != 0) mdata.AddField("m31", m.m31); if(m.m32 != 0) mdata.AddField("m32", m.m32); if(m.m33 != 0) mdata.AddField("m33", m.m33); return mdata; } public static Matrix4x4 ToMatrix4x4(JSONObject obj) { Matrix4x4 result = new Matrix4x4(); if(obj["m00"]) result.m00 = obj["m00"].f; if(obj["m01"]) result.m01 = obj["m01"].f; if(obj["m02"]) result.m02 = obj["m02"].f; if(obj["m03"]) result.m03 = obj["m03"].f; if(obj["m10"]) result.m10 = obj["m10"].f; if(obj["m11"]) result.m11 = obj["m11"].f; if(obj["m12"]) result.m12 = obj["m12"].f; if(obj["m13"]) result.m13 = obj["m13"].f; if(obj["m20"]) result.m20 = obj["m20"].f; if(obj["m21"]) result.m21 = obj["m21"].f; if(obj["m22"]) result.m22 = obj["m22"].f; if(obj["m23"]) result.m23 = obj["m23"].f; if(obj["m30"]) result.m30 = obj["m30"].f; if(obj["m31"]) result.m31 = obj["m31"].f; if(obj["m32"]) result.m32 = obj["m32"].f; if(obj["m33"]) result.m33 = obj["m33"].f; return result; } /* * Quaternion */ public static JSONObject FromQuaternion(Quaternion q) { JSONObject qdata = JSONObject.obj; if(q.w != 0) qdata.AddField("w", q.w); if(q.x != 0) qdata.AddField("x", q.x); if(q.y != 0) qdata.AddField("y", q.y); if(q.z != 0) qdata.AddField("z", q.z); return qdata; } public static Quaternion ToQuaternion(JSONObject obj) { float x = obj["x"] ? obj["x"].f : 0; float y = obj["y"] ? obj["y"].f : 0; float z = obj["z"] ? obj["z"].f : 0; float w = obj["w"] ? obj["w"].f : 0; return new Quaternion(x, y, z, w); } /* * Color */ public static JSONObject FromColor(Color c) { JSONObject cdata = JSONObject.obj; if(c.r != 0) cdata.AddField("r", c.r); if(c.g != 0) cdata.AddField("g", c.g); if(c.b != 0) cdata.AddField("b", c.b); if(c.a != 0) cdata.AddField("a", c.a); return cdata; } public static Color ToColor(JSONObject obj) { Color c = new Color(); for(int i = 0; i < obj.Count; i++) { switch(obj.keys[i]) { case "r": c.r = obj[i].f; break; case "g": c.g = obj[i].f; break; case "b": c.b = obj[i].f; break; case "a": c.a = obj[i].f; break; } } return c; } /* * Layer Mask */ public static JSONObject FromLayerMask(LayerMask l) { JSONObject result = JSONObject.obj; result.AddField("value", l.value); return result; } public static LayerMask ToLayerMask(JSONObject obj) { LayerMask l = new LayerMask {value = (int)obj["value"].n}; return l; } public static JSONObject FromRect(Rect r) { JSONObject result = JSONObject.obj; if(r.x != 0) result.AddField("x", r.x); if(r.y != 0) result.AddField("y", r.y); if(r.height != 0) result.AddField("height", r.height); if(r.width != 0) result.AddField("width", r.width); return result; } public static Rect ToRect(JSONObject obj) { Rect r = new Rect(); for(int i = 0; i < obj.Count; i++) { switch(obj.keys[i]) { case "x": r.x = obj[i].f; break; case "y": r.y = obj[i].f; break; case "height": r.height = obj[i].f; break; case "width": r.width = obj[i].f; break; } } return r; } public static JSONObject FromRectOffset(RectOffset r) { JSONObject result = JSONObject.obj; if(r.bottom != 0) result.AddField("bottom", r.bottom); if(r.left != 0) result.AddField("left", r.left); if(r.right != 0) result.AddField("right", r.right); if(r.top != 0) result.AddField("top", r.top); return result; } public static RectOffset ToRectOffset(JSONObject obj) { RectOffset r = new RectOffset(); for(int i = 0; i < obj.Count; i++) { switch(obj.keys[i]) { case "bottom": r.bottom = (int)obj[i].n; break; case "left": r.left = (int)obj[i].n; break; case "right": r.right = (int)obj[i].n; break; case "top": r.top = (int)obj[i].n; break; } } return r; } public static AnimationCurve ToAnimationCurve(JSONObject obj){ AnimationCurve a = new AnimationCurve(); if(obj.HasField("keys")){ JSONObject keys = obj.GetField("keys"); for(int i =0; i < keys.list.Count;i++){ a.AddKey(ToKeyframe(keys[i])); } } if(obj.HasField("preWrapMode")) a.preWrapMode = (WrapMode)((int)obj.GetField("preWrapMode").n); if(obj.HasField("postWrapMode")) a.postWrapMode = (WrapMode)((int)obj.GetField("postWrapMode").n); return a; } public static JSONObject FromAnimationCurve(AnimationCurve a){ JSONObject result = JSONObject.obj; result.AddField("preWrapMode", a.preWrapMode.ToString()); result.AddField("postWrapMode", a.postWrapMode.ToString()); if(a.keys.Length > 0){ JSONObject keysJSON = JSONObject.Create(); for(int i =0; i < a.keys.Length;i++){ keysJSON.Add(FromKeyframe(a.keys[i])); } result.AddField("keys", keysJSON); } return result; } public static Keyframe ToKeyframe(JSONObject obj){ Keyframe k = new Keyframe(obj.HasField("time")? obj.GetField("time").f : 0, obj.HasField("value")? obj.GetField("value").f : 0); if(obj.HasField("inTangent")) k.inTangent = obj.GetField("inTangent").f; if(obj.HasField("outTangent")) k.outTangent = obj.GetField("outTangent").f; if(obj.HasField("tangentMode")) k.tangentMode = (int)obj.GetField("tangentMode").f; return k; } public static JSONObject FromKeyframe(Keyframe k){ JSONObject result = JSONObject.obj; if(k.inTangent != 0) result.AddField("inTangent", k.inTangent); if(k.outTangent != 0) result.AddField("outTangent", k.outTangent); if(k.tangentMode != 0) result.AddField("tangentMode", k.tangentMode); if(k.time != 0) result.AddField("time", k.time); if(k.value != 0) result.AddField("value", k.value); return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Data.SqlTypes; using System.Globalization; using System.Text; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class SqlTypeTest { private static string[] s_sampleString = new string[] { "In", "its", "first", "month", "on", "the", "market,", "Microsoft\u2019s", "new", "search", "engine", "Bing", "Yahoo\u2019s", "Wednesday", "from", "tracker", "comScore", "8.4% of queries", "Earlier, Microsoft said that unique visitors to Bing", "rose 8% in June compared to the previous month. ", "The company also touted the search engine\u2019s success with advertisers, saying electronics", "retailer TigerDirect increased its marketing spend on", "Bing \u201Cby twofold.\u201D", "\u3072\u3089\u304C\u306A", "\u304B\u305F\u304B\u306A", "\u30AB\u30BF\u30AB\u30CA", "\uFF2C\uFF4F\uFF52\uFF45\uFF4D\u3000\uFF49\uFF50\uFF53\uFF55\uFF4D\u3000\uFF44\uFF4F\uFF4C\uFF4F\uFF52\u3000\uFF53\uFF49\uFF54\u3000\uFF41\uFF4D\uFF45\uFF54", "\uFF8C\uFF67\uFF7D\uFF9E\uFF65\uFF77\uFF9E\uFF80\uFF70", "\u30D5\u30A1\u30BA\u30FB\u30AE\u30BF\u30FC", "eNGine", new string(new char[] {'I', 'n', '\uD800', '\uDC00', 'z'}), // surrogate pair new string(new char[] {'\uD800', '\uDC00', '\uD800', '\uDCCC', '\uDBFF', '\uDFCC', '\uDBFF', '\uDFFF'}) // surrogate pairs }; private static string[,] s_specialMatchingString = new string[4, 2] {{"Lorem ipsum dolor sit amet", "\uFF2C\uFF4F\uFF52\uFF45\uFF4D\u3000\uFF49\uFF50\uFF53\uFF55\uFF4D\u3000\uFF44\uFF4F\uFF4C\uFF4F\uFF52\u3000\uFF53\uFF49\uFF54\u3000\uFF41\uFF4D\uFF45\uFF54"}, {"\u304B\u305F\u304B\u306A", "\u30AB\u30BF\u30AB\u30CA"}, {"\uFF8C\uFF67\uFF7D\uFF9E\uFF65\uFF77\uFF9E\uFF80\uFF70", "\u30D5\u30A1\u30BA\u30FB\u30AE\u30BF\u30FC"}, {"engine", "eNGine"}}; private static SqlCompareOptions s_defaultCompareOption = SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth; private static SqlCompareOptions[] s_compareOptions = new SqlCompareOptions[] { SqlCompareOptions.None, SqlCompareOptions.BinarySort, SqlCompareOptions.BinarySort2, s_defaultCompareOption}; private static int s_sampleStringCount = s_sampleString.Length - 1; private static CultureInfo[] s_cultureInfo = { new CultureInfo("ar-SA"), // Arabic - Saudi Arabia new CultureInfo("ja-JP"), // Japanese - Japan new CultureInfo("de-DE"), // German - Germany new CultureInfo("hi-IN"), // Hindi - India new CultureInfo("tr-TR"), // Turkish - Turkey new CultureInfo("th-TH"), // Thai - Thailand new CultureInfo("el-GR"), // Greek - Greece new CultureInfo("ru-RU"), // Russian - Russia new CultureInfo("he-IL"), // Hebrew - Israel new CultureInfo("cs-CZ"), // Czech - Czech Republic new CultureInfo("fr-CH"), // French - Switzerland new CultureInfo("en-US") // English - United States }; private static int[] s_cultureLocaleIDs = { 0x0401, // Arabic - Saudi Arabia 0x0411, // Japanese - Japan 0x0407, // German - Germany 0x0439, // Hindi - India 0x041f, // Turkish - Turkey 0x041e, // Thai - Thailand 0x0408, // Greek - Greece 0x0419, // Russian - Russia 0x040d, // Hebrew - Israel 0x0405, // Czech - Czech Republic 0x100c, // French - Switzerland 0x0409 // English - United States }; private static UnicodeEncoding s_unicodeEncoding = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true); [Fact] public static void SqlStringValidComparisonTest() { for (int j = 0; j < s_cultureInfo.Length; ++j) { SqlStringDefaultCompareOptionTest(s_cultureLocaleIDs[j]); for (int i = 0; i < s_compareOptions.Length; ++i) { SqlStringCompareTest(200, s_compareOptions[i], s_cultureInfo[j], s_cultureLocaleIDs[j]); } } } [Fact] public static void SqlStringNullComparisonTest() { SqlString nullSqlString = new SqlString(null); SqlString nonNullSqlString = new SqlString("abc "); Assert.True( (bool)(nullSqlString < nonNullSqlString || nonNullSqlString >= nullSqlString || nullSqlString.CompareTo(nonNullSqlString) < 0 || nonNullSqlString.CompareTo(nullSqlString) >= 0), "FAILED: (SqlString Null Comparison): Null SqlString not equal to null"); Assert.True((nullSqlString == null && nullSqlString.CompareTo(null) == 0).IsNull, "FAILED: (SqlString Null Comparison): Null SqlString not equal to null"); } // Special characters matching test for default option (SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth) private static void SqlStringDefaultCompareOptionTest(int localeID) { SqlString str1; SqlString str2; for (int i = 0; i < s_specialMatchingString.GetLength(0); ++i) { // SqlString(string) creates instance with the default comparison options str1 = new SqlString(s_specialMatchingString[i, 0], localeID); str2 = new SqlString(s_specialMatchingString[i, 1], localeID); // Per default option, each set contains two string which should be matched as equal per default option Assert.True((bool)(str1 == str2), string.Format("Error (Default Comparison Option with Operator): {0} and {1} should be equal", s_specialMatchingString[i, 0], s_specialMatchingString[i, 1])); Assert.True(str1.CompareTo(str2) == 0, string.Format("FAILED: (Default Comparison Option with CompareTo): {0} and {1} should be equal", s_specialMatchingString[i, 0], s_specialMatchingString[i, 1])); } } private static void SqlStringCompareTest(int numberOfItems, SqlCompareOptions compareOption, CultureInfo cInfo, int localeID) { SortedList<SqlString, SqlString> items = CreateSortedSqlStringList(numberOfItems, compareOption, cInfo, localeID); VerifySortedSqlStringList(items, compareOption, cInfo); } private static SortedList<SqlString, SqlString> CreateSortedSqlStringList(int numberOfItems, SqlCompareOptions compareOption, CultureInfo cInfo, int localeID) { SortedList<SqlString, SqlString> items = new SortedList<SqlString, SqlString>(numberOfItems); // // Generate list of SqlString // Random rand = new Random(500); int numberOfWords; StringBuilder builder = new StringBuilder(); SqlString word; for (int i = 0; i < numberOfItems; ++i) { do { builder.Clear(); numberOfWords = rand.Next(10) + 1; for (int j = 0; j < numberOfWords; ++j) { builder.Append(s_sampleString[rand.Next(s_sampleStringCount)]); builder.Append(" "); } if (numberOfWords % 2 == 1) { for (int k = 0; k < rand.Next(100); ++k) { builder.Append(' '); } } word = new SqlString(builder.ToString(), localeID, compareOption); } while (items.ContainsKey(word)); items.Add(word, word); } return items; } private static void VerifySortedSqlStringList(SortedList<SqlString, SqlString> items, SqlCompareOptions compareOption, CultureInfo cInfo) { // // Verify the list is in order // IList<SqlString> keyList = items.Keys; for (int i = 0; i < items.Count - 1; ++i) { SqlString currentString = keyList[i]; SqlString nextString = keyList[i + 1]; Assert.True((bool)((currentString < nextString) && (nextString >= currentString)), "FAILED: (SqlString Operator Comparison): SqlStrings are out of order"); Assert.True((currentString.CompareTo(nextString) < 0) && (nextString.CompareTo(currentString) > 0), "FAILED: (SqlString.CompareTo): SqlStrings are out of order"); switch (compareOption) { case SqlCompareOptions.BinarySort: Assert.True(CompareBinary(currentString.Value, nextString.Value) < 0, "FAILED: (SqlString BinarySort Comparison): SqlStrings are out of order"); break; case SqlCompareOptions.BinarySort2: Assert.True(string.CompareOrdinal(currentString.Value.TrimEnd(), nextString.Value.TrimEnd()) < 0, "FAILED: (SqlString BinarySort2 Comparison): SqlStrings are out of order"); break; default: CompareInfo cmpInfo = cInfo.CompareInfo; CompareOptions cmpOptions = SqlString.CompareOptionsFromSqlCompareOptions(nextString.SqlCompareOptions); Assert.True(cmpInfo.Compare(currentString.Value.TrimEnd(), nextString.Value.TrimEnd(), cmpOptions) < 0, "FAILED: (SqlString Comparison): SqlStrings are out of order"); break; } } } // Wide-character string comparison for Binary Unicode Collation (for SqlCompareOptions.BinarySort) // Return values: // -1 : wstr1 < wstr2 // 0 : wstr1 = wstr2 // 1 : wstr1 > wstr2 // // Does a memory comparison. // NOTE: This comparison algorithm is different from BinraySory2. The algorithm is copied fro SqlString implementation private static int CompareBinary(string x, string y) { byte[] rgDataX = s_unicodeEncoding.GetBytes(x); byte[] rgDataY = s_unicodeEncoding.GetBytes(y); int cbX = rgDataX.Length; int cbY = rgDataY.Length; int cbMin = cbX < cbY ? cbX : cbY; int i; for (i = 0; i < cbMin; i++) { if (rgDataX[i] < rgDataY[i]) return -1; else if (rgDataX[i] > rgDataY[i]) return 1; } i = cbMin; int iCh; int iSpace = (int)' '; if (cbX < cbY) { for (; i < cbY; i += 2) { iCh = ((int)rgDataY[i + 1]) << 8 + rgDataY[i]; if (iCh != iSpace) return (iSpace > iCh) ? 1 : -1; } } else { for (; i < cbX; i += 2) { iCh = ((int)rgDataX[i + 1]) << 8 + rgDataX[i]; if (iCh != iSpace) return (iCh > iSpace) ? 1 : -1; } } return 0; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace CustomerManager.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// <copyright file="Proxy.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; namespace OpenQA.Selenium { /// <summary> /// Describes the kind of proxy. /// </summary> /// <remarks> /// Keep these in sync with the Firefox preferences numbers: /// http://kb.mozillazine.org/Network.proxy.type /// </remarks> public enum ProxyKind { /// <summary> /// Direct connection, no proxy (default on Windows). /// </summary> Direct = 0, /// <summary> /// Manual proxy settings (e.g., for httpProxy). /// </summary> Manual, /// <summary> /// Proxy automatic configuration from URL. /// </summary> ProxyAutoConfigure, /// <summary> /// Use proxy automatic detection. /// </summary> AutoDetect = 4, /// <summary> /// Use the system values for proxy settings (default on Linux). /// </summary> System, /// <summary> /// No proxy type is specified. /// </summary> Unspecified } /// <summary> /// Describes proxy settings to be used with a driver instance. /// </summary> [JsonObject(MemberSerialization.OptIn)] public class Proxy { private ProxyKind proxyKind = ProxyKind.Unspecified; private bool isAutoDetect; private string ftpProxyLocation; private string httpProxyLocation; private string proxyAutoConfigUrl; private string sslProxyLocation; private string socksProxyLocation; private string socksUserName; private string socksPassword; private List<string> noProxyAddresses = new List<string>(); /// <summary> /// Initializes a new instance of the <see cref="Proxy"/> class. /// </summary> public Proxy() { } /// <summary> /// Initializes a new instance of the <see cref="Proxy"/> class with the given proxy settings. /// </summary> /// <param name="settings">A dictionary of settings to use with the proxy.</param> public Proxy(Dictionary<string, object> settings) { if (settings == null) { throw new ArgumentNullException("settings", "settings dictionary cannot be null"); } if (settings.ContainsKey("proxyType")) { ProxyKind rawType = (ProxyKind)Enum.Parse(typeof(ProxyKind), settings["proxyType"].ToString(), true); this.Kind = rawType; } if (settings.ContainsKey("ftpProxy")) { this.FtpProxy = settings["ftpProxy"].ToString(); } if (settings.ContainsKey("httpProxy")) { this.HttpProxy = settings["httpProxy"].ToString(); } if (settings.ContainsKey("noProxy")) { List<string> bypassAddresses = new List<string>(); string addressesAsString = settings["noProxy"] as string; if (addressesAsString != null) { bypassAddresses.AddRange(addressesAsString.Split(';')); } else { object[] addressesAsArray = settings["noProxy"] as object[]; if (addressesAsArray != null) { foreach (object address in addressesAsArray) { bypassAddresses.Add(address.ToString()); } } } this.AddBypassAddresses(bypassAddresses); } if (settings.ContainsKey("proxyAutoconfigUrl")) { this.ProxyAutoConfigUrl = settings["proxyAutoconfigUrl"].ToString(); } if (settings.ContainsKey("sslProxy")) { this.SslProxy = settings["sslProxy"].ToString(); } if (settings.ContainsKey("socksProxy")) { this.SocksProxy = settings["socksProxy"].ToString(); } if (settings.ContainsKey("socksUsername")) { this.SocksUserName = settings["socksUsername"].ToString(); } if (settings.ContainsKey("socksPassword")) { this.SocksPassword = settings["socksPassword"].ToString(); } if (settings.ContainsKey("autodetect")) { this.IsAutoDetect = (bool)settings["autodetect"]; } } /// <summary> /// Gets or sets the type of proxy. /// </summary> [JsonIgnore] public ProxyKind Kind { get { return this.proxyKind; } set { this.VerifyProxyTypeCompatilibily(value); this.proxyKind = value; } } /// <summary> /// Gets the type of proxy as a string for JSON serialization. /// </summary> [JsonProperty("proxyType")] public string SerializableProxyKind { get { if (this.proxyKind == ProxyKind.ProxyAutoConfigure) { return "PAC"; } return this.proxyKind.ToString().ToUpperInvariant(); } } /// <summary> /// Gets or sets a value indicating whether the proxy uses automatic detection. /// </summary> [JsonIgnore] public bool IsAutoDetect { get { return this.isAutoDetect; } set { if (this.isAutoDetect == value) { return; } this.VerifyProxyTypeCompatilibily(ProxyKind.AutoDetect); this.proxyKind = ProxyKind.AutoDetect; this.isAutoDetect = value; } } /// <summary> /// Gets or sets the value of the proxy for the FTP protocol. /// </summary> [JsonProperty("ftpProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)] public string FtpProxy { get { return this.ftpProxyLocation; } set { this.VerifyProxyTypeCompatilibily(ProxyKind.Manual); this.proxyKind = ProxyKind.Manual; this.ftpProxyLocation = value; } } /// <summary> /// Gets or sets the value of the proxy for the HTTP protocol. /// </summary> [JsonProperty("httpProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)] public string HttpProxy { get { return this.httpProxyLocation; } set { this.VerifyProxyTypeCompatilibily(ProxyKind.Manual); this.proxyKind = ProxyKind.Manual; this.httpProxyLocation = value; } } /// <summary> /// Gets or sets the value for bypass proxy addresses. /// </summary> [Obsolete("Add addresses to bypass with the proxy by using the AddBypassAddress method.")] public string NoProxy { get { return this.BypassProxyAddresses; } set { this.AddBypassAddress(value); } } /// <summary> /// Gets the semicolon delimited list of address for which to bypass the proxy. /// </summary> [JsonProperty("noProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)] public string BypassProxyAddresses { get { if (this.noProxyAddresses.Count == 0) { return null; } return string.Join(";", this.noProxyAddresses.ToArray()); } } /// <summary> /// Gets or sets the URL used for proxy automatic configuration. /// </summary> [JsonProperty("proxyAutoconfigUrl", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)] public string ProxyAutoConfigUrl { get { return this.proxyAutoConfigUrl; } set { this.VerifyProxyTypeCompatilibily(ProxyKind.ProxyAutoConfigure); this.proxyKind = ProxyKind.ProxyAutoConfigure; this.proxyAutoConfigUrl = value; } } /// <summary> /// Gets or sets the value of the proxy for the SSL protocol. /// </summary> [JsonProperty("sslProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)] public string SslProxy { get { return this.sslProxyLocation; } set { this.VerifyProxyTypeCompatilibily(ProxyKind.Manual); this.proxyKind = ProxyKind.Manual; this.sslProxyLocation = value; } } /// <summary> /// Gets or sets the value of the proxy for the SOCKS protocol. /// </summary> [JsonProperty("socksProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)] public string SocksProxy { get { return this.socksProxyLocation; } set { this.VerifyProxyTypeCompatilibily(ProxyKind.Manual); this.proxyKind = ProxyKind.Manual; this.socksProxyLocation = value; } } /// <summary> /// Gets or sets the value of username for the SOCKS proxy. /// </summary> [JsonProperty("socksUsername", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)] public string SocksUserName { get { return this.socksUserName; } set { this.VerifyProxyTypeCompatilibily(ProxyKind.Manual); this.proxyKind = ProxyKind.Manual; this.socksUserName = value; } } /// <summary> /// Gets or sets the value of password for the SOCKS proxy. /// </summary> [JsonProperty("socksPassword", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)] public string SocksPassword { get { return this.socksPassword; } set { this.VerifyProxyTypeCompatilibily(ProxyKind.Manual); this.proxyKind = ProxyKind.Manual; this.socksPassword = value; } } /// <summary> /// Adds a single address to the list of addresses against which the proxy will not be used. /// </summary> /// <param name="address">The address to add.</param> public void AddBypassAddress(string address) { if (string.IsNullOrEmpty(address)) { throw new ArgumentException("address must not be null or empty", "address"); } this.AddBypassAddresses(address); } /// <summary> /// Adds addresses to the list of addresses against which the proxy will not be used. /// </summary> /// <param name="addressesToAdd">An array of addresses to add.</param> public void AddBypassAddresses(params string[] addressesToAdd) { this.AddBypassAddresses(new List<string>(addressesToAdd)); } /// <summary> /// Adds addresses to the list of addresses against which the proxy will not be used. /// </summary> /// <param name="addressesToAdd">An <see cref="IEnumerable{T}"/> object of arguments to add.</param> public void AddBypassAddresses(IEnumerable<string> addressesToAdd) { if (addressesToAdd == null) { throw new ArgumentNullException("addressesToAdd", "addressesToAdd must not be null"); } this.VerifyProxyTypeCompatilibily(ProxyKind.Manual); this.proxyKind = ProxyKind.Manual; this.noProxyAddresses.AddRange(addressesToAdd); } /// <summary> /// Returns a dictionary suitable for serializing to the W3C Specification /// dialect of the wire protocol. /// </summary> /// <returns>A dictionary suitable for serializing to the W3C Specification /// dialect of the wire protocol.</returns> internal Dictionary<string, object> ToCapability() { return this.AsDictionary(true); } /// <summary> /// Returns a dictionary suitable for serializing to the OSS dialect of the /// wire protocol. /// </summary> /// <returns>A dictionary suitable for serializing to the OSS dialect of the /// wire protocol.</returns> internal Dictionary<string, object> ToLegacyCapability() { return this.AsDictionary(false); } private Dictionary<string, object> AsDictionary(bool isSpecCompliant) { Dictionary<string, object> serializedDictionary = null; if (this.proxyKind != ProxyKind.Unspecified) { serializedDictionary = new Dictionary<string, object>(); if (this.proxyKind == ProxyKind.ProxyAutoConfigure) { serializedDictionary["proxyType"] = "pac"; if (!string.IsNullOrEmpty(this.proxyAutoConfigUrl)) { serializedDictionary["proxyAutoconfigUrl"] = this.proxyAutoConfigUrl; } } else { serializedDictionary["proxyType"] = this.proxyKind.ToString().ToLowerInvariant(); } if (!string.IsNullOrEmpty(this.httpProxyLocation)) { serializedDictionary["httpProxy"] = this.httpProxyLocation; } if (!string.IsNullOrEmpty(this.sslProxyLocation)) { serializedDictionary["sslProxy"] = this.sslProxyLocation; } if (!string.IsNullOrEmpty(this.ftpProxyLocation)) { serializedDictionary["ftpProxy"] = this.ftpProxyLocation; } if (!string.IsNullOrEmpty(this.socksProxyLocation)) { string socksAuth = string.Empty; if (!string.IsNullOrEmpty(this.socksUserName) && !string.IsNullOrEmpty(this.socksPassword)) { // TODO: this is probably inaccurate as to how this is supposed // to look. socksAuth = this.socksUserName + ":" + this.socksPassword + "@"; } serializedDictionary["socksProxy"] = socksAuth + this.socksProxyLocation; } if (this.noProxyAddresses.Count > 0) { serializedDictionary["noProxy"] = this.GetNoProxyAddressList(isSpecCompliant); } } return serializedDictionary; } private object GetNoProxyAddressList(bool isSpecCompliant) { object addresses = null; if (isSpecCompliant) { List<object> addressList = new List<object>(); foreach (string address in this.noProxyAddresses) { addressList.Add(address); } addresses = addressList; } else { addresses = this.BypassProxyAddresses; } return addresses; } private void VerifyProxyTypeCompatilibily(ProxyKind compatibleProxy) { if (this.proxyKind != ProxyKind.Unspecified && this.proxyKind != compatibleProxy) { string errorMessage = string.Format( CultureInfo.InvariantCulture, "Specified proxy type {0} is not compatible with current setting {1}", compatibleProxy.ToString().ToUpperInvariant(), this.proxyKind.ToString().ToUpperInvariant()); throw new InvalidOperationException(errorMessage); } } } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; using Elastic.Clients.Elasticsearch; using Elastic.Clients.Elasticsearch.Aggregations; using Elastic.Clients.Elasticsearch.Helpers; using Elastic.Clients.Elasticsearch.QueryDsl; using Elastic.Clients.JsonNetSerializer; using Elastic.Transport; namespace Playground { internal class Program { public class Thing { public QueryContainer? Query { get; set; } } public class UserType { [MyConverter] public string? Name { get; set; } } internal sealed class MyConverterAttribute : JsonConverterAttribute { #pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. #pragma warning disable CS8603 // Possible null reference return. public override JsonConverter CreateConverter(Type typeToConvert) => (JsonConverter)Activator.CreateInstance(typeof(MyConverterConverter<>).MakeGenericType(typeToConvert)); #pragma warning restore CS8603 // Possible null reference return. #pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type. } internal sealed class MyConverterConverter<T> : JsonConverter<T> { public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotImplementedException(); public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { var converter = options.GetConverter(typeof(T)); writer.WritePropertyName("custom"); if (converter is JsonConverter<T> final) final.Write(writer, value, options); } public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSerializerOptions options) => writer.WritePropertyName("custom"); } private static async Task Main() { var toConvert = new UserType { Name = "steve" }; var jsonTest = JsonSerializer.Serialize(toConvert); var client = new ElasticsearchClient(new ElasticsearchClientSettings(new Uri("http://localhost:9600")) //.CertificateFingerprint("028567742bb754e19ddc8eab752b70d6534f98dccdb681863f57f9b0564170c0") //.ServerCertificateValidationCallback((a, b, c, d) => true) //.Authentication(new BasicAuthentication("elastic", "HSPvzLR7cSt8PwXJRWjl")) .DefaultMappingFor<Person>(p => p.IndexName("people-test"))); var result = await client.BulkAsync(b => b.DeleteMany("people-test", new Id[] { "1", "2" })); result = await client.BulkAsync(b => b.DeleteMany<Person>(new[] { new Person { Id = 100 }, new Person { Id = 200 } })); result = await client.BulkAsync(b => b.DeleteMany(new[] { new Person { Id = 100 }, new Person { Id = 200 } })); Console.ReadKey(); //var health = await client.Cluster.HealthAsync(new Elastic.Clients.Elasticsearch.Cluster.ClusterHealthRequest("non-exist")); //Console.ReadKey(); //var ec = new Client(); ////#pragma warning disable IDE0039 // Use local function //// //Func<BoolQueryDescriptor<Person>, IBoolQuery> test = b => b.Name("thing"); //// //Local variables change type //// Action<ExampleRequestDescriptor> test = b => b.Name("thing"); ////#pragma warning restore IDE0039 // Use local function //// //static IBoolQuery TestBoolQuery(BoolQueryDescriptor<Person> b) => b.Name("thing"); //// //Local functions become void returning //// static void TestBoolQuery(ExampleRequestDescriptor b) => b.Name("thing"); //// ec.SomeEndpoint(TestBoolQuery); //// ec.SomeEndpoint(new ExampleRequest //// { //// Name = "Object test", //// Subtype = new ClusterSubtype //// { //// Identifier = "AnID" //// }, //// Query = new Elastic.Clients.Elasticsearch.Experimental.QueryContainer(new Elastic.Clients.Elasticsearch.Experimental.BoolQuery { Tag = "variant_string" }) //// }); //// ec.SomeEndpoint(new ExampleRequest //// { //// Name = "Object test", //// Subtype = new ClusterSubtype //// { //// Identifier = "AnID" //// }, //// // Static query "helper" provides a way to use the fluent syntax that can be combined with object initialiser code //// // at the cost of an extra object allocation //// Query = Query.Bool(b => b.Tag("using_query_helper")) //// }); //ec.SomeEndpoint(new ExampleRequest //{ // Name = "Object test", // Subtype = new ClusterSubtypeDescriptor().Identifier("implictly-assigned"), // Query = Query.Bool(b => b.Tag("using_query_helper")) //}); //ec.SomeEndpoint(c => c // .Name("Descriptor test") // .Subtype(s => s.Identifier("AnID")) // .Query(c => c.Bool(v => v.Tag("some_tag")))); ////var descriptor = new ClusterSubtypeDescriptor().Identifier("AnID"); ////ec.SomeEndpoint(c => c //// .Name("Descriptor test") //// .Subtype(descriptor) //// .Query(c => c.Boosting(v => v.BoostAmount(10)))); ////ec.SomeEndpoint(c => c //// .Name("Mixed object and descriptor test") //// .Subtype(new ClusterSubtype { Identifier = "AnID" })); ////var requestDescriptor = new ExampleRequestDescriptor().Name("descriptor_usage"); ////ec.SomeEndpoint(requestDescriptor); ////var boolQuery = new Elastic.Clients.Elasticsearch.Experimental.BoolQuery { Tag = "TEST" }; ////var container = boolQuery.WrapInContainer(); ////if (container.TryGetBoolQuery(out boolQuery)) ////{ //// Console.WriteLine(boolQuery.Tag); ////} //ec.CombinedEndpoint(r => r.WithName("Steve").WithThing(t => t.WithTitle("Title"))); //var pool = new SingleNodePool(new Uri("https://localhost:9600")); //var client = new ElasticsearchClient(new ElasticsearchClientSettings(pool) // .Authentication(new BasicAuthentication("elastic", "Ey5c7EYcZ=g0JtMwo-+y")) // .ServerCertificateValidationCallback((a, b, c, d) => true) // .DefaultMappingFor<PersonV2>(p => p.IndexName("people-test"))); ////.CertificateFingerprint("3842926c8a7ef04bb24ecaf8a4c44b7e24a416d682f3b818cf553fde39470451")); //var put = await client.IndexAsync(new PersonV2 { FirstName = "Steve" }, i => i.Id("1234657890")); //var get = await client.GetAsync<PersonV2>(Infer.Index<PersonV2>(), "1234657890"); var people = new PersonV2[] { new PersonV2 { FirstName = "Martijn" }, new PersonV2 { FirstName = "Steve" }, new PersonV2 { FirstName = "Russ" }, new PersonV2 { FirstName = "Philip" }, new PersonV2 { FirstName = "Nigel" }, new PersonV2 { FirstName = "Fernando" }, new PersonV2 { FirstName = "Enrico" }, new PersonV2 { FirstName = "Sylvain" }, new PersonV2 { FirstName = "Laurent" }, new PersonV2 { FirstName = "Seth" }, new PersonV2 { FirstName = "Tomas" } }; //var bulkAll = new BulkAllObservable<PersonV2>(client, new BulkAllRequest<PersonV2>(people) { Index = "people-v2-test" }); var bulkAll = client.BulkAll(people, b => b.Index("people-v2-test")); var observer = bulkAll.Wait(TimeSpan.FromMinutes(1), n => { }); //var bulkAllv2 = client.Helpers.BulkAllObservable(people, b => b.Index("people-v2-test")); //var observer2 = bulkAllv2.Wait(TimeSpan.FromMinutes(1), n => { }); //var request = await client.BulkAsync(b => b // .Index("people-test") // .Create(new Person { FirstName = "Rhiannon" }) // .Create(new Person { FirstName = "Rhiannon" }, c => c.Id(200)) // .Index(new Person { FirstName = "Steve" }, i => i.Id(100)) // .Update(BulkUpdateOperationFactory.WithPartial(200, new Person { LastName = "Gordon" })) // .Update(BulkUpdateOperationFactory.WithScript(200, Infer.Index<Person>(), new InlineScript("ctx._source.lastName = 'Gordon'"))) // .Delete(100)); //client.Search<Person>(s => s // .Size(1) // .From(0) // .Aggregations(a => a.Terms("my-terms", t => t.Field("firstName"))) // .Query(q => q.MatchAll())); var countResult = await client.CountAsync<Person>(d => d.Query(new QueryContainer(new MatchQuery { Field = "name", Query = "NEST" }))); var serialiser = client.RequestResponseSerializer; //var response = client.IndexManagement.CreateIndex("testing", i => i // .Settings(s => s.Add("thing", 10))); //var qc = new QueryContainer(new BoolQuery { QueryName = "a_bool_query", Must = new[] { new QueryContainer(new TermQuery { Boost = 0.5f, Field = "the_field", Value = "the_value", CaseInsensitive = true }) } }); //var thing = new Thing { Query = qc }; var thing = new IndexRequest<Person>(new Person() { FirstName = "Steve", LastName = "Gordon", Age = 37 }); var aggs = new AggregationDictionary { { "startDates", new TermsAggregation("startDates") { Field = "startedOn" } }, { "endDates", new DateHistogramAggregation("endDates") { Field = "endedOn" } } }; var search = new SearchRequest() { From = 10, Size = 20, Query = new QueryContainer(new MatchAllQuery()), Aggregations = aggs, PostFilter = new QueryContainer(new TermQuery { Field = "state", Value = "Stable" }) }; var stream = new MemoryStream(); serialiser.Serialize(search, stream); stream.Position = 0; var json = Encoding.UTF8.GetString(stream.ToArray()); stream.Position = 0; if (json.Length > 0) { var deserialised = serialiser.Deserialize<Thing>(stream); } //var response = client.Ping(); //if (response.IsValid) //{ //} //var searchAgain = new SearchRequest() //{ // Query = new Elastic.Clients.Elasticsearch.QueryDsl.QueryContainer(new Elastic.Clients.Elasticsearch.QueryDsl.BoolQuery { Boost = 1.2F }), // MinScore = 10.0, // Profile = true //}; //var jsonStream = new MemoryStream(); //client.ElasticsearchClientSettings.RequestResponseSerializer.Serialize(searchAgain, jsonStream); //jsonStream.Position = 0; //var json = Encoding.UTF8.GetString(jsonStream.ToArray()); //var response = client.Search<Person>(searchAgain); //// TODO: The original search request includes header parsing as the config is cached - we should reset this on the product check flow? //response = client.Search<Person>(searchAgain); ////var response = client.Transport.Request<BytesResponse>(HttpMethod.GET, "test"); ////var stream = new MemoryStream(); ////IMatchQuery match = new MatchQuery() { QueryName = "test_match", Field = "firstName", Query = "Steve" }; ////client.ElasticsearchClientSettings.SourceSerializer.Serialize(match, stream); ////stream.Position = 0; ////var json = Encoding.UTF8.GetString(stream.ToArray()); ////var matchAll = new QueryContainer(new MatchAllQuery() { QueryName = "test_query" }); ////var boolQuery = new QueryContainer(new BoolQuery() { Filter = new[] { new QueryContainer(new MatchQuery() { QueryName = "test_match", Field = "firstName", Query = "Steve" }) }}); //var search = new SearchRequest() //{ // Query = new Elastic.Clients.Elasticsearch.QueryDsl.QueryContainer(new Elastic.Clients.Elasticsearch.QueryDsl.BoolQuery { Boost = 1.2F }), // MinScore = 10.0, // Profile = true //}; //var stream = new MemoryStream(); //client.ElasticsearchClientSettings.SourceSerializer.Serialize(search, stream); //stream.Position = 0; //var json1 = Encoding.UTF8.GetString(stream.ToArray()); //ISearchRequest d = new SearchRequestDescriptor().MinScore(10.0).Profile(true); //var newStream = new MemoryStream(); //client.ElasticsearchClientSettings.SourceSerializer.Serialize(d, newStream); //stream.Position = 0; //var json = Encoding.UTF8.GetString(stream.ToArray()); //if (json.Length > 0) // Console.WriteLine(json); //var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(json)); //var request = client.ElasticsearchClientSettings.SourceSerializer.Deserialize<ISearchRequest>(jsonStream); //if (request is not null) // Console.WriteLine("DONE"); //var response = await client.SearchAsync<Person>(search); //var fluentResponse = client.SearchAsync<Person>(s => s.Query(matchAll)); //var matchQueryOne = Query<Person>.Match(m => m.Field(f => f.FirstName).Query("Steve")); //var matchQueryTwo = new QueryContainer(new MatchQuery() { Field = "firstName"/*Infer.Field<Person>(f => f.FirstName)*/, Query = "Steve" }); //var matchQueryThree = new QueryContainerDescriptor<Person>().Match(m => m.Query(SearchQuery.String("Steve"))); //var matchQueryFour = new QueryContainerDescriptor<Person>().Match(m => m.Analyzer("")); //var s = new ElasticsearchClientSettings(); //IElasticsearchClient client = new ElasticsearchClient(s); //var indexName = Guid.NewGuid().ToString(); //// Get cluster health //var clusterHealthRequest = new HealthRequest {Level = Level.Cluster}; //var clusterHealthResponse = await client.Cluster.HealthAsync(clusterHealthRequest); //var clusterHealthResponseTwo = await client.Cluster.HealthAsync(d => d.Level(Level.Cluster)); //var allocExplainRequest = new AllocationExplainRequest { Primary = true }; //var allocExplainResponse = await client.Cluster.AllocationExplainAsync(allocExplainRequest); //var personDoc = new Person("Steve Gordon") { Age = 36, Email = "sgordon@example.com" }; //var indexResponseOne = await client.IndexAsync(new IndexRequest<Person>("people") { Document = personDoc }); //var indexResponseTwo = await client.IndexAsync(personDoc, "people"); //if (!clusterHealthResponse.IsValid) // throw new Exception("Failed to get cluster health"); //if (clusterHealthResponse.Status == Health.Red) // throw new Exception("Cluster is unhealthy"); //// Create an index //var createResponse = await client.IndexManagement.CreateAsync(new CreateRequest(indexName) //{ // Mappings = new TypeMapping // { // DateDetection = false, // Properties = new Dictionary<PropertyName, PropertyBase> // { // {"age", new NumberProperty {Type = NumberType.Integer}}, // {"name", new TextProperty()}, // {"email", new KeywordProperty()} // }, // Meta = new Metadata { { "foo", "bar" } } // } //}); //if (!createResponse.IsValid) // throw new Exception($"Failed to create index {indexName}"); //if (!createResponse.Acknowledged) // throw new Exception("The create index request has not been acknowledged"); //// TODO - Check index exists //// Index a document //var indexResponse = // await client.IndexAsync(new IndexRequest<Person>(indexName, new Id("1")) // { // Document = new Person("Steve") { Age = 36, Email = "test@example.com" } // }); //if (!indexResponse.IsValid) // throw new Exception("Failed to index the document"); //Console.WriteLine($"Indexed document with ID {indexResponse.Id}"); //// Index a document without explicit ID //var indexResponse2 = // await client.IndexAsync(new IndexRequest<Person>(indexName) // { // Document = new Person("Joe") { Age = 40, Email = "test2@example.com" } // }); //if (!indexResponse2.IsValid) // throw new Exception("Failed to index the document"); //Console.WriteLine($"Indexed document with ID {indexResponse2.Id}"); //// Check the document exists //var documentExistsResponse = await client.ExistsAsync(indexName, indexResponse.Id); //if (!documentExistsResponse.IsValid) // throw new Exception("Failed to check if the document exists"); //if (!documentExistsResponse.Exists) // throw new Exception($"Document with ID {indexResponse.Id} does not exist"); //// Get the document by its ID //var getDocumentResponse = await client.GetAsync<Person>(indexName, indexResponse.Id); //if (!getDocumentResponse.IsValid) // throw new Exception($"Failed to get a document with ID {indexResponse.Id}"); ////var refreshResponse = await client.IndexManagement.RefreshAsync(new RefreshRequest(indexName)); ////if (!refreshResponse.IsValid) //// throw new Exception($"Failed to refresh index {indexName}"); //// Basic search //var searchResponse = // await client.SearchAsync<Person>(new SearchRequest(indexName) { RestTotalHitsAsInt = true }); //var searchResponseTwo = // await client.SearchAsync<Person>(new SearchRequest(Indices.All) { RestTotalHitsAsInt = true }); //if (!searchResponse.IsValid) // throw new Exception("Failed to search for any documents"); //// TODO - Union deserialisation not yet implemented ////long hits = 0; ////searchResponse.Hits.Total.Match(a => hits = a.Value, b => hits = b); //// Console.WriteLine($"The basic search found {hits} hits"); //Console.WriteLine($"The basic search found {searchResponse.Hits.Hits.Count} hits"); //// Basic terms agg //// Original ////var request = new SearchRequest<Person> ////{ //// Aggregations = new TermsAggregation("symbols") //// { //// Field = Infer.Field<Person>(f => f.Name), //// Size = 1000 //// }, //// Size = 0 ////}; //// Basic terms aggregation //var request = new SearchRequest(indexName) //{ // Aggregations = // new // Dictionary<string, AggregationContainer> // TODO - Can this be improved to align with our existing style? // { // { // "names", // new() // { // Terms = new TermsAggregation // { // //Field = Infer.Field<Person>(f => f.Email!), // Field = "email", // Size = 100 // } // } // } // }, // Size = 0, // //Profile = true, // RestTotalHitsAsInt = true // required for now until union converter is able to handle objects! TODO //}; //searchResponse = await client.SearchAsync<Person>(request); //if (!searchResponse.IsValid) // throw new Exception("Failed to search for any documents (using aggregation)"); //// TODO - Search with aggregation to get average age //// Delete document //var deleteDocumentResponse = await client.DeleteAsync(indexName, indexResponse.Id); //if (!deleteDocumentResponse.IsValid || deleteDocumentResponse.Result != Result.Deleted) // throw new Exception($"Failed to delete document with ID {indexResponse.Id}"); //// Delete index //var deleteIndexResponse = await client.IndexManagement.DeleteAsync(new Elastic.Clients.Elasticsearch.IndexManagement.DeleteRequest(indexName)); //if (!deleteIndexResponse.IsValid) // throw new Exception($"Failed to delete index {indexName}"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct SByte : IComparable, IConvertible, IFormattable, IComparable<SByte>, IEquatable<SByte> { private sbyte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 127. public const sbyte MaxValue = (sbyte)0x7F; // The minimum value that a Byte may represent: -128. public const sbyte MinValue = unchecked((sbyte)0x80); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type SByte, this method throws an ArgumentException. // public int CompareTo(Object obj) { if (obj == null) { return 1; } if (!(obj is SByte)) { throw new ArgumentException(SR.Arg_MustBeSByte); } return m_value - ((SByte)obj).m_value; } public int CompareTo(SByte value) { return m_value - value; } // Determines whether two Byte objects are equal. public override bool Equals(Object obj) { if (!(obj is SByte)) { return false; } return m_value == ((SByte)obj).m_value; } [NonVersionable] public bool Equals(SByte obj) { return m_value == obj; } // Gets a hash code for this instance. public override int GetHashCode() { return ((int)m_value ^ (int)m_value << 8); } // Provides a string representation of a byte. public override String ToString() { return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { return ToString(format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { return ToString(format, NumberFormatInfo.GetInstance(provider)); } private String ToString(String format, NumberFormatInfo info) { if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { uint temp = (uint)(m_value & 0x000000FF); return Number.FormatUInt32(temp, format, info); } return Number.FormatInt32(m_value, format, info); } [CLSCompliant(false)] public static sbyte Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static sbyte Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static sbyte Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses a signed byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // [CLSCompliant(false)] public static sbyte Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static sbyte Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static sbyte Parse(String s, NumberStyles style, NumberFormatInfo info) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsReadOnlySpan(), style, info); } private static sbyte Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { int i = 0; try { i = Number.ParseInt32(s, style, info); } catch (OverflowException e) { throw new OverflowException(SR.Overflow_SByte, e); } if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || i > Byte.MaxValue) { throw new OverflowException(SR.Overflow_SByte); } return (sbyte)i; } if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_SByte); return (sbyte)i; } [CLSCompliant(false)] public static bool TryParse(String s, out SByte result) { if (s == null) { result = 0; return false; } return TryParse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } [CLSCompliant(false)] public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out SByte result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result); } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan<char> s, out sbyte result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out SByte result) { result = 0; int i; if (!Number.TryParseInt32(s, style, info, out i)) { return false; } if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || i > Byte.MaxValue) { return false; } result = (sbyte)i; return true; } if (i < MinValue || i > MaxValue) { return false; } result = (sbyte)i; return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.SByte; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return m_value; } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return m_value; } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "SByte", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Logging; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.Project; using Clipboard = System.Windows.Forms.Clipboard; using Task = System.Threading.Tasks.Task; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; using VsMenus = Microsoft.VisualStudioTools.Project.VsMenus; namespace Microsoft.PythonTools.Project { /// <summary> /// Represents an interpreter as a node in the Solution Explorer. /// </summary> [ComVisible(true)] internal class InterpretersNode : HierarchyNode { private readonly IInterpreterRegistryService _interpreterService; internal readonly IPythonInterpreterFactory _factory; internal readonly IPackageManager _packageManager; private readonly bool _isReference; private readonly bool _canDelete, _canRemove; private readonly string _captionSuffix; private bool _suppressPackageRefresh; private bool _checkedItems, _checkingItems, _disposed; internal readonly string _absentId; internal readonly bool _isGlobalDefault; public static readonly object InstallPackageLockMoniker = new object(); public InterpretersNode( PythonProjectNode project, IPythonInterpreterFactory factory, bool isInterpreterReference, bool canDelete, bool isGlobalDefault = false, bool? canRemove = null ) : base(project, MakeElement(project)) { ExcludeNodeFromScc = true; _interpreterService = project.Site.GetComponentModel().GetService<IInterpreterRegistryService>(); _factory = factory; _isReference = isInterpreterReference; _canDelete = canDelete; _isGlobalDefault = isGlobalDefault; _canRemove = canRemove.HasValue ? canRemove.Value : !isGlobalDefault; _captionSuffix = isGlobalDefault ? Strings.GlobalDefaultSuffix : ""; var interpreterOpts = project.Site.GetComponentModel().GetService<IInterpreterOptionsService>(); _packageManager = interpreterOpts?.GetPackageManagers(factory).FirstOrDefault(); if (_packageManager != null) { _packageManager.InstalledPackagesChanged += InstalledPackagesChanged; _packageManager.EnableNotifications(); } } private InterpretersNode(PythonProjectNode project, string id) : base(project, MakeElement(project)) { _absentId = id; _canRemove = true; _captionSuffix = Strings.MissingSuffix; } public static InterpretersNode CreateAbsentInterpreterNode(PythonProjectNode project, string id) { return new InterpretersNode(project, id); } public override int MenuCommandId { get { return PythonConstants.EnvironmentMenuId; } } public override Guid MenuGroupId { get { return GuidList.guidPythonToolsCmdSet; } } private static ProjectElement MakeElement(PythonProjectNode project) { return new VirtualProjectElement(project); } public override void Close() { if (!_disposed) { if (_packageManager != null) { _packageManager.InstalledPackagesChanged -= InstalledPackagesChanged; } } _disposed = true; base.Close(); } private void InstalledPackagesChanged(object sender, EventArgs e) { RefreshPackages(); } private void RefreshPackages() { RefreshPackagesAsync(_packageManager) .SilenceException<OperationCanceledException>() .HandleAllExceptions(ProjectMgr.Site, GetType()) .DoNotWait(); } private async Task RefreshPackagesAsync(IPackageManager packageManager) { if (_suppressPackageRefresh || packageManager == null) { return; } bool prevChecked = _checkedItems; // Use _checkingItems to prevent the expanded state from // disappearing too quickly. _checkingItems = true; _checkedItems = true; var packages = new Dictionary<string, PackageSpec>(); foreach (var p in await packageManager.GetInstalledPackagesAsync(CancellationToken.None)) { packages[p.FullSpec] = p; } await ProjectMgr.Site.GetUIThread().InvokeAsync(() => { if (ProjectMgr == null || ProjectMgr.IsClosed) { return; } try { var logger = ProjectMgr.Site.GetPythonToolsService().Logger; if (logger != null) { foreach (var p in packages) { logger.LogEvent(PythonLogEvent.PythonPackage, new PackageInfo {Name = p.Value.Name.ToLowerInvariant()}); } } } catch (Exception ex) { Debug.Fail(ex.ToUnhandledExceptionMessage(GetType())); } bool anyChanges = false; var existing = AllChildren.OfType<InterpretersPackageNode>().ToDictionary(c => c.Url); // remove the nodes which were uninstalled. foreach (var keyValue in existing) { if (!packages.Remove(keyValue.Key)) { RemoveChild(keyValue.Value); anyChanges = true; } } // add the new nodes foreach (var p in packages.OrderBy(kv => kv.Key)) { AddChild(new InterpretersPackageNode(ProjectMgr, p.Value)); anyChanges = true; } _checkingItems = false; ProjectMgr.OnInvalidateItems(this); if (!prevChecked) { if (anyChanges) { ProjectMgr.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Expandable, 0); } if (ProjectMgr.ParentHierarchy != null) { ExpandItem(EXPANDFLAGS.EXPF_CollapseFolder); } } }); } /// <summary> /// Disables the file watcher. This function may be called as many times /// as you like, but it only requires one call to /// <see cref="ResumeWatching"/> to re-enable the watcher. /// </summary> public void StopWatching() { _suppressPackageRefresh = true; } /// <summary> /// Enables the file watcher, regardless of how many times /// <see cref="StopWatching"/> was called. If the file watcher was /// enabled successfully, the list of packages is updated. /// </summary> public void ResumeWatching() { _suppressPackageRefresh = false; RefreshPackagesAsync(_packageManager) .SilenceException<OperationCanceledException>() .HandleAllExceptions(ProjectMgr.Site, GetType()) .DoNotWait(); } public override Guid ItemTypeGuid { get { return PythonConstants.InterpreterItemTypeGuid; } } internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (cmdGroup == VsMenus.guidStandardCommandSet2K) { switch ((VsCommands2K)cmd) { case CommonConstants.OpenFolderInExplorerCmdId: Process.Start(new ProcessStartInfo { FileName = _factory.Configuration.GetPrefixPath(), Verb = "open", UseShellExecute = true }); return VSConstants.S_OK; } } if (cmdGroup == ProjectMgr.SharedCommandGuid) { switch ((SharedCommands)cmd) { case SharedCommands.OpenCommandPromptHere: var pyProj = ProjectMgr as PythonProjectNode; if (pyProj != null && _factory != null && _factory.Configuration != null) { return pyProj.OpenCommandPrompt( _factory.Configuration.GetPrefixPath(), _factory.Configuration, _factory.Configuration.Description ); } break; case SharedCommands.CopyFullPath: Clipboard.SetText(_factory.Configuration.InterpreterPath); return VSConstants.S_OK; } } return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut); } public new PythonProjectNode ProjectMgr { get { return (PythonProjectNode)base.ProjectMgr; } } internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject) { // Interpreter and InterpreterReference can both be removed from // the project, but the default environment cannot return _canRemove; } else if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) { // Only Interpreter can be deleted. return _canDelete; } return false; } public override bool Remove(bool removeFromStorage) { // If _canDelete, a prompt has already been shown by VS. return Remove(removeFromStorage, !_canDelete); } private bool Remove(bool removeFromStorage, bool showPrompt) { if (!_canRemove || (removeFromStorage && !_canDelete)) { // Prevent the environment from being deleted or removed if not // supported. throw new NotSupportedException(); } if (showPrompt && !Utilities.IsInAutomationFunction(ProjectMgr.Site)) { string message = !removeFromStorage ? Strings.EnvironmentRemoveConfirmation.FormatUI(Caption) : _factory == null ? Strings.EnvironmentDeleteConfirmation_NoPath.FormatUI(Caption) : Strings.EnvironmentDeleteConfirmation.FormatUI(Caption, _factory.Configuration.GetPrefixPath()); int res = VsShellUtilities.ShowMessageBox( ProjectMgr.Site, string.Empty, message, OLEMSGICON.OLEMSGICON_WARNING, OLEMSGBUTTON.OLEMSGBUTTON_OKCANCEL, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); if (res != 1) { return false; } } //Make sure we can edit the project file if (!ProjectMgr.QueryEditProjectFile(false)) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } if (!string.IsNullOrEmpty(_absentId)) { Debug.Assert(!removeFromStorage, "Cannot remove absent environment from storage"); ProjectMgr.RemoveInterpreterFactory(_absentId); return true; } if (_factory == null) { Debug.Fail("Attempted to remove null factory from project"); return true; } ProjectMgr.RemoveInterpreter(_factory, !_isReference && removeFromStorage && _canDelete); return true; } /// <summary> /// Show interpreter display (description and version). /// </summary> public override string Caption { get { if (!string.IsNullOrEmpty(_absentId)) { string company, tag; if (CPythonInterpreterFactoryConstants.TryParseInterpreterId(_absentId, out company, out tag)) { if (company == PythonRegistrySearch.PythonCoreCompany) { company = "Python"; } return "{0} {1}{2}".FormatUI(company, tag, _captionSuffix); } return _absentId + _captionSuffix; } if (_factory == null) { Debug.Fail("null factory in interpreter node"); return "(null)"; } return _factory.Configuration.Description + _captionSuffix; } } /// <summary> /// Prevent editing the description /// </summary> public override string GetEditLabel() { return null; } protected override VSOVERLAYICON OverlayIconIndex { get { if (!Directory.Exists(Url)) { return (VSOVERLAYICON)__VSOVERLAYICON2.OVERLAYICON_NOTONDISK; } else if (_isReference) { return VSOVERLAYICON.OVERLAYICON_SHORTCUT; } return base.OverlayIconIndex; } } protected override bool SupportsIconMonikers { get { return true; } } protected override ImageMoniker GetIconMoniker(bool open) { if (_factory == null || !_factory.Configuration.IsAvailable()) { // TODO: Find a better icon return KnownMonikers.DocumentWarning; } else if (ProjectMgr.ActiveInterpreter == _factory) { return KnownMonikers.ActiveEnvironment; } // TODO: Change to PYEnvironment return KnownMonikers.DockPanel; } /// <summary> /// Interpreter node cannot be dragged. /// </summary> protected internal override string PrepareSelectedNodesForClipBoard() { return null; } /// <summary> /// Disable Copy/Cut/Paste commands on interpreter node. /// </summary> internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) { if (cmdGroup == VsMenus.guidStandardCommandSet2K) { switch ((VsCommands2K)cmd) { case CommonConstants.OpenFolderInExplorerCmdId: result = QueryStatusResult.SUPPORTED; if (_factory != null && Directory.Exists(_factory.Configuration.GetPrefixPath())) { result |= QueryStatusResult.ENABLED; } return VSConstants.S_OK; } } if (cmdGroup == GuidList.guidPythonToolsCmdSet) { switch (cmd) { case PythonConstants.ActivateEnvironment: result |= QueryStatusResult.SUPPORTED; if (_factory != null && _factory.Configuration.IsAvailable() && ProjectMgr.ActiveInterpreter != _factory && Directory.Exists(_factory.Configuration.GetPrefixPath()) ) { result |= QueryStatusResult.ENABLED; } return VSConstants.S_OK; case PythonConstants.InstallPythonPackage: result |= QueryStatusResult.SUPPORTED; if (_factory != null && _factory.Configuration.IsAvailable() && Directory.Exists(_factory.Configuration.GetPrefixPath()) ) { result |= QueryStatusResult.ENABLED; } return VSConstants.S_OK; case PythonConstants.InstallRequirementsTxt: result |= QueryStatusResult.SUPPORTED; if (_factory != null && _factory.IsRunnable() && File.Exists(PathUtils.GetAbsoluteFilePath(ProjectMgr.ProjectHome, "requirements.txt"))) { result |= QueryStatusResult.ENABLED; } return VSConstants.S_OK; case PythonConstants.GenerateRequirementsTxt: result |= QueryStatusResult.SUPPORTED; if (_factory != null && _factory.Configuration.IsAvailable()) { result |= QueryStatusResult.ENABLED; } return VSConstants.S_OK; case PythonConstants.OpenInteractiveForEnvironment: result |= QueryStatusResult.SUPPORTED; if (_factory != null && _factory.Configuration.IsAvailable() && File.Exists(_factory.Configuration.InterpreterPath) ) { result |= QueryStatusResult.ENABLED; } return VSConstants.S_OK; } } if (cmdGroup == ProjectMgr.SharedCommandGuid) { switch ((SharedCommands)cmd) { case SharedCommands.OpenCommandPromptHere: result |= QueryStatusResult.SUPPORTED; if (_factory != null && _factory.Configuration.IsAvailable() && Directory.Exists(_factory.Configuration.GetPrefixPath()) && File.Exists(_factory.Configuration.InterpreterPath)) { result |= QueryStatusResult.ENABLED; } return VSConstants.S_OK; case SharedCommands.CopyFullPath: result |= QueryStatusResult.SUPPORTED; if (_factory != null && _factory.Configuration.IsAvailable() && Directory.Exists(_factory.Configuration.GetPrefixPath()) && File.Exists(_factory.Configuration.InterpreterPath)) { result |= QueryStatusResult.ENABLED; } return VSConstants.S_OK; } } return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result); } public override string Url { get { if (!string.IsNullOrEmpty(_absentId)) { return "UnknownInterpreter\\{0}".FormatInvariant(_absentId); } if (_factory == null) { Debug.Fail("null factory in interpreter node"); return "UnknownInterpreter"; } if (!PathUtils.IsValidPath(_factory.Configuration.GetPrefixPath())) { return "UnknownInterpreter\\{0}".FormatInvariant(_factory.Configuration.Id); } return _factory.Configuration.GetPrefixPath(); } } /// <summary> /// Defines whether this node is valid node for painting the interpreter /// icon. /// </summary> protected override bool CanShowDefaultIcon() { return true; } public override bool CanAddFiles { get { return false; } } protected override NodeProperties CreatePropertiesObject() { return new InterpretersNodeProperties(this); } public override object GetProperty(int propId) { if (propId == (int)__VSHPROPID.VSHPROPID_Expandable) { if (_packageManager == null) { // No package manager, so we are not expandable return false; } if (!_checkedItems) { // We haven't checked if we have files on disk yet, report // that we can expand until we do. // We do this lazily so we don't need to spawn a process for // each interpreter on project load. ThreadPool.QueueUserWorkItem(_ => RefreshPackages()); return true; } else if (_checkingItems) { // Still checking, so keep reporting true. return true; } } return base.GetProperty(propId); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using GeoAPI.Geometries; // The Original Code is from a code project example: // http://www.codeproject.com/KB/recipes/fortunevoronoi.aspx // which is protected under the Code Project Open License // http://www.codeproject.com/info/cpol10.aspx namespace DotSpatial.NTSExtension.Voronoi { /// <summary> /// A vector class, implementing all interesting features of vectors /// </summary> public struct Vector2 { #region Fields /// <summary> /// This double controls the test for equality so that values that are smaller than this value will be considered equal. /// </summary> public static double Tolerance; /// <summary> /// The x coordinate /// </summary> public readonly double X; /// <summary> /// The y coordinate /// </summary> public readonly double Y; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Vector2"/> struct by reading a long array of vertices and assigning the vector based on that. /// </summary> /// <param name="xyvertices">Vertices to assign.</param> /// <param name="offset">Offset that indicates where the x value is.</param> public Vector2(double[] xyvertices, int offset) { X = xyvertices[offset]; Y = xyvertices[offset + 1]; } /// <summary> /// Initializes a new instance of the <see cref="Vector2"/> struct. /// </summary> /// <param name="x">The elements of the vector</param> public Vector2(params double[] x) { X = x[0]; Y = x[1]; } #endregion #region Properties /// <summary> /// Gets the dot product of this vector with itself /// </summary> public double SquaredLength => this * this; #endregion #region Operators /// <summary> /// Calculates the vector sum of these two vectors /// </summary> /// <param name="a">One vector to add</param> /// <param name="b">The second vector to add</param> /// <returns>The vector sum of the specified vectors</returns> public static Vector2 operator +(Vector2 a, Vector2 b) { return new Vector2(a.X + b.X, a.Y + b.Y); } /// <summary> /// Overrides equality to use the tolerant equality /// </summary> /// <param name="a">First vector to check.</param> /// <param name="b">Second vector to check.</param> /// <returns>True, if both are equal.</returns> public static bool operator ==(Vector2 a, Vector2 b) { return a.Equals(b); } /// <summary> /// Overrides equality to use the tolerant equality test /// </summary> /// <param name="a">First vector to check.</param> /// <param name="b">Second vector to check.</param> /// <returns>True, if both are not equal.</returns> public static bool operator !=(Vector2 a, Vector2 b) { return !a.Equals(b); } /// <summary> /// Get the scalar product of two vectors /// </summary> /// <param name="a">First vector to multiply.</param> /// <param name="b">Second vector to multiply.</param> /// <returns>The resulting value.</returns> public static double operator *(Vector2 a, Vector2 b) { return (a.X * b.X) + (a.Y * b.Y); } /// <summary> /// Multiplies the vector by a scalar /// </summary> /// <param name="a">The vector to modify</param> /// <param name="scale">The double scale to multiply</param> /// <returns>A new Vector2</returns> public static Vector2 operator *(Vector2 a, double scale) { return new Vector2(a.X * scale, a.Y * scale); } /// <summary> /// Multiplies the vector by a scalar. /// </summary> /// <param name="scale">The double scale to multiply.</param> /// <param name="a">The vector to modify.</param> /// <returns>A new Vector2.</returns> public static Vector2 operator *(double scale, Vector2 a) { return new Vector2(a.X * scale, a.Y * scale); } /// <summary> /// Calculates the vector sum of these two vectors /// </summary> /// <param name="a">One vector to add</param> /// <param name="b">The second vector to add</param> /// <returns>The vector sum of the specified vectors</returns> public static Vector2 operator -(Vector2 a, Vector2 b) { return new Vector2(a.X - b.X, a.Y - b.Y); } #endregion #region Methods /// <summary> /// True if any of the double values is not a number. /// </summary> /// <returns>bool if either X or Y is nan.</returns> public bool ContainsNan() { return double.IsNaN(X) || double.IsNaN(Y); } /// <summary> /// Calculates the euclidean distance from this cell to another /// </summary> /// <param name="other">Second cell for distance calculation.</param> /// <returns>Vector2 stuff</returns> public double Distance(Vector2 other) { double dx = X - other.X; double dy = Y - other.Y; return Math.Sqrt((dx * dx) + (dy * dy)); } /// <summary> /// Compares this vector with another one. /// </summary> /// <param name="obj">Selecond vector for comparing.</param> /// <returns>True, if the vectors are equal by tolerance.</returns> public override bool Equals(object obj) { if (obj == null) return false; Vector2 b = (Vector2)obj; return TolerantEqual(X, b.X) && TolerantEqual(Y, b.Y); } /// <summary> /// Retrieves a hashcode that is dependent on the elements. /// </summary> /// <returns>The hashcode</returns> public override int GetHashCode() { return X.GetHashCode() * Y.GetHashCode(); } /// <summary> /// Transforms the vector into a coordinate with an x and y value. /// </summary> /// <returns>Returns a coordinate with this vectors X and Y values.</returns> public Coordinate ToCoordinate() { return new Coordinate(X, Y); } /// <summary> /// Convert the vector into a reconstructable string representation /// </summary> /// <returns>A string from which the vector can be rebuilt</returns> public override string ToString() { return "(" + X + "," + Y + ")"; } private static bool TolerantEqual(double a, double b) { // both being NaN counts as equal if (double.IsNaN(a) && double.IsNaN(b)) return true; // If one is NaN but the other isn't, then the vector is not equal if (double.IsNaN(a) || double.IsNaN(b)) return false; // Allow the default, operating system controlled equality check for two doubles if (Tolerance == 0) return a == b; // If a tolerance has been specified, check equality using that tolerance level. return Math.Abs(a - b) <= Tolerance; } #endregion } }
#region Header // Revit MEP API sample application // // Copyright (C) 2007-2021 by Jeremy Tammik, Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software // 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. #endregion // Header #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Mechanical; using Autodesk.Revit.UI; #endregion // Namespaces namespace AdnRme { [Transaction( TransactionMode.Manual )] class CmdAssignFlowToTerminals : IExternalCommand { #region Get Terminals Per Space /// <summary> /// Helper class for sorting the spaces by space number before listing them /// </summary> class NumericalComparer : IComparer<string> { public int Compare( string x, string y ) { return int.Parse( x ) - int.Parse( y ); } } static Dictionary<string, List<FamilyInstance>> GetTerminalsPerSpace( Document doc ) { FilteredElementCollector terminals = Util.GetSupplyAirTerminals( doc ); Dictionary<string,List<FamilyInstance>> terminalsPerSpace = new Dictionary<string,List<FamilyInstance>>(); foreach( FamilyInstance terminal in terminals ) { //string roomNr = terminal.Room.Number; string spaceNr = terminal.Space.Number; // changed Room to Space if( !terminalsPerSpace.ContainsKey( spaceNr ) ) { terminalsPerSpace.Add( spaceNr, new List<FamilyInstance>() ); } terminalsPerSpace[spaceNr].Add( terminal ); } List<string> keys = new List<string>( terminalsPerSpace.Keys ); keys.Sort( new NumericalComparer() ); string ids; List<FamilyInstance> spaceTerminals; int n, nTerminals = 0; foreach( string key in keys ) { spaceTerminals = terminalsPerSpace[key]; n = spaceTerminals.Count; ids = Util.IdList( spaceTerminals ); Debug.WriteLine( string.Format( "Space {0} contains {1} air terminal{2}{3} {4}", key, n, Util.PluralSuffix( n ), Util.DotOrColon( n ), ids ) ); nTerminals += n; } n = terminalsPerSpace.Count; Debug.WriteLine( string.Format( "Processing a total of {0} space{1} containing {2} air terminal{3}.", n, Util.PluralSuffix( n ), nTerminals, Util.PluralSuffix( nTerminals ) ) ); return terminalsPerSpace; } #endregion // Get Terminals Per Space #region AssignFlowToTerminals static double RoundFlowTo( double a ) { a = a / Const.RoundTerminalFlowTo; a = Math.Round( a, 0, MidpointRounding.AwayFromZero ); a = a * Const.RoundTerminalFlowTo; return a; } static void AssignFlowToTerminals( List<FamilyInstance> terminals, double flow ) { foreach( FamilyInstance terminal in terminals ) { Parameter p = Util.GetTerminalFlowParameter( terminal ); p.Set( flow ); } } static void AssignFlowToTerminalsForSpace( List<FamilyInstance> terminals, Space space ) { Debug.Assert( null != terminals, "expected valid list of terminals" ); int n = terminals.Count; double calculatedSupplyAirFlow = Util.GetSpaceParameterValue( space, Bip.CalculatedSupplyAirFlow, ParameterName.CalculatedSupplyAirFlow ); double flowCfm = calculatedSupplyAirFlow * Const.SecondsPerMinute; double flowCfmPerOutlet = flowCfm / n; double flowCfmPerOutletRounded = RoundFlowTo( flowCfmPerOutlet ); double flowPerOutlet = flowCfmPerOutletRounded / Const.SecondsPerMinute; string format = "Space {0} has calculated supply airflow {1} f^3/s = {2} CFM and {3} terminal{4}" + " --> flow {5} CFM per terminal, rounded to {6} = {7} f^3/s"; Debug.WriteLine( string.Format( format, space.Number, Util.RealString( calculatedSupplyAirFlow ), Util.RealString( flowCfm ), n, Util.PluralSuffix( n ), Util.RealString( flowCfmPerOutlet ), Util.RealString( flowCfmPerOutletRounded ), Util.RealString( flowPerOutlet ) ) ); AssignFlowToTerminals( terminals, flowPerOutlet ); } #endregion // AssignFlowToTerminals #region Execute Command public Result Execute( ExternalCommandData commandData, ref String message, ElementSet elements ) { try { WaitCursor waitCursor = new WaitCursor(); UIApplication uiapp = commandData.Application; Document doc = uiapp.ActiveUIDocument.Document; // // 1. determine air terminals for each space. // determine the relationship between all air terminals and all spaces: // extract and group all air terminals per space // (key=space, val=set of air terminals) // Debug.WriteLine( "\nDetermining terminals per space..." ); Dictionary<string, List<FamilyInstance>> terminalsPerSpace = GetTerminalsPerSpace( doc ); // // 2. assign flow to the air terminals depending on the space's calculated supply air flow. // //ElementFilterIterator it = doc.get_Elements( typeof( Room ) ); // 2008 //ElementIterator it = doc.get_Elements( typeof( Space ) ); // 2009 //List<Element> spaces = new List<Element>(); // 2009 //doc.get_Elements( typeof( Space ), spaces ); // 2009 //FilteredElementCollector collector = new FilteredElementCollector( doc ); //collector.OfClass( typeof( Space ) ); //IList<Element> spaces = collector.ToElements(); using( Transaction tx = new Transaction( doc ) ) { List<Space> spaces = Util.GetSpaces( doc ); int n = spaces.Count; string s = "{0} of " + n.ToString() + " spaces processed..."; string caption = "Assign Flow to Terminals"; tx.Start( caption ); using( ProgressForm pf = new ProgressForm( caption, s, n ) ) { foreach( Space space in spaces ) { if( terminalsPerSpace.ContainsKey( space.Number ) ) { AssignFlowToTerminalsForSpace( terminalsPerSpace[space.Number], space ); } pf.Increment(); } } tx.Commit(); Debug.WriteLine( "Completed." ); return Result.Succeeded; } } catch( Exception ex ) { message = ex.Message; return Result.Failed; } } #endregion // Execute Command } }
/****************************************************************************** * The MIT License * Copyright (c) 2007 Novell Inc., 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. *******************************************************************************/ // Authors: // Thomas Wiest (twiest@novell.com) // Rusty Howell (rhowell@novell.com) // // (C) Novell Inc. using System; using System.Collections.Generic; using System.Text; namespace System.Management.Internal { /// <summary> /// The PROPERTY element defines a single (non-array) CIM Property that is not a reference. /// It contains a single value of the Property. /// </summary> internal class CimProperty : CimClassMember { /* <!ELEMENT PROPERTY (QUALIFIER*,VALUE?)> * <!ATTLIST PROPERTY * %CIMName; * %CIMType; #REQUIRED * %ClassOrigin; * %Propagated; * xml:lang NMTOKEN #IMPLIED> * */ private string _value = null; #region Constructors /// <summary> /// Creates a new property with the given name and type /// </summary> /// <param name="name"></param> /// <param name="type"></param> public CimProperty(CimName name, CimType type) { Name = name; Type = type; } #endregion #region Properties /// <summary> /// Gets or sets the value of the property /// </summary> public string Value { get { if (_value == null) return string.Empty; return _value; } set { _value = value; } } /// <summary> /// Returns true if the property has a key qualifier and the key qualifier is set to 'true' /// </summary> public bool IsKeyProperty { get { //Changed for MONO for (int i = 0; i < Qualifiers.Count; i++) { CimQualifier curQual = Qualifiers[i]; if ( (curQual.Name.ToString().Equals("key", StringComparison.OrdinalIgnoreCase)) && (curQual.Type == CimType.BOOLEAN) && (curQual.Values[0].Equals("true", StringComparison.OrdinalIgnoreCase)) ) return true; } return false; } } /// <summary> /// Returns true if the property has a required qualifier and the required qualifier is set to 'true' /// </summary> public bool IsRequiredProperty { get { //Changed for MONO for (int i = 0; i < Qualifiers.Count; i++) { CimQualifier curQual = Qualifiers[i]; if ((curQual.Name.ToString().Equals("required", StringComparison.OrdinalIgnoreCase)) && (curQual.Type == CimType.BOOLEAN) && (curQual.Values[0].Equals("true", StringComparison.OrdinalIgnoreCase))) return true; } return false; } } /// <summary> /// Returns true if the property name, type, and value are set /// </summary> public bool IsSet { get { return (Name.IsSet && Type.IsSet && (_value != string.Empty)); } } #endregion #region Methods /// <summary> /// Converts the property to a CimKeyBinding /// </summary> /// <returns></returns> public CimKeyBinding ToCimKeyBinding() { CimKeyValue tmpCKV = new CimKeyValue(); tmpCKV.ValueType = "string"; tmpCKV.Value = this.Value; return new CimKeyBinding(this.Name, tmpCKV); } #region Equals, operator== , operator!= /// <summary> /// Deep compare of two CimProperty objects /// </summary> /// <param name="obj"></param> /// <returns>returns true if the objects are equal</returns> public override bool Equals(object obj) { if ((obj == null) || !(obj is CimProperty)) { return false; } return (this == (CimProperty)obj); } /// <summary> /// Deep compare of two CimProperty objects /// </summary> /// <param name="val1"></param> /// <param name="val2"></param> /// <returns>Returns true if the properties are equal</returns> public static bool operator ==(CimProperty val1, CimProperty val2) { if (((object)val1 == null) || ((object)val2 == null)) { if (((object)val1 == null) && ((object)val2 == null)) { return true; } return false; } //Add code here if ((val1.Name != val2.Name) || (val1.Type != val2.Type) || (val1.ClassOrigin != val2.ClassOrigin)) return false; if (val1.IsPropagated == val2.IsPropagated) return false; if (val1.Qualifiers != val2.Qualifiers) return false; if (val1.Value.ToLower() != val2.Value.ToLower()) return false; return true; } /// <summary> /// Deep compare of two CimProperty objects /// </summary> /// <param name="val1"></param> /// <param name="val2"></param> /// <returns>Returns true if the properties are not equal</returns> public static bool operator !=(CimProperty val1, CimProperty val2) { return !(val1 == val2); } #endregion #endregion } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; using System; using System.Reflection; public class TestResults : EditorWindow { string previousScene; Vector2 scrollPosition; List<StepList> tests; bool lastFrameWasCompiling = false; bool wantsToRunTests = false; bool autorunTests = true; bool showGreen = true; bool showYellow = true; bool showRed = true; float slowTickInterval = 0.1f; float slowTickTimeout = 0.0f; float startTime; float finishTime; [MenuItem("Window/Unit Testing")] static void Init() { TestResults window = (TestResults)EditorWindow.GetWindow(typeof(TestResults), false, "Test Results"); window.minSize = new Vector2(256, 24); } void OnGUI() { EditorGUILayout.BeginVertical(); EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button("Run Tests", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { wantsToRunTests = true; } GUILayout.Space(6); autorunTests = GUILayout.Toggle(autorunTests, "Test After Every Compile", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)); GUILayout.Label(""); GUILayout.Label("Finished in " + (finishTime - startTime) + " seconds", GUILayout.ExpandWidth(false)); GUI.color = showGreen ? Step.green : Step.green / 1.3f; showGreen = GUILayout.Toggle(showGreen, "" + CountTests(Step.green), EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)); GUI.color = showYellow ? Step.yellow : Step.yellow / 1.3f; showYellow = GUILayout.Toggle(showYellow, "" + CountTests(Step.yellow), EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)); GUI.color = showRed ? Step.red : Step.red / 1.4f; showRed = GUILayout.Toggle(showRed, "" + CountTests(Step.red), EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)); GUI.color = Color.white; EditorGUILayout.EndHorizontal(); scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); if (tests != null) { foreach (StepList test in tests) { if (test.severity == Step.red && showRed || test.severity == Step.yellow && showYellow || test.severity == Step.green && showGreen) { Color oldColor = GUI.color; GUI.color = test.severity; EditorGUILayout.BeginHorizontal(); test.expanded = EditorGUILayout.Foldout(test.expanded, "if it " + test.type + ","); EditorGUILayout.LabelField("", GUILayout.Width(GUI.skin.label.CalcSize(new GUIContent(test.type + " : ")).x - 30)); EditorGUILayout.LabelField(test.reason, EditorStyles.whiteLabel, GUILayout.Width(GUI.skin.label.CalcSize(new GUIContent(test.reason)).x)); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); if (test.expanded) { foreach (Step step in test.steps) { DrawStep(step.status, step.step); } } GUI.color = oldColor; } } } EditorGUILayout.EndScrollView(); EditorGUILayout.EndVertical(); GUI.color = Color.white; } int CountTests(Color color) { int count = 0; if (tests != null) { foreach (StepList test in tests) { if (test.severity == color) { count++; } } } return count; } void DrawStep(Color color, string step) { Color oldColor = GUI.color; GUI.color = color; foreach (string line in step.Split('\n')) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("", GUILayout.Width(30)); EditorGUILayout.SelectableLabel(line, EditorStyles.whiteLabel, GUILayout.Width(GUI.skin.label.CalcSize(new GUIContent(step)).x), GUILayout.Height(14)); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); } GUI.color = oldColor; } void Update() { if (!EditorApplication.isCompiling && lastFrameWasCompiling && autorunTests) { wantsToRunTests = true; } if (wantsToRunTests && CanRunTests()) { RunTests(); } RunsTests fixture = FindObjectOfType(typeof(RunsTests)) as RunsTests; if (fixture != null) { if (fixture.finished) { SpinDown(); } else if (fixture.tests.Count != 0) { tests = fixture.tests; } } slowTickTimeout += 0.01f; while (slowTickTimeout > slowTickInterval) { slowTickTimeout -= slowTickInterval; Repaint(); } lastFrameWasCompiling = EditorApplication.isCompiling; } bool CanRunTests() { return (!EditorApplication.isCompiling && !EditorApplication.isPlaying && !CheckForCompilerErrors()); } void RunTests() { CheckForCompilerErrors(); startTime = Time.time; wantsToRunTests = false; tests = new List<StepList>(); previousScene = EditorApplication.currentScene; EditorApplication.SaveScene(); EditorApplication.OpenScene("Assets/Scenes/packages/invisibledrygoods/GivenWhenUnity/TestRunner.unity"); if (EditorApplication.currentScene == previousScene) { EditorApplication.OpenScene("Assets/Scenes/TestRunner.unity"); } EditorApplication.isPlaying = true; } void SpinDown() { finishTime = Time.time; EditorApplication.OpenScene(previousScene); EditorApplication.isPlaying = false; } bool CheckForCompilerErrors() { Assembly assembly = Assembly.GetAssembly(typeof(SceneView)); Type logEntries = assembly.GetType("UnityEditorInternal.LogEntries"); logEntries.GetMethod("Clear").Invoke(new object(), null); int count = (int)logEntries.GetMethod("GetCount").Invoke(new object(), null); return count != 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; using System.Collections.Generic; using Internal.IL; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.IL.Stubs { public class ILCodeStream { private const int StartOffsetNotSet = -1; private struct LabelAndOffset { public readonly ILCodeLabel Label; public readonly int Offset; public LabelAndOffset(ILCodeLabel label, int offset) { Label = label; Offset = offset; } } internal byte[] _instructions; internal int _length; internal int _startOffsetForLinking; internal ArrayBuilder<ILSequencePoint> _sequencePoints; private ArrayBuilder<LabelAndOffset> _offsetsNeedingPatching; private ILEmitter _emitter; internal ILCodeStream(ILEmitter emitter) { _instructions = Array.Empty<byte>(); _startOffsetForLinking = StartOffsetNotSet; _emitter = emitter; } internal int RelativeToAbsoluteOffset(int relativeOffset) { Debug.Assert(_startOffsetForLinking != StartOffsetNotSet); return _startOffsetForLinking + relativeOffset; } private void EmitByte(byte b) { if (_instructions.Length == _length) Array.Resize<byte>(ref _instructions, 2 * _instructions.Length + 10); _instructions[_length++] = b; } private void EmitUInt16(ushort value) { EmitByte((byte)value); EmitByte((byte)(value >> 8)); } private void EmitUInt32(int value) { EmitByte((byte)value); EmitByte((byte)(value >> 8)); EmitByte((byte)(value >> 16)); EmitByte((byte)(value >> 24)); } public void Emit(ILOpcode opcode) { if ((int)opcode > 0x100) EmitByte((byte)ILOpcode.prefix1); EmitByte((byte)opcode); } public void Emit(ILOpcode opcode, ILToken token) { Emit(opcode); EmitUInt32((int)token); } public void EmitLdc(int value) { if (-1 <= value && value <= 8) { Emit((ILOpcode)(ILOpcode.ldc_i4_0 + value)); } else if (value == (sbyte)value) { Emit(ILOpcode.ldc_i4_s); EmitByte((byte)value); } else { Emit(ILOpcode.ldc_i4); EmitUInt32(value); } } public void EmitLdArg(int index) { if (index < 4) { Emit((ILOpcode)(ILOpcode.ldarg_0 + index)); } else { Emit(ILOpcode.ldarg); EmitUInt16((ushort)index); } } public void EmitLdArga(int index) { if (index < 0x100) { Emit(ILOpcode.ldarga_s); EmitByte((byte)index); } else { Emit(ILOpcode.ldarga); EmitUInt16((ushort)index); } } public void EmitLdLoc(ILLocalVariable variable) { int index = (int)variable; if (index < 4) { Emit((ILOpcode)(ILOpcode.ldloc_0 + index)); } else if (index < 0x100) { Emit(ILOpcode.ldloc_s); EmitByte((byte)index); } else { Emit(ILOpcode.ldloc); EmitUInt16((ushort)index); } } public void EmitLdLoca(ILLocalVariable variable) { int index = (int)variable; if (index < 0x100) { Emit(ILOpcode.ldloca_s); EmitByte((byte)index); } else { Emit(ILOpcode.ldloca); EmitUInt16((ushort)index); } } public void EmitStLoc(ILLocalVariable variable) { int index = (int)variable; if (index < 4) { Emit((ILOpcode)(ILOpcode.stloc_0 + index)); } else if (index < 0x100) { Emit(ILOpcode.stloc_s); EmitByte((byte)index); } else { Emit(ILOpcode.stloc); EmitUInt16((ushort)index); } } public void Emit(ILOpcode opcode, ILCodeLabel label) { Debug.Assert(opcode == ILOpcode.br || opcode == ILOpcode.brfalse || opcode == ILOpcode.brtrue || opcode == ILOpcode.beq || opcode == ILOpcode.bge || opcode == ILOpcode.bgt || opcode == ILOpcode.ble || opcode == ILOpcode.blt || opcode == ILOpcode.bne_un || opcode == ILOpcode.bge_un || opcode == ILOpcode.bgt_un || opcode == ILOpcode.ble_un || opcode == ILOpcode.blt_un || opcode == ILOpcode.leave); Emit(opcode); _offsetsNeedingPatching.Add(new LabelAndOffset(label, _length)); EmitUInt32(4); } public void EmitSwitch(ILCodeLabel[] labels) { Emit(ILOpcode.switch_); EmitUInt32(labels.Length); int remainingBytes = labels.Length * 4; foreach (var label in labels) { _offsetsNeedingPatching.Add(new LabelAndOffset(label, _length)); EmitUInt32(remainingBytes); remainingBytes -= 4; } } public void EmitUnaligned() { Emit(ILOpcode.unaligned); EmitByte(1); } public void EmitLdInd(TypeDesc type) { switch (type.UnderlyingType.Category) { case TypeFlags.Byte: case TypeFlags.SByte: case TypeFlags.Boolean: Emit(ILOpcode.ldind_i1); break; case TypeFlags.Char: case TypeFlags.UInt16: case TypeFlags.Int16: Emit(ILOpcode.ldind_i2); break; case TypeFlags.UInt32: case TypeFlags.Int32: Emit(ILOpcode.ldind_i4); break; case TypeFlags.UInt64: case TypeFlags.Int64: Emit(ILOpcode.ldind_i8); break; case TypeFlags.Single: Emit(ILOpcode.ldind_r4); break; case TypeFlags.Double: Emit(ILOpcode.ldind_r8); break; case TypeFlags.IntPtr: case TypeFlags.UIntPtr: case TypeFlags.Pointer: case TypeFlags.FunctionPointer: Emit(ILOpcode.ldind_i); break; case TypeFlags.Array: case TypeFlags.SzArray: case TypeFlags.Class: case TypeFlags.Interface: Emit(ILOpcode.ldind_ref); break; case TypeFlags.ValueType: case TypeFlags.Nullable: case TypeFlags.SignatureMethodVariable: case TypeFlags.SignatureTypeVariable: Emit(ILOpcode.ldobj, _emitter.NewToken(type)); break; default: Debug.Fail("Unexpected TypeDesc category"); break; } } public void EmitStInd(TypeDesc type) { switch (type.UnderlyingType.Category) { case TypeFlags.Byte: case TypeFlags.SByte: case TypeFlags.Boolean: Emit(ILOpcode.stind_i1); break; case TypeFlags.Char: case TypeFlags.UInt16: case TypeFlags.Int16: Emit(ILOpcode.stind_i2); break; case TypeFlags.UInt32: case TypeFlags.Int32: Emit(ILOpcode.stind_i4); break; case TypeFlags.UInt64: case TypeFlags.Int64: Emit(ILOpcode.stind_i8); break; case TypeFlags.Single: Emit(ILOpcode.stind_r4); break; case TypeFlags.Double: Emit(ILOpcode.stind_r8); break; case TypeFlags.IntPtr: case TypeFlags.UIntPtr: case TypeFlags.Pointer: case TypeFlags.FunctionPointer: Emit(ILOpcode.stind_i); break; case TypeFlags.Array: case TypeFlags.SzArray: case TypeFlags.Class: case TypeFlags.Interface: Emit(ILOpcode.stind_ref); break; case TypeFlags.ValueType: case TypeFlags.Nullable: Emit(ILOpcode.stobj, _emitter.NewToken(type)); break; default: Debug.Fail("Unexpected TypeDesc category"); break; } } public void EmitStElem(TypeDesc type) { switch (type.UnderlyingType.Category) { case TypeFlags.Byte: case TypeFlags.SByte: case TypeFlags.Boolean: Emit(ILOpcode.stelem_i1); break; case TypeFlags.Char: case TypeFlags.UInt16: case TypeFlags.Int16: Emit(ILOpcode.stelem_i2); break; case TypeFlags.UInt32: case TypeFlags.Int32: Emit(ILOpcode.stelem_i4); break; case TypeFlags.UInt64: case TypeFlags.Int64: Emit(ILOpcode.stelem_i8); break; case TypeFlags.Single: Emit(ILOpcode.stelem_r4); break; case TypeFlags.Double: Emit(ILOpcode.stelem_r8); break; case TypeFlags.IntPtr: case TypeFlags.UIntPtr: case TypeFlags.Pointer: case TypeFlags.FunctionPointer: Emit(ILOpcode.stelem_i); break; case TypeFlags.Array: case TypeFlags.SzArray: case TypeFlags.Class: case TypeFlags.Interface: Emit(ILOpcode.stelem_ref); break; case TypeFlags.ValueType: case TypeFlags.Nullable: Emit(ILOpcode.stelem, _emitter.NewToken(type)); break; default: Debug.Fail("Unexpected TypeDesc category"); break; } } public void EmitLdElem(TypeDesc type) { switch (type.UnderlyingType.Category) { case TypeFlags.Byte: case TypeFlags.SByte: case TypeFlags.Boolean: Emit(ILOpcode.ldelem_i1); break; case TypeFlags.Char: case TypeFlags.UInt16: case TypeFlags.Int16: Emit(ILOpcode.ldelem_i2); break; case TypeFlags.UInt32: case TypeFlags.Int32: Emit(ILOpcode.ldelem_i4); break; case TypeFlags.UInt64: case TypeFlags.Int64: Emit(ILOpcode.ldelem_i8); break; case TypeFlags.Single: Emit(ILOpcode.ldelem_r4); break; case TypeFlags.Double: Emit(ILOpcode.ldelem_r8); break; case TypeFlags.IntPtr: case TypeFlags.UIntPtr: case TypeFlags.Pointer: case TypeFlags.FunctionPointer: Emit(ILOpcode.ldelem_i); break; case TypeFlags.Array: case TypeFlags.SzArray: case TypeFlags.Class: case TypeFlags.Interface: Emit(ILOpcode.ldelem_ref); break; case TypeFlags.ValueType: case TypeFlags.Nullable: Emit(ILOpcode.ldelem, _emitter.NewToken(type)); break; default: Debug.Fail("Unexpected TypeDesc category"); break; } } public void EmitLabel(ILCodeLabel label) { label.Place(this, _length); } public void BeginTry(ILExceptionRegionBuilder builder) { Debug.Assert(builder._beginTryStream == null); builder._beginTryStream = this; builder._beginTryOffset = _length; } public void EndTry(ILExceptionRegionBuilder builder) { Debug.Assert(builder._endTryStream == null); builder._endTryStream = this; builder._endTryOffset = _length; } public void BeginHandler(ILExceptionRegionBuilder builder) { Debug.Assert(builder._beginHandlerStream == null); builder._beginHandlerStream = this; builder._beginHandlerOffset = _length; } public void EndHandler(ILExceptionRegionBuilder builder) { Debug.Assert(builder._endHandlerStream == null); builder._endHandlerStream = this; builder._endHandlerOffset = _length; } internal void PatchLabels() { for (int i = 0; i < _offsetsNeedingPatching.Count; i++) { LabelAndOffset patch = _offsetsNeedingPatching[i]; Debug.Assert(patch.Label.IsPlaced); Debug.Assert(_startOffsetForLinking != StartOffsetNotSet); int offset = patch.Offset; int delta = _instructions[offset + 3] << 24 | _instructions[offset + 2] << 16 | _instructions[offset + 1] << 8 | _instructions[offset]; int value = patch.Label.AbsoluteOffset - _startOffsetForLinking - patch.Offset - delta; _instructions[offset] = (byte)value; _instructions[offset + 1] = (byte)(value >> 8); _instructions[offset + 2] = (byte)(value >> 16); _instructions[offset + 3] = (byte)(value >> 24); } } public void DefineSequencePoint(string document, int lineNumber) { // Last sequence point defined for this offset wins. if (_sequencePoints.Count > 0 && _sequencePoints[_sequencePoints.Count - 1].Offset == _length) { _sequencePoints[_sequencePoints.Count - 1] = new ILSequencePoint(_length, document, lineNumber); } else { _sequencePoints.Add(new ILSequencePoint(_length, document, lineNumber)); } } } public class ILExceptionRegionBuilder { internal ILCodeStream _beginTryStream; internal int _beginTryOffset; internal ILCodeStream _endTryStream; internal int _endTryOffset; internal ILCodeStream _beginHandlerStream; internal int _beginHandlerOffset; internal ILCodeStream _endHandlerStream; internal int _endHandlerOffset; internal ILExceptionRegionBuilder() { } internal int TryOffset => _beginTryStream.RelativeToAbsoluteOffset(_beginTryOffset); internal int TryLength => _endTryStream.RelativeToAbsoluteOffset(_endTryOffset) - TryOffset; internal int HandlerOffset => _beginHandlerStream.RelativeToAbsoluteOffset(_beginHandlerOffset); internal int HandlerLength => _endHandlerStream.RelativeToAbsoluteOffset(_endHandlerOffset) - HandlerOffset; internal bool IsDefined => _beginTryStream != null && _endTryStream != null && _beginHandlerStream != null && _endHandlerStream != null; } /// <summary> /// Represent a token. Use one of the overloads of <see cref="ILEmitter.NewToken"/> /// to create a new token. /// </summary> public enum ILToken { } /// <summary> /// Represents a local variable. Use <see cref="ILEmitter.NewLocal"/> to create a new local variable. /// </summary> public enum ILLocalVariable { } public class ILStubMethodIL : MethodIL { private readonly byte[] _ilBytes; private readonly LocalVariableDefinition[] _locals; private readonly Object[] _tokens; private readonly MethodDesc _method; private readonly ILExceptionRegion[] _exceptionRegions; private readonly MethodDebugInformation _debugInformation; private const int MaxStackNotSet = -1; private int _maxStack; public ILStubMethodIL(MethodDesc owningMethod, byte[] ilBytes, LocalVariableDefinition[] locals, Object[] tokens, ILExceptionRegion[] exceptionRegions = null, MethodDebugInformation debugInfo = null) { _ilBytes = ilBytes; _locals = locals; _tokens = tokens; _method = owningMethod; _maxStack = MaxStackNotSet; if (exceptionRegions == null) exceptionRegions = Array.Empty<ILExceptionRegion>(); _exceptionRegions = exceptionRegions; if (debugInfo == null) debugInfo = MethodDebugInformation.None; _debugInformation = debugInfo; } public ILStubMethodIL(ILStubMethodIL methodIL) { _ilBytes = methodIL._ilBytes; _locals = methodIL._locals; _tokens = methodIL._tokens; _method = methodIL._method; _debugInformation = methodIL._debugInformation; _maxStack = methodIL._maxStack; } public override MethodDesc OwningMethod { get { return _method; } } public override byte[] GetILBytes() { return _ilBytes; } public override MethodDebugInformation GetDebugInfo() { return _debugInformation; } public override int MaxStack { get { if (_maxStack == MaxStackNotSet) _maxStack = this.ComputeMaxStack(); return _maxStack; } } public override ILExceptionRegion[] GetExceptionRegions() { return _exceptionRegions; } public override bool IsInitLocals { get { return true; } } public override LocalVariableDefinition[] GetLocals() { return _locals; } public override Object GetObject(int token) { return _tokens[(token & 0xFFFFFF) - 1]; } } public class ILCodeLabel { private ILCodeStream _codeStream; private int _offsetWithinCodeStream; internal bool IsPlaced { get { return _codeStream != null; } } internal int AbsoluteOffset { get { Debug.Assert(IsPlaced); return _codeStream.RelativeToAbsoluteOffset(_offsetWithinCodeStream); } } internal ILCodeLabel() { } internal void Place(ILCodeStream codeStream, int offsetWithinCodeStream) { Debug.Assert(!IsPlaced); _codeStream = codeStream; _offsetWithinCodeStream = offsetWithinCodeStream; } } public class ILEmitter { private ArrayBuilder<ILCodeStream> _codeStreams; private ArrayBuilder<LocalVariableDefinition> _locals; private ArrayBuilder<Object> _tokens; private ArrayBuilder<ILExceptionRegionBuilder> _finallyRegions; public ILEmitter() { } public ILCodeStream NewCodeStream() { ILCodeStream stream = new ILCodeStream(this); _codeStreams.Add(stream); return stream; } private ILToken NewToken(Object value, int tokenType) { Debug.Assert(value != null); _tokens.Add(value); return (ILToken)(_tokens.Count | tokenType); } public ILToken NewToken(TypeDesc value) { return NewToken(value, 0x01000000); } public ILToken NewToken(MethodDesc value) { return NewToken(value, 0x0a000000); } public ILToken NewToken(FieldDesc value) { return NewToken(value, 0x0a000000); } public ILToken NewToken(string value) { return NewToken(value, 0x70000000); } public ILToken NewToken(MethodSignature value) { return NewToken(value, 0x11000000); } public ILLocalVariable NewLocal(TypeDesc localType, bool isPinned = false) { int index = _locals.Count; _locals.Add(new LocalVariableDefinition(localType, isPinned)); return (ILLocalVariable)index; } public ILCodeLabel NewCodeLabel() { var newLabel = new ILCodeLabel(); return newLabel; } public ILExceptionRegionBuilder NewFinallyRegion() { var region = new ILExceptionRegionBuilder(); _finallyRegions.Add(region); return region; } public MethodIL Link(MethodDesc owningMethod) { int totalLength = 0; int numSequencePoints = 0; for (int i = 0; i < _codeStreams.Count; i++) { ILCodeStream ilCodeStream = _codeStreams[i]; ilCodeStream._startOffsetForLinking = totalLength; totalLength += ilCodeStream._length; numSequencePoints += ilCodeStream._sequencePoints.Count; } byte[] ilInstructions = new byte[totalLength]; int copiedLength = 0; for (int i = 0; i < _codeStreams.Count; i++) { ILCodeStream ilCodeStream = _codeStreams[i]; ilCodeStream.PatchLabels(); Array.Copy(ilCodeStream._instructions, 0, ilInstructions, copiedLength, ilCodeStream._length); copiedLength += ilCodeStream._length; } MethodDebugInformation debugInfo = null; if (numSequencePoints > 0) { ILSequencePoint[] sequencePoints = new ILSequencePoint[numSequencePoints]; int copiedSequencePointLength = 0; for (int codeStreamIndex = 0; codeStreamIndex < _codeStreams.Count; codeStreamIndex++) { ILCodeStream ilCodeStream = _codeStreams[codeStreamIndex]; for (int sequencePointIndex = 0; sequencePointIndex < ilCodeStream._sequencePoints.Count; sequencePointIndex++) { ILSequencePoint sequencePoint = ilCodeStream._sequencePoints[sequencePointIndex]; sequencePoints[copiedSequencePointLength] = new ILSequencePoint( ilCodeStream._startOffsetForLinking + sequencePoint.Offset, sequencePoint.Document, sequencePoint.LineNumber); copiedSequencePointLength++; } } debugInfo = new EmittedMethodDebugInformation(sequencePoints); } ILExceptionRegion[] exceptionRegions = null; int numberOfExceptionRegions = _finallyRegions.Count; if (numberOfExceptionRegions > 0) { exceptionRegions = new ILExceptionRegion[numberOfExceptionRegions]; for (int i = 0; i < _finallyRegions.Count; i++) { ILExceptionRegionBuilder region = _finallyRegions[i]; Debug.Assert(region.IsDefined); exceptionRegions[i] = new ILExceptionRegion(ILExceptionRegionKind.Finally, region.TryOffset, region.TryLength, region.HandlerOffset, region.HandlerLength, classToken: 0, filterOffset: 0); } } var result = new ILStubMethodIL(owningMethod, ilInstructions, _locals.ToArray(), _tokens.ToArray(), exceptionRegions, debugInfo); result.CheckStackBalance(); return result; } private class EmittedMethodDebugInformation : MethodDebugInformation { private readonly ILSequencePoint[] _sequencePoints; public EmittedMethodDebugInformation(ILSequencePoint[] sequencePoints) { _sequencePoints = sequencePoints; } public override IEnumerable<ILSequencePoint> GetSequencePoints() { return _sequencePoints; } } } public abstract partial class ILStubMethod : MethodDesc { public abstract MethodIL EmitIL(); public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return false; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_NATIVE using System; using System.Diagnostics; using Microsoft.Scripting.Runtime; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; #if CLR2 using Microsoft.Scripting.Math; #else using System.Numerics; #endif namespace IronPython.Modules { /// <summary> /// Provides support for interop with native code from Python code. /// </summary> public static partial class CTypes { /// <summary> /// Fields are created when a Structure is defined and provide /// introspection of the structure. /// </summary> [PythonType, PythonHidden] public sealed class Field : PythonTypeDataSlot, ICodeFormattable { private readonly INativeType _fieldType; private readonly int _offset, _index, _bits = -1, _bitsOffset; private readonly string _fieldName; internal Field(string fieldName, INativeType fieldType, int offset, int index) { _offset = offset; _fieldType = fieldType; _index = index; _fieldName = fieldName; } internal Field(string fieldName, INativeType fieldType, int offset, int index, int? bits, int? bitOffset) { _offset = offset; _fieldType = fieldType; _index = index; _fieldName = fieldName; if (bits != null) { _bits = bits.Value; _bitsOffset = bitOffset.Value; } } public int offset { get { return _offset; } } public int size { get { return _fieldType.Size; } } #region Internal APIs internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { if (instance != null) { CData inst = (CData)instance; value = _fieldType.GetValue(inst._memHolder, inst, _offset, false); if (_bits == -1) { return true; } value = ExtractBits(value); return true; } value = this; return true; } internal override bool GetAlwaysSucceeds { get { return true; } } internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) { if (instance != null) { SetValue(((CData)instance)._memHolder, 0, value); return true; } return base.TrySetValue(context, instance, owner, value); } internal void SetValue(MemoryHolder address, int baseOffset, object value) { if (_bits == -1) { object keepAlive = _fieldType.SetValue(address, baseOffset + _offset, value); if (keepAlive != null) { address.AddObject(_index.ToString(), keepAlive); } } else { SetBitsValue(address, baseOffset, value); } } internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { throw PythonOps.TypeError("cannot delete fields in ctypes structures/unions"); } internal INativeType NativeType { get { return _fieldType; } } internal int? BitCount { get { if (_bits == -1) { return null; } return _bits; } } internal string FieldName { get { return _fieldName; } } #endregion #region ICodeFormattable Members public string __repr__(CodeContext context) { if (_bits == -1) { return String.Format("<Field type={0}, ofs={1}, size={2}>", ((PythonType)_fieldType).Name, offset, size); } return String.Format("<Field type={0}, ofs={1}:{2}, bits={3}>", ((PythonType)_fieldType).Name, offset, _bitsOffset, _bits); } #endregion #region Private implementation /// <summary> /// Called for fields which have been limited to a range of bits. Given the /// value for the full type this extracts the individual bits. /// </summary> private object ExtractBits(object value) { if (value is int) { int validBits = ((1 << _bits) - 1); int iVal = (int)value; iVal = (iVal >> _bitsOffset) & validBits; if (IsSignedType) { // need to sign extend if high bit is set if ((iVal & (1 << (_bits - 1))) != 0) { iVal |= (-1) ^ validBits; } } value = ScriptingRuntimeHelpers.Int32ToObject(iVal); } else { Debug.Assert(value is BigInteger); // we only return ints or big ints from GetValue ulong validBits = (1UL << _bits) - 1; BigInteger biVal = (BigInteger)value; ulong bits; if (IsSignedType) { bits = (ulong)(long)biVal; } else { bits = (ulong)biVal; } bits = (bits >> _bitsOffset) & validBits; if (IsSignedType) { // need to sign extend if high bit is set if ((bits & (1UL << (_bits - 1))) != 0) { bits |= ulong.MaxValue ^ validBits; } value = (BigInteger)(long)bits; } else { value = (BigInteger)bits; } } return value; } /// <summary> /// Called for fields which have been limited to a range of bits. Sets the /// specified value into the bits for the field. /// </summary> private void SetBitsValue(MemoryHolder address, int baseOffset, object value) { // get the value in the form of a ulong which can contain the biggest bitfield ulong newBits; if (value is int) { newBits = (ulong)(int)value; } else if (value is BigInteger) { newBits = (ulong)(long)(BigInteger)value; } else { throw PythonOps.TypeErrorForTypeMismatch("int or long", value); } // do the same for the existing value int offset = checked(_offset + baseOffset); object curValue = _fieldType.GetValue(address, null, offset, false); ulong valueBits; if (curValue is int) { valueBits = (ulong)(int)curValue; } else { valueBits = (ulong)(long)(BigInteger)curValue; } // get a mask for the bits this field owns ulong targetBits = ((1UL << _bits) - 1) << _bitsOffset; // clear the existing bits valueBits &= ~targetBits; // or in the new bits provided by the user valueBits |= (newBits << _bitsOffset) & targetBits; // and set the value if (IsSignedType) { if (_fieldType.Size <= 4) { _fieldType.SetValue(address, offset, (int)(long)valueBits); } else { _fieldType.SetValue(address, offset, (BigInteger)(long)valueBits); } } else { if (_fieldType.Size < 4) { _fieldType.SetValue(address, offset, (int)valueBits); } else { _fieldType.SetValue(address, offset, (BigInteger)valueBits); } } } private bool IsSignedType { get { switch (((SimpleType)_fieldType)._type) { case SimpleTypeKind.SignedByte: case SimpleTypeKind.SignedInt: case SimpleTypeKind.SignedLong: case SimpleTypeKind.SignedLongLong: case SimpleTypeKind.SignedShort: return true; } return false; } } #endregion } } } #endif
// Copyright 2011, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Author: api.anash@gmail.com (Anash P. Oommen) using Google.Api.Ads.Common.Lib; using System; using System.Configuration; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Net; using System.Xml; namespace Google.Api.Ads.AdWords.Lib { /// <summary> /// This class reads the configuration keys from App.config. /// </summary> public class AdWordsAppConfig : AppConfigBase { /// <summary> /// The short name to identify this assembly. /// </summary> private const string SHORT_NAME = "AwApi-DotNet"; /// <summary> /// Key name for clientCustomerId. /// </summary> private const string CLIENT_CUSTOMER_ID = "ClientCustomerId"; /// <summary> /// Key name for developerToken. /// </summary> private const string DEVELOPER_TOKEN = "DeveloperToken"; /// <summary> /// Key name for userAgent. /// </summary> private const string USER_AGENT = "UserAgent"; /// <summary> /// Key name for AdWords API URL. /// </summary> private const string ADWORDSAPI_SERVER = "AdWordsApi.Server"; /// <summary> /// Key name for authorizationMethod. /// </summary> private const string AUTHORIZATION_METHOD = "AuthorizationMethod"; /// <summary> /// Default value for AdWords API URL. /// </summary> private const string DEFAULT_ADWORDSAPI_SERVER = "https://adwords.google.com"; /// <summary> /// Default value for authorizationMethod. /// </summary> private const AdWordsAuthorizationMethod DEFAULT_AUTHORIZATION_METHOD = AdWordsAuthorizationMethod.OAuth2; /// <summary> /// ClientCustomerId to be used in SOAP headers. /// </summary> private string clientCustomerId; /// <summary> /// DeveloperToken to be used in the SOAP header. /// </summary> private string developerToken; /// <summary> /// Useragent to be used in the SOAP header. /// </summary> private string userAgent; /// <summary> /// Url for AdWords API. /// </summary> private string adWordsApiServer; /// <summary> /// Authorization method to be used when making API calls. /// </summary> private AdWordsAuthorizationMethod authorizationMethod; /// <summary> /// Gets or sets the client customerId to be used in SOAP headers. /// </summary> public string ClientCustomerId { get { return clientCustomerId; } set { SetPropertyField("ClientCustomerId", ref clientCustomerId, value); } } /// <summary> /// Gets or sets the developer token to be used in SOAP headers. /// </summary> public string DeveloperToken { get { return developerToken; } set { SetPropertyField("DeveloperToken", ref developerToken, value); } } /// <summary> /// Gets or sets the useragent to be used in SOAP headers. /// </summary> public string UserAgent { get { return userAgent; } set { SetPropertyField("UserAgent", ref userAgent, value); } } /// <summary> /// Gets or sets the URL for AdWords API. /// </summary> public string AdWordsApiServer { get { return adWordsApiServer; } set { SetPropertyField("AdWordsApiServer", ref adWordsApiServer, value); } } /// <summary> /// Gets or sets the authorization method to be used when making API calls. /// </summary> public AdWordsAuthorizationMethod AuthorizationMethod { get { return authorizationMethod; } set { SetPropertyField("AuthorizationMethod", ref authorizationMethod, value); } } /// <summary> /// Gets a useragent string that can be used with the library. /// </summary> public string GetUserAgent() { return String.Format("{0} ({1}{2})", this.UserAgent, this.Signature, this.EnableGzipCompression ? ", gzip" : ""); } /// <summary> /// Gets the default OAuth2 scope. /// </summary> public override string GetDefaultOAuth2Scope() { return string.Format("{0}/api/adwords/", this.AdWordsApiServer); } /// <summary> /// Public constructor. /// </summary> public AdWordsAppConfig() : base() { clientCustomerId = ""; developerToken = ""; userAgent = ""; adWordsApiServer = DEFAULT_ADWORDSAPI_SERVER; authorizationMethod = DEFAULT_AUTHORIZATION_METHOD; ReadSettings((Hashtable) ConfigurationManager.GetSection("AdWordsApi")); } /// <summary> /// Read all settings from App.config. /// </summary> /// <param name="settings">The parsed App.config settings.</param> protected override void ReadSettings(Hashtable settings) { base.ReadSettings(settings); clientCustomerId = ReadSetting(settings, CLIENT_CUSTOMER_ID, clientCustomerId); developerToken = ReadSetting(settings, DEVELOPER_TOKEN, developerToken); userAgent = ReadSetting(settings, USER_AGENT, userAgent); adWordsApiServer = ReadSetting(settings, ADWORDSAPI_SERVER, adWordsApiServer); try { authorizationMethod = (AdWordsAuthorizationMethod) Enum.Parse( typeof(AdWordsAuthorizationMethod), ReadSetting(settings, AUTHORIZATION_METHOD, authorizationMethod.ToString())); } catch { authorizationMethod = DEFAULT_AUTHORIZATION_METHOD; } // If there is an OAuth2 scope mentioned in App.config, this will be // loaded by the above call. If there isn't one, we will initialize it // with a library-specific default value. if (string.IsNullOrEmpty(this.OAuth2Scope)) { this.OAuth2Scope = GetDefaultOAuth2Scope(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // This file contains the IDN functions and implementation. // // This allows encoding of non-ASCII domain names in a "punycode" form, // for example: // // \u5B89\u5BA4\u5948\u7F8E\u6075-with-SUPER-MONKEYS // // is encoded as: // // xn---with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n // // Additional options are provided to allow unassigned IDN characters and // to validate according to the Std3ASCII Rules (like DNS names). // // There are also rules regarding bidirectionality of text and the length // of segments. // // For additional rules see also: // RFC 3490 - Internationalizing Domain Names in Applications (IDNA) // RFC 3491 - Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN) // RFC 3492 - Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA) using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; namespace System.Globalization { // IdnMapping class used to map names to Punycode public sealed partial class IdnMapping { private bool _allowUnassigned; private bool _useStd3AsciiRules; public IdnMapping() { } public bool AllowUnassigned { get { return _allowUnassigned; } set { _allowUnassigned = value; } } public bool UseStd3AsciiRules { get { return _useStd3AsciiRules; } set { _useStd3AsciiRules = value; } } // Gets ASCII (Punycode) version of the string public string GetAscii(string unicode) { return GetAscii(unicode, 0); } public string GetAscii(string unicode, int index) { if (unicode == null) throw new ArgumentNullException(nameof(unicode)); return GetAscii(unicode, index, unicode.Length - index); } public string GetAscii(string unicode, int index, int count) { if (unicode == null) throw new ArgumentNullException(nameof(unicode)); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (index > unicode.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); if (index > unicode.Length - count) throw new ArgumentOutOfRangeException(nameof(unicode), SR.ArgumentOutOfRange_IndexCountBuffer); if (count == 0) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); } if (unicode[index + count - 1] == 0) { throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, index + count - 1), nameof(unicode)); } if (GlobalizationMode.Invariant) { return GetAsciiInvariant(unicode, index, count); } unsafe { fixed (char* pUnicode = unicode) { return GetAsciiCore(unicode, pUnicode + index, count); } } } // Gets Unicode version of the string. Normalized and limited to IDNA characters. public string GetUnicode(string ascii) { return GetUnicode(ascii, 0); } public string GetUnicode(string ascii, int index) { if (ascii == null) throw new ArgumentNullException(nameof(ascii)); return GetUnicode(ascii, index, ascii.Length - index); } public string GetUnicode(string ascii, int index, int count) { if (ascii == null) throw new ArgumentNullException(nameof(ascii)); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (index > ascii.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); if (index > ascii.Length - count) throw new ArgumentOutOfRangeException(nameof(ascii), SR.ArgumentOutOfRange_IndexCountBuffer); // This is a case (i.e. explicitly null-terminated input) where behavior in .NET and Win32 intentionally differ. // The .NET APIs should (and did in v4.0 and earlier) throw an ArgumentException on input that includes a terminating null. // The Win32 APIs fail on an embedded null, but not on a terminating null. if (count > 0 && ascii[index + count - 1] == (char)0) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); if (GlobalizationMode.Invariant) { return GetUnicodeInvariant(ascii, index, count); } unsafe { fixed (char* pAscii = ascii) { return GetUnicodeCore(ascii, pAscii + index, count); } } } public override bool Equals(object obj) { return obj is IdnMapping that && _allowUnassigned == that._allowUnassigned && _useStd3AsciiRules == that._useStd3AsciiRules; } public override int GetHashCode() { return (_allowUnassigned ? 100 : 200) + (_useStd3AsciiRules ? 1000 : 2000); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static unsafe string GetStringForOutput(string originalString, char* input, int inputLength, char* output, int outputLength) { return originalString.Length == inputLength && new ReadOnlySpan<char>(input, inputLength).SequenceEqual(new ReadOnlySpan<char>(output, outputLength)) ? originalString : new string(output, 0, outputLength); } // // Invariant implementation // private const char c_delimiter = '-'; private const string c_strAcePrefix = "xn--"; private const int c_labelLimit = 63; // Not including dots private const int c_defaultNameLimit = 255; // Including dots private const int c_initialN = 0x80; private const int c_maxint = 0x7ffffff; private const int c_initialBias = 72; private const int c_punycodeBase = 36; private const int c_tmin = 1; private const int c_tmax = 26; private const int c_skew = 38; private const int c_damp = 700; // Legal "dot" separators (i.e: . in www.microsoft.com) private static char[] c_Dots = { '.', '\u3002', '\uFF0E', '\uFF61' }; private string GetAsciiInvariant(string unicode, int index, int count) { if (index > 0 || count < unicode.Length) { unicode = unicode.Substring(index, count); } // Check for ASCII only string, which will be unchanged if (ValidateStd3AndAscii(unicode, UseStd3AsciiRules, true)) { return unicode; } // Cannot be null terminated (normalization won't help us with this one, and // may have returned false before checking the whole string above) Debug.Assert(count >= 1, "[IdnMapping.GetAscii] Expected 0 length strings to fail before now."); if (unicode[unicode.Length - 1] <= 0x1f) { throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, unicode.Length - 1), nameof(unicode)); } // May need to check Std3 rules again for non-ascii if (UseStd3AsciiRules) { ValidateStd3AndAscii(unicode, true, false); } // Go ahead and encode it return PunycodeEncode(unicode); } // See if we're only ASCII static bool ValidateStd3AndAscii(string unicode, bool bUseStd3, bool bCheckAscii) { // If its empty, then its too small if (unicode.Length == 0) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); int iLastDot = -1; // Loop the whole string for (int i = 0; i < unicode.Length; i++) { // Aren't allowing control chars (or 7f, but idn tables catch that, they don't catch \0 at end though) if (unicode[i] <= 0x1f) { throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, i ), nameof(unicode)); } // If its Unicode or a control character, return false (non-ascii) if (bCheckAscii && unicode[i] >= 0x7f) return false; // Check for dots if (IsDot(unicode[i])) { // Can't have 2 dots in a row if (i == iLastDot + 1) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); // If its too far between dots then fail if (i - iLastDot > c_labelLimit + 1) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); // If validating Std3, then char before dot can't be - char if (bUseStd3 && i > 0) ValidateStd3(unicode[i - 1], true); // Remember where the last dot is iLastDot = i; continue; } // If necessary, make sure its a valid std3 character if (bUseStd3) { ValidateStd3(unicode[i], (i == iLastDot + 1)); } } // If we never had a dot, then we need to be shorter than the label limit if (iLastDot == -1 && unicode.Length > c_labelLimit) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); // Need to validate entire string length, 1 shorter if last char wasn't a dot if (unicode.Length > c_defaultNameLimit - (IsDot(unicode[unicode.Length - 1]) ? 0 : 1)) throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(unicode[unicode.Length - 1]) ? 0 : 1)), nameof(unicode)); // If last char wasn't a dot we need to check for trailing - if (bUseStd3 && !IsDot(unicode[unicode.Length - 1])) ValidateStd3(unicode[unicode.Length - 1], true); return true; } /* PunycodeEncode() converts Unicode to Punycode. The input */ /* is represented as an array of Unicode code points (not code */ /* units; surrogate pairs are not allowed), and the output */ /* will be represented as an array of ASCII code points. The */ /* output string is *not* null-terminated; it will contain */ /* zeros if and only if the input contains zeros. (Of course */ /* the caller can leave room for a terminator and add one if */ /* needed.) The input_length is the number of code points in */ /* the input. The output_length is an in/out argument: the */ /* caller passes in the maximum number of code points that it */ /* can receive, and on successful return it will contain the */ /* number of code points actually output. The case_flags array */ /* holds input_length boolean values, where nonzero suggests that */ /* the corresponding Unicode character be forced to uppercase */ /* after being decoded (if possible), and zero suggests that */ /* it be forced to lowercase (if possible). ASCII code points */ /* are encoded literally, except that ASCII letters are forced */ /* to uppercase or lowercase according to the corresponding */ /* uppercase flags. If case_flags is a null pointer then ASCII */ /* letters are left as they are, and other code points are */ /* treated as if their uppercase flags were zero. The return */ /* value can be any of the punycode_status values defined above */ /* except punycode_bad_input; if not punycode_success, then */ /* output_size and output might contain garbage. */ static string PunycodeEncode(string unicode) { // 0 length strings aren't allowed if (unicode.Length == 0) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); StringBuilder output = new StringBuilder(unicode.Length); int iNextDot = 0; int iAfterLastDot = 0; int iOutputAfterLastDot = 0; // Find the next dot while (iNextDot < unicode.Length) { // Find end of this segment iNextDot = unicode.IndexOfAny(c_Dots, iAfterLastDot); Debug.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken"); if (iNextDot < 0) iNextDot = unicode.Length; // Only allowed to have empty . section at end (www.microsoft.com.) if (iNextDot == iAfterLastDot) { // Only allowed to have empty sections as trailing . if (iNextDot != unicode.Length) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); // Last dot, stop break; } // We'll need an Ace prefix output.Append(c_strAcePrefix); // Everything resets every segment. bool bRightToLeft = false; // Check for RTL. If right-to-left, then 1st & last chars must be RTL BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iAfterLastDot); if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic) { // It has to be right to left. bRightToLeft = true; // Check last char int iTest = iNextDot - 1; if (char.IsLowSurrogate(unicode, iTest)) { iTest--; } eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iTest); if (eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic) { // Oops, last wasn't RTL, last should be RTL if first is RTL throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode)); } } // Handle the basic code points int basicCount; int numProcessed = 0; // Num code points that have been processed so far (this segment) for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++) { // Can't be lonely surrogate because it would've thrown in normalization Debug.Assert(char.IsLowSurrogate(unicode, basicCount) == false, "[IdnMapping.punycode_encode]Unexpected low surrogate"); // Double check our bidi rules BidiCategory testBidi = CharUnicodeInfo.GetBidiCategory(unicode, basicCount); // If we're RTL, we can't have LTR chars if (bRightToLeft && testBidi == BidiCategory.LeftToRight) { // Oops, throw error throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode)); } // If we're not RTL we can't have RTL chars if (!bRightToLeft && (testBidi == BidiCategory.RightToLeft || testBidi == BidiCategory.RightToLeftArabic)) { // Oops, throw error throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode)); } // If its basic then add it if (Basic(unicode[basicCount])) { output.Append(EncodeBasic(unicode[basicCount])); numProcessed++; } // If its a surrogate, skip the next since our bidi category tester doesn't handle it. else if (char.IsSurrogatePair(unicode, basicCount)) basicCount++; } int numBasicCodePoints = numProcessed; // number of basic code points // Stop if we ONLY had basic code points if (numBasicCodePoints == iNextDot - iAfterLastDot) { // Get rid of xn-- and this segments done output.Remove(iOutputAfterLastDot, c_strAcePrefix.Length); } else { // If it has some non-basic code points the input cannot start with xn-- if (unicode.Length - iAfterLastDot >= c_strAcePrefix.Length && unicode.Substring(iAfterLastDot, c_strAcePrefix.Length).Equals( c_strAcePrefix, StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(unicode)); // Need to do ACE encoding int numSurrogatePairs = 0; // number of surrogate pairs so far // Add a delimiter (-) if we had any basic code points (between basic and encoded pieces) if (numBasicCodePoints > 0) { output.Append(c_delimiter); } // Initialize the state int n = c_initialN; int delta = 0; int bias = c_initialBias; // Main loop while (numProcessed < (iNextDot - iAfterLastDot)) { /* All non-basic code points < n have been */ /* handled already. Find the next larger one: */ int j; int m; int test = 0; for (m = c_maxint, j = iAfterLastDot; j < iNextDot; j += IsSupplementary(test) ? 2 : 1) { test = char.ConvertToUtf32(unicode, j); if (test >= n && test < m) m = test; } /* Increase delta enough to advance the decoder's */ /* <n,i> state to <m,0>, but guard against overflow: */ delta += (int)((m - n) * ((numProcessed - numSurrogatePairs) + 1)); Debug.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int"); n = m; for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1) { // Make sure we're aware of surrogates test = char.ConvertToUtf32(unicode, j); // Adjust for character position (only the chars in our string already, some // haven't been processed. if (test < n) { delta++; Debug.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int"); } if (test == n) { // Represent delta as a generalized variable-length integer: int q, k; for (q = delta, k = c_punycodeBase; ; k += c_punycodeBase) { int t = k <= bias ? c_tmin : k >= bias + c_tmax ? c_tmax : k - bias; if (q < t) break; Debug.Assert(c_punycodeBase != t, "[IdnMapping.punycode_encode]Expected c_punycodeBase (36) to be != t"); output.Append(EncodeDigit(t + (q - t) % (c_punycodeBase - t))); q = (q - t) / (c_punycodeBase - t); } output.Append(EncodeDigit(q)); bias = Adapt(delta, (numProcessed - numSurrogatePairs) + 1, numProcessed == numBasicCodePoints); delta = 0; numProcessed++; if (IsSupplementary(m)) { numProcessed++; numSurrogatePairs++; } } } ++delta; ++n; Debug.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int"); } } // Make sure its not too big if (output.Length - iOutputAfterLastDot > c_labelLimit) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); // Done with this segment, add dot if necessary if (iNextDot != unicode.Length) output.Append('.'); iAfterLastDot = iNextDot + 1; iOutputAfterLastDot = output.Length; } // Throw if we're too long if (output.Length > c_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)) throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)), nameof(unicode)); // Return our output string return output.ToString(); } // Is it a dot? // are we U+002E (., full stop), U+3002 (ideographic full stop), U+FF0E (fullwidth full stop), or // U+FF61 (halfwidth ideographic full stop). // Note: IDNA Normalization gets rid of dots now, but testing for last dot is before normalization private static bool IsDot(char c) { return c == '.' || c == '\u3002' || c == '\uFF0E' || c == '\uFF61'; } private static bool IsSupplementary(int cTest) { return cTest >= 0x10000; } private static bool Basic(uint cp) { // Is it in ASCII range? return cp < 0x80; } // Validate Std3 rules for a character private static void ValidateStd3(char c, bool bNextToDot) { // Check for illegal characters if ((c <= ',' || c == '/' || (c >= ':' && c <= '@') || // Lots of characters not allowed (c >= '[' && c <= '`') || (c >= '{' && c <= (char)0x7F)) || (c == '-' && bNextToDot)) throw new ArgumentException(SR.Format(SR.Argument_IdnBadStd3, c), nameof(c)); } private string GetUnicodeInvariant(string ascii, int index, int count) { if (index > 0 || count < ascii.Length) { // We're only using part of the string ascii = ascii.Substring(index, count); } // Convert Punycode to Unicode string strUnicode = PunycodeDecode(ascii); // Output name MUST obey IDNA rules & round trip (casing differences are allowed) if (!ascii.Equals(GetAscii(strUnicode), StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(ascii)); return strUnicode; } /* PunycodeDecode() converts Punycode to Unicode. The input is */ /* represented as an array of ASCII code points, and the output */ /* will be represented as an array of Unicode code points. The */ /* input_length is the number of code points in the input. The */ /* output_length is an in/out argument: the caller passes in */ /* the maximum number of code points that it can receive, and */ /* on successful return it will contain the actual number of */ /* code points output. The case_flags array needs room for at */ /* least output_length values, or it can be a null pointer if the */ /* case information is not needed. A nonzero flag suggests that */ /* the corresponding Unicode character be forced to uppercase */ /* by the caller (if possible), while zero suggests that it be */ /* forced to lowercase (if possible). ASCII code points are */ /* output already in the proper case, but their flags will be set */ /* appropriately so that applying the flags would be harmless. */ /* The return value can be any of the punycode_status values */ /* defined above; if not punycode_success, then output_length, */ /* output, and case_flags might contain garbage. On success, the */ /* decoder will never need to write an output_length greater than */ /* input_length, because of how the encoding is defined. */ private static string PunycodeDecode(string ascii) { // 0 length strings aren't allowed if (ascii.Length == 0) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii)); // Throw if we're too long if (ascii.Length > c_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)) throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), nameof(ascii)); // output stringbuilder StringBuilder output = new StringBuilder(ascii.Length); // Dot searching int iNextDot = 0; int iAfterLastDot = 0; int iOutputAfterLastDot = 0; while (iNextDot < ascii.Length) { // Find end of this segment iNextDot = ascii.IndexOf('.', iAfterLastDot); if (iNextDot < 0 || iNextDot > ascii.Length) iNextDot = ascii.Length; // Only allowed to have empty . section at end (www.microsoft.com.) if (iNextDot == iAfterLastDot) { // Only allowed to have empty sections as trailing . if (iNextDot != ascii.Length) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii)); // Last dot, stop break; } // In either case it can't be bigger than segment size if (iNextDot - iAfterLastDot > c_labelLimit) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii)); // See if this section's ASCII or ACE if (ascii.Length < c_strAcePrefix.Length + iAfterLastDot || string.Compare(ascii, iAfterLastDot, c_strAcePrefix, 0, c_strAcePrefix.Length, StringComparison.OrdinalIgnoreCase) != 0) { // Its ASCII, copy it output.Append(ascii, iAfterLastDot, iNextDot - iAfterLastDot); } else { // Not ASCII, bump up iAfterLastDot to be after ACE Prefix iAfterLastDot += c_strAcePrefix.Length; // Get number of basic code points (where delimiter is) // numBasicCodePoints < 0 if there're no basic code points int iTemp = ascii.LastIndexOf(c_delimiter, iNextDot - 1); // Trailing - not allowed if (iTemp == iNextDot - 1) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); int numBasicCodePoints; if (iTemp <= iAfterLastDot) numBasicCodePoints = 0; else { numBasicCodePoints = iTemp - iAfterLastDot; // Copy all the basic code points, making sure they're all in the allowed range, // and losing the casing for all of them. for (int copyAscii = iAfterLastDot; copyAscii < iAfterLastDot + numBasicCodePoints; copyAscii++) { // Make sure we don't allow unicode in the ascii part if (ascii[copyAscii] > 0x7f) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); // When appending make sure they get lower cased output.Append((char)(ascii[copyAscii] >= 'A' && ascii[copyAscii] <='Z' ? ascii[copyAscii] - 'A' + 'a' : ascii[copyAscii])); } } // Get ready for main loop. Start at beginning if we didn't have any // basic code points, otherwise start after the -. // asciiIndex will be next character to read from ascii int asciiIndex = iAfterLastDot + (numBasicCodePoints > 0 ? numBasicCodePoints + 1 : 0); // initialize our state int n = c_initialN; int bias = c_initialBias; int i = 0; int w, k; // no Supplementary characters yet int numSurrogatePairs = 0; // Main loop, read rest of ascii while (asciiIndex < iNextDot) { /* Decode a generalized variable-length integer into delta, */ /* which gets added to i. The overflow checking is easier */ /* if we increase i as we go, then subtract off its starting */ /* value at the end to obtain delta. */ int oldi = i; for (w = 1, k = c_punycodeBase; ; k += c_punycodeBase) { // Check to make sure we aren't overrunning our ascii string if (asciiIndex >= iNextDot) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); // decode the digit from the next char int digit = DecodeDigit(ascii[asciiIndex++]); Debug.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0"); if (digit > (c_maxint - i) / w) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); i += (int)(digit * w); int t = k <= bias ? c_tmin : k >= bias + c_tmax ? c_tmax : k - bias; if (digit < t) break; Debug.Assert(c_punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != c_punycodeBase (36)"); if (w > c_maxint / (c_punycodeBase - t)) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); w *= (c_punycodeBase - t); } bias = Adapt(i - oldi, (output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1, oldi == 0); /* i was supposed to wrap around from output.Length to 0, */ /* incrementing n each time, so we'll fix that now: */ Debug.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0, "[IdnMapping.punycode_decode]Expected to have added > 0 characters this segment"); if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > c_maxint - n) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); n += (int)(i / (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1)); i %= (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1); // Make sure n is legal if ((n < 0 || n > 0x10ffff) || (n >= 0xD800 && n <= 0xDFFF)) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); // insert n at position i of the output: Really tricky if we have surrogates int iUseInsertLocation; string strTemp = char.ConvertFromUtf32(n); // If we have supplimentary characters if (numSurrogatePairs > 0) { // Hard way, we have supplimentary characters int iCount; for (iCount = i, iUseInsertLocation = iOutputAfterLastDot; iCount > 0; iCount--, iUseInsertLocation++) { // If its a surrogate, we have to go one more if (iUseInsertLocation >= output.Length) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); if (char.IsSurrogate(output[iUseInsertLocation])) iUseInsertLocation++; } } else { // No Supplementary chars yet, just add i iUseInsertLocation = iOutputAfterLastDot + i; } // Insert it output.Insert(iUseInsertLocation, strTemp); // If it was a surrogate increment our counter if (IsSupplementary(n)) numSurrogatePairs++; // Index gets updated i++; } // Do BIDI testing bool bRightToLeft = false; // Check for RTL. If right-to-left, then 1st & last chars must be RTL BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(output, iOutputAfterLastDot); if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic) { // It has to be right to left. bRightToLeft = true; } // Check the rest of them to make sure RTL/LTR is consistent for (int iTest = iOutputAfterLastDot; iTest < output.Length; iTest++) { // This might happen if we run into a pair if (char.IsLowSurrogate(output[iTest])) continue; // Check to see if its LTR eBidi = CharUnicodeInfo.GetBidiCategory(output, iTest); if ((bRightToLeft && eBidi == BidiCategory.LeftToRight) || (!bRightToLeft && (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic))) throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(ascii)); } // Its also a requirement that the last one be RTL if 1st is RTL if (bRightToLeft && eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic) { // Oops, last wasn't RTL, last should be RTL if first is RTL throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(ascii)); } } // See if this label was too long if (iNextDot - iAfterLastDot > c_labelLimit) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii)); // Done with this segment, add dot if necessary if (iNextDot != ascii.Length) output.Append('.'); iAfterLastDot = iNextDot + 1; iOutputAfterLastDot = output.Length; } // Throw if we're too long if (output.Length > c_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1)) throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1)), nameof(ascii)); // Return our output string return output.ToString(); } // DecodeDigit(cp) returns the numeric value of a basic code */ // point (for use in representing integers) in the range 0 to */ // c_punycodeBase-1, or <0 if cp is does not represent a value. */ private static int DecodeDigit(char cp) { if (cp >= '0' && cp <= '9') return cp - '0' + 26; // Two flavors for case differences if (cp >= 'a' && cp <= 'z') return cp - 'a'; if (cp >= 'A' && cp <= 'Z') return cp - 'A'; // Expected 0-9, A-Z or a-z, everything else is illegal throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(cp)); } private static int Adapt(int delta, int numpoints, bool firsttime) { uint k; delta = firsttime ? delta / c_damp : delta / 2; Debug.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints."); delta += delta / numpoints; for (k = 0; delta > ((c_punycodeBase - c_tmin) * c_tmax) / 2; k += c_punycodeBase) { delta /= c_punycodeBase - c_tmin; } Debug.Assert(delta + c_skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew."); return (int)(k + (c_punycodeBase - c_tmin + 1) * delta / (delta + c_skew)); } /* EncodeBasic(bcp,flag) forces a basic code point to lowercase */ /* if flag is false, uppercase if flag is true, and returns */ /* the resulting code point. The code point is unchanged if it */ /* is caseless. The behavior is undefined if bcp is not a basic */ /* code point. */ static char EncodeBasic(char bcp) { if (HasUpperCaseFlag(bcp)) bcp += (char)('a' - 'A'); return bcp; } // Return whether a punycode code point is flagged as being upper case. private static bool HasUpperCaseFlag(char punychar) { return (punychar >= 'A' && punychar <= 'Z'); } /* EncodeDigit(d,flag) returns the basic code point whose value */ /* (when used for representing integers) is d, which needs to be in */ /* the range 0 to punycodeBase-1. The lowercase form is used unless flag is */ /* true, in which case the uppercase form is used. */ private static char EncodeDigit(int d) { Debug.Assert(d >= 0 && d < c_punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase"); // 26-35 map to ASCII 0-9 if (d > 25) return (char)(d - 26 + '0'); // 0-25 map to a-z or A-Z return (char)(d + 'a'); } } }
using System.Linq; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.VisualBasic.Syntax; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.CodeAnalysis.Formatting; using System.Collections.Generic; using RefactoringEssentials.Util; namespace RefactoringEssentials.VB { /// <summary> /// Surround usage of a variable with an "IsNot Nothing" check or adds it to surrounding If block. /// </summary> [ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name = "Add check for Nothing")] public class AddCheckForNothingCodeRefactoringProvider : CodeRefactoringProvider { public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) return; var span = context.Span; if (!span.IsEmpty) return; var cancellationToken = context.CancellationToken; if (cancellationToken.IsCancellationRequested) return; var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (model.IsFromGeneratedCode(cancellationToken)) return; var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(span.Start); ExpressionSyntax identifier = token.Parent as IdentifierNameSyntax; if (identifier == null) return; // If identifier is a type name, this might be a static member access or similar, don't suggest null checks on it var identifierSymbol = model.GetSymbolInfo(identifier).Symbol; if ((identifierSymbol == null) || (identifierSymbol.IsType())) return; // Identifier might be part of a MemberAccessExpression and we need to check it for null as a whole identifier = GetOuterMemberAccessExpression(identifier) ?? identifier; if ((identifier.Parent is ExpressionSyntax) && ConditionContainsNullCheck((ExpressionSyntax)identifier.Parent, identifier)) return; var identifierAncestors = identifier.Ancestors(); // Don't surround Return statements with checks if (identifierAncestors.OfType<ReturnStatementSyntax>().Any()) return; // If identifier is in a conditional ternary expression, skip refactoring is case of present null check in its condition var conditionalExprParent = identifierAncestors.OfType<TernaryConditionalExpressionSyntax>().FirstOrDefault(); if ((conditionalExprParent != null) && ConditionContainsNullCheck(conditionalExprParent.Condition, identifier)) return; // Check identifier type, don't suggest null checks for value types! var identifierType = model.GetTypeInfo(identifier).Type; if ((identifierType == null) || (identifierType.IsValueType && !identifierType.IsNullableType())) return; SyntaxNode statementToWrap = identifierAncestors.OfType<ExecutableStatementSyntax>().FirstOrDefault(); if (statementToWrap == null) return; // No refactoring if statement is inside of a local variable declaration if (statementToWrap is LocalDeclarationStatementSyntax) return; bool wrapWithSingleLineIfStatement = false; SyntaxNode newWrappedStatement = null; var wrappedStatementAncestors = statementToWrap.Ancestors(); if (wrappedStatementAncestors.OfType<SingleLineLambdaExpressionSyntax>().Any()) { // Inside of a single-line lambda => wrap with single line If statement wrapWithSingleLineIfStatement = true; } // Check surrounding block var surroundingElseIfBlock = wrappedStatementAncestors.FirstOrDefault() as ElseIfBlockSyntax; if (surroundingElseIfBlock != null) { // Special handling for extension of Else If blocks if (StatementWithConditionContainsNullCheck(surroundingElseIfBlock, identifier)) return; statementToWrap = surroundingElseIfBlock; newWrappedStatement = ExtendIfConditionWithNullCheck(surroundingElseIfBlock, identifier); } else { var surroundingStatement = wrappedStatementAncestors.OfType<ExecutableStatementSyntax>().FirstOrDefault(); if (surroundingStatement != null) { if (StatementWithConditionContainsNullCheck(surroundingStatement, identifier)) return; if ((surroundingStatement is MultiLineIfBlockSyntax) || (surroundingStatement is SingleLineIfStatementSyntax)) { statementToWrap = surroundingStatement; newWrappedStatement = ExtendIfConditionWithNullCheck(surroundingStatement, identifier); } } else { if (StatementWithConditionContainsNullCheck(statementToWrap, identifier)) return; if ((statementToWrap is MultiLineIfBlockSyntax) || (statementToWrap is SingleLineIfStatementSyntax)) { newWrappedStatement = ExtendIfConditionWithNullCheck(statementToWrap, identifier); } } } if (newWrappedStatement == null) { if (wrapWithSingleLineIfStatement) { newWrappedStatement = SyntaxFactory.SingleLineIfStatement( SyntaxFactory.Token(SyntaxKind.IfKeyword), CreateIsNotNothingBinaryExpression(identifier), SyntaxFactory.Token(SyntaxKind.ThenKeyword), SyntaxFactory.List<StatementSyntax>(new[] { ((StatementSyntax)statementToWrap).WithoutLeadingTrivia().WithoutTrailingTrivia() }), null ).WithLeadingTrivia(statementToWrap.GetLeadingTrivia()).WithTrailingTrivia(statementToWrap.GetTrailingTrivia()).WithAdditionalAnnotations(Formatter.Annotation); } else { newWrappedStatement = SyntaxFactory.MultiLineIfBlock( SyntaxFactory.IfStatement( SyntaxFactory.Token(SyntaxKind.IfKeyword), CreateIsNotNothingBinaryExpression(identifier), SyntaxFactory.Token(SyntaxKind.ThenKeyword)), SyntaxFactory.List<StatementSyntax>(new[] { ((StatementSyntax) statementToWrap).WithoutLeadingTrivia().WithoutTrailingTrivia() }), SyntaxFactory.List<ElseIfBlockSyntax>(), null ).WithLeadingTrivia(statementToWrap.GetLeadingTrivia()).WithTrailingTrivia(statementToWrap.GetTrailingTrivia()).WithAdditionalAnnotations(Formatter.Annotation); } } context.RegisterRefactoring(CodeActionFactory.Create(token.Span, DiagnosticSeverity.Info, GettextCatalog.GetString("Add check for Nothing"), t2 => { var newRoot = root.ReplaceNode<SyntaxNode>(statementToWrap, newWrappedStatement); return Task.FromResult(document.WithSyntaxRoot(newRoot)); })); } SyntaxNode ExtendIfConditionWithNullCheck(SyntaxNode statement, ExpressionSyntax identifier) { MultiLineIfBlockSyntax multiLineIfStatement = statement as MultiLineIfBlockSyntax; if (multiLineIfStatement != null) { return multiLineIfStatement.WithIfStatement( multiLineIfStatement.IfStatement.WithCondition( SyntaxFactory.BinaryExpression(SyntaxKind.AndAlsoExpression, ParenthizeIfNeeded(CreateIsNotNothingBinaryExpression(identifier)), SyntaxFactory.Token(SyntaxKind.AndAlsoKeyword), ParenthizeIfNeeded(multiLineIfStatement.IfStatement.Condition) ).WithAdditionalAnnotations(Formatter.Annotation) )); } SingleLineIfStatementSyntax singleLineIfStatement = statement as SingleLineIfStatementSyntax; if (singleLineIfStatement != null) { return singleLineIfStatement.WithCondition( SyntaxFactory.BinaryExpression(SyntaxKind.AndAlsoExpression, ParenthizeIfNeeded(CreateIsNotNothingBinaryExpression(identifier)), SyntaxFactory.Token(SyntaxKind.AndAlsoKeyword), ParenthizeIfNeeded(singleLineIfStatement.Condition) ).WithAdditionalAnnotations(Formatter.Annotation) ); } ElseIfBlockSyntax elseIfBlock = statement as ElseIfBlockSyntax; if (elseIfBlock != null) { return elseIfBlock.WithElseIfStatement( elseIfBlock.ElseIfStatement.WithCondition( SyntaxFactory.BinaryExpression(SyntaxKind.AndAlsoExpression, ParenthizeIfNeeded(CreateIsNotNothingBinaryExpression(identifier)), SyntaxFactory.Token(SyntaxKind.AndAlsoKeyword), ParenthizeIfNeeded(elseIfBlock.ElseIfStatement.Condition) ).WithAdditionalAnnotations(Formatter.Annotation) )); } return null; } BinaryExpressionSyntax CreateIsNotNothingBinaryExpression(ExpressionSyntax identifier) { return SyntaxFactory.BinaryExpression(SyntaxKind.IsNotExpression, identifier.WithoutTrailingTrivia(), SyntaxFactory.Token(SyntaxKind.IsNotKeyword), SyntaxFactory.LiteralExpression(SyntaxKind.NothingLiteralExpression, SyntaxFactory.Token(SyntaxKind.NothingKeyword))); } bool StatementWithConditionContainsNullCheck(SyntaxNode statement, ExpressionSyntax identifierToCheck) { if (statement is SingleLineIfStatementSyntax) return ConditionContainsNullCheck(((SingleLineIfStatementSyntax)statement).Condition, identifierToCheck); if (statement is MultiLineIfBlockSyntax) return ConditionContainsNullCheck(((MultiLineIfBlockSyntax)statement).IfStatement.Condition, identifierToCheck); if (statement is ElseIfBlockSyntax) return ConditionContainsNullCheck(((ElseIfBlockSyntax)statement).ElseIfStatement.Condition, identifierToCheck); if (statement is WhileBlockSyntax) return ConditionContainsNullCheck(((WhileBlockSyntax)statement).WhileStatement.Condition, identifierToCheck); if (statement is DoLoopBlockSyntax) return ConditionContainsNullCheck(((DoLoopBlockSyntax)statement).DoStatement.WhileOrUntilClause.Condition, identifierToCheck); if (statement is TernaryConditionalExpressionSyntax) return ConditionContainsNullCheck(((TernaryConditionalExpressionSyntax)statement).Condition, identifierToCheck); return false; } bool ConditionContainsNullCheck(ExpressionSyntax condition, ExpressionSyntax identifierToCheck) { var identifierNameToCheck = identifierToCheck as IdentifierNameSyntax; var memberAccessExpressionToCheck = identifierToCheck as MemberAccessExpressionSyntax; return condition.DescendantNodesAndSelf().Any(n => { var binaryExpr = n as BinaryExpressionSyntax; if (binaryExpr != null) { IdentifierNameSyntax identifierName = binaryExpr.Left as IdentifierNameSyntax; if ((identifierName != null) && (identifierNameToCheck != null) && (identifierName.Identifier.ValueText == identifierNameToCheck.Identifier.ValueText)) return binaryExpr.IsKind(SyntaxKind.IsNotExpression) && binaryExpr.Right.IsKind(SyntaxKind.NothingLiteralExpression); MemberAccessExpressionSyntax memberAccessExpressionSyntax = binaryExpr.Left as MemberAccessExpressionSyntax; if ((memberAccessExpressionSyntax != null) && (memberAccessExpressionToCheck != null) && (memberAccessExpressionSyntax.ToString() == identifierToCheck.ToString())) return binaryExpr.IsKind(SyntaxKind.IsNotExpression) && binaryExpr.Right.IsKind(SyntaxKind.NothingLiteralExpression); identifierName = binaryExpr.Right as IdentifierNameSyntax; if ((identifierName != null) && (identifierNameToCheck != null) && (identifierName.Identifier.ValueText == identifierNameToCheck.Identifier.ValueText)) return binaryExpr.IsKind(SyntaxKind.IsNotExpression) && binaryExpr.Left.IsKind(SyntaxKind.NothingLiteralExpression); memberAccessExpressionSyntax = binaryExpr.Right as MemberAccessExpressionSyntax; if ((memberAccessExpressionSyntax != null) && (memberAccessExpressionToCheck != null) && (memberAccessExpressionSyntax.ToString() == identifierToCheck.ToString())) return binaryExpr.IsKind(SyntaxKind.IsNotExpression) && binaryExpr.Left.IsKind(SyntaxKind.NothingLiteralExpression); } return false; }); } ExpressionSyntax ParenthizeIfNeeded(ExpressionSyntax expression) { if (expression is BinaryExpressionSyntax) return SyntaxFactory.ParenthesizedExpression(expression); return expression; } MemberAccessExpressionSyntax GetOuterMemberAccessExpression(ExpressionSyntax identifier) { var parent = identifier.Parent as MemberAccessExpressionSyntax; if ((parent == null) || (parent.Name != identifier)) return null; return parent; } } }
/* '=============================================================================== ' Generated From - CSharp_dOOdads_BusinessEntity.vbgen ' ' ** IMPORTANT ** ' How to Generate your stored procedures: ' ' SQL = SQL_StoredProcs.vbgen ' ACCESS = Access_StoredProcs.vbgen ' ORACLE = Oracle_StoredProcs.vbgen ' FIREBIRD = FirebirdStoredProcs.vbgen ' POSTGRESQL = PostgreSQL_StoredProcs.vbgen ' ' The supporting base class SqlClientEntity is in the Architecture directory in "dOOdads". ' ' This object is 'abstract' which means you need to inherit from it to be able ' to instantiate it. This is very easilly done. You can override properties and ' methods in your derived class, this allows you to regenerate this class at any ' time and not worry about overwriting custom code. ' ' NEVER EDIT THIS FILE. ' ' public class YourObject : _YourObject ' { ' ' } ' '=============================================================================== */ // Generated by MyGeneration Version # (1.1.4.0) using System; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Collections.Specialized; using MyGeneration.dOOdads; namespace MyGeneration.dOOdads.Tests.SQL { public abstract class _AggregateTest : SqlClientEntity { public _AggregateTest() { this.QuerySource = "AggregateTest"; this.MappingName = "AggregateTest"; } //================================================================= // public Overrides void AddNew() //================================================================= // //================================================================= public override void AddNew() { base.AddNew(); } public override void FlushData() { this._whereClause = null; this._aggregateClause = null; base.FlushData(); } //================================================================= // public Function LoadAll() As Boolean //================================================================= // Loads all of the records in the database, and sets the currentRow to the first row //================================================================= public bool LoadAll() { ListDictionary parameters = null; return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_AggregateTestLoadAll]", parameters); } //================================================================= // public Overridable Function LoadByPrimaryKey() As Boolean //================================================================= // Loads a single row of via the primary key //================================================================= public virtual bool LoadByPrimaryKey(int ID) { ListDictionary parameters = new ListDictionary(); parameters.Add(Parameters.ID, ID); return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_AggregateTestLoadByPrimaryKey]", parameters); } #region Parameters protected class Parameters { public static SqlParameter ID { get { return new SqlParameter("@ID", SqlDbType.Int, 0); } } public static SqlParameter DepartmentID { get { return new SqlParameter("@DepartmentID", SqlDbType.Int, 0); } } public static SqlParameter FirstName { get { return new SqlParameter("@FirstName", SqlDbType.VarChar, 25); } } public static SqlParameter LastName { get { return new SqlParameter("@LastName", SqlDbType.VarChar, 15); } } public static SqlParameter Age { get { return new SqlParameter("@Age", SqlDbType.Int, 0); } } public static SqlParameter HireDate { get { return new SqlParameter("@HireDate", SqlDbType.DateTime, 0); } } public static SqlParameter Salary { get { return new SqlParameter("@Salary", SqlDbType.Decimal, 0); } } public static SqlParameter IsActive { get { return new SqlParameter("@IsActive", SqlDbType.Bit, 0); } } } #endregion #region ColumnNames public class ColumnNames { public const string ID = "ID"; public const string DepartmentID = "DepartmentID"; public const string FirstName = "FirstName"; public const string LastName = "LastName"; public const string Age = "Age"; public const string HireDate = "HireDate"; public const string Salary = "Salary"; public const string IsActive = "IsActive"; static public string ToPropertyName(string columnName) { if(ht == null) { ht = new Hashtable(); ht[ID] = _AggregateTest.PropertyNames.ID; ht[DepartmentID] = _AggregateTest.PropertyNames.DepartmentID; ht[FirstName] = _AggregateTest.PropertyNames.FirstName; ht[LastName] = _AggregateTest.PropertyNames.LastName; ht[Age] = _AggregateTest.PropertyNames.Age; ht[HireDate] = _AggregateTest.PropertyNames.HireDate; ht[Salary] = _AggregateTest.PropertyNames.Salary; ht[IsActive] = _AggregateTest.PropertyNames.IsActive; } return (string)ht[columnName]; } static private Hashtable ht = null; } #endregion #region PropertyNames public class PropertyNames { public const string ID = "ID"; public const string DepartmentID = "DepartmentID"; public const string FirstName = "FirstName"; public const string LastName = "LastName"; public const string Age = "Age"; public const string HireDate = "HireDate"; public const string Salary = "Salary"; public const string IsActive = "IsActive"; static public string ToColumnName(string propertyName) { if(ht == null) { ht = new Hashtable(); ht[ID] = _AggregateTest.ColumnNames.ID; ht[DepartmentID] = _AggregateTest.ColumnNames.DepartmentID; ht[FirstName] = _AggregateTest.ColumnNames.FirstName; ht[LastName] = _AggregateTest.ColumnNames.LastName; ht[Age] = _AggregateTest.ColumnNames.Age; ht[HireDate] = _AggregateTest.ColumnNames.HireDate; ht[Salary] = _AggregateTest.ColumnNames.Salary; ht[IsActive] = _AggregateTest.ColumnNames.IsActive; } return (string)ht[propertyName]; } static private Hashtable ht = null; } #endregion #region StringPropertyNames public class StringPropertyNames { public const string ID = "s_ID"; public const string DepartmentID = "s_DepartmentID"; public const string FirstName = "s_FirstName"; public const string LastName = "s_LastName"; public const string Age = "s_Age"; public const string HireDate = "s_HireDate"; public const string Salary = "s_Salary"; public const string IsActive = "s_IsActive"; } #endregion #region Properties public virtual int ID { get { return base.Getint(ColumnNames.ID); } set { base.Setint(ColumnNames.ID, value); } } public virtual int DepartmentID { get { return base.Getint(ColumnNames.DepartmentID); } set { base.Setint(ColumnNames.DepartmentID, value); } } public virtual string FirstName { get { return base.Getstring(ColumnNames.FirstName); } set { base.Setstring(ColumnNames.FirstName, value); } } public virtual string LastName { get { return base.Getstring(ColumnNames.LastName); } set { base.Setstring(ColumnNames.LastName, value); } } public virtual int Age { get { return base.Getint(ColumnNames.Age); } set { base.Setint(ColumnNames.Age, value); } } public virtual DateTime HireDate { get { return base.GetDateTime(ColumnNames.HireDate); } set { base.SetDateTime(ColumnNames.HireDate, value); } } public virtual decimal Salary { get { return base.Getdecimal(ColumnNames.Salary); } set { base.Setdecimal(ColumnNames.Salary, value); } } public virtual bool IsActive { get { return base.Getbool(ColumnNames.IsActive); } set { base.Setbool(ColumnNames.IsActive, value); } } #endregion #region String Properties public virtual string s_ID { get { return this.IsColumnNull(ColumnNames.ID) ? string.Empty : base.GetintAsString(ColumnNames.ID); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ID); else this.ID = base.SetintAsString(ColumnNames.ID, value); } } public virtual string s_DepartmentID { get { return this.IsColumnNull(ColumnNames.DepartmentID) ? string.Empty : base.GetintAsString(ColumnNames.DepartmentID); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.DepartmentID); else this.DepartmentID = base.SetintAsString(ColumnNames.DepartmentID, value); } } public virtual string s_FirstName { get { return this.IsColumnNull(ColumnNames.FirstName) ? string.Empty : base.GetstringAsString(ColumnNames.FirstName); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.FirstName); else this.FirstName = base.SetstringAsString(ColumnNames.FirstName, value); } } public virtual string s_LastName { get { return this.IsColumnNull(ColumnNames.LastName) ? string.Empty : base.GetstringAsString(ColumnNames.LastName); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.LastName); else this.LastName = base.SetstringAsString(ColumnNames.LastName, value); } } public virtual string s_Age { get { return this.IsColumnNull(ColumnNames.Age) ? string.Empty : base.GetintAsString(ColumnNames.Age); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Age); else this.Age = base.SetintAsString(ColumnNames.Age, value); } } public virtual string s_HireDate { get { return this.IsColumnNull(ColumnNames.HireDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.HireDate); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.HireDate); else this.HireDate = base.SetDateTimeAsString(ColumnNames.HireDate, value); } } public virtual string s_Salary { get { return this.IsColumnNull(ColumnNames.Salary) ? string.Empty : base.GetdecimalAsString(ColumnNames.Salary); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Salary); else this.Salary = base.SetdecimalAsString(ColumnNames.Salary, value); } } public virtual string s_IsActive { get { return this.IsColumnNull(ColumnNames.IsActive) ? string.Empty : base.GetboolAsString(ColumnNames.IsActive); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.IsActive); else this.IsActive = base.SetboolAsString(ColumnNames.IsActive, value); } } #endregion #region Where Clause public class WhereClause { public WhereClause(BusinessEntity entity) { this._entity = entity; } public TearOffWhereParameter TearOff { get { if(_tearOff == null) { _tearOff = new TearOffWhereParameter(this); } return _tearOff; } } #region WhereParameter TearOff's public class TearOffWhereParameter { public TearOffWhereParameter(WhereClause clause) { this._clause = clause; } public WhereParameter ID { get { WhereParameter where = new WhereParameter(ColumnNames.ID, Parameters.ID); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter DepartmentID { get { WhereParameter where = new WhereParameter(ColumnNames.DepartmentID, Parameters.DepartmentID); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter FirstName { get { WhereParameter where = new WhereParameter(ColumnNames.FirstName, Parameters.FirstName); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter LastName { get { WhereParameter where = new WhereParameter(ColumnNames.LastName, Parameters.LastName); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Age { get { WhereParameter where = new WhereParameter(ColumnNames.Age, Parameters.Age); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter HireDate { get { WhereParameter where = new WhereParameter(ColumnNames.HireDate, Parameters.HireDate); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Salary { get { WhereParameter where = new WhereParameter(ColumnNames.Salary, Parameters.Salary); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter IsActive { get { WhereParameter where = new WhereParameter(ColumnNames.IsActive, Parameters.IsActive); this._clause._entity.Query.AddWhereParameter(where); return where; } } private WhereClause _clause; } #endregion public WhereParameter ID { get { if(_ID_W == null) { _ID_W = TearOff.ID; } return _ID_W; } } public WhereParameter DepartmentID { get { if(_DepartmentID_W == null) { _DepartmentID_W = TearOff.DepartmentID; } return _DepartmentID_W; } } public WhereParameter FirstName { get { if(_FirstName_W == null) { _FirstName_W = TearOff.FirstName; } return _FirstName_W; } } public WhereParameter LastName { get { if(_LastName_W == null) { _LastName_W = TearOff.LastName; } return _LastName_W; } } public WhereParameter Age { get { if(_Age_W == null) { _Age_W = TearOff.Age; } return _Age_W; } } public WhereParameter HireDate { get { if(_HireDate_W == null) { _HireDate_W = TearOff.HireDate; } return _HireDate_W; } } public WhereParameter Salary { get { if(_Salary_W == null) { _Salary_W = TearOff.Salary; } return _Salary_W; } } public WhereParameter IsActive { get { if(_IsActive_W == null) { _IsActive_W = TearOff.IsActive; } return _IsActive_W; } } private WhereParameter _ID_W = null; private WhereParameter _DepartmentID_W = null; private WhereParameter _FirstName_W = null; private WhereParameter _LastName_W = null; private WhereParameter _Age_W = null; private WhereParameter _HireDate_W = null; private WhereParameter _Salary_W = null; private WhereParameter _IsActive_W = null; public void WhereClauseReset() { _ID_W = null; _DepartmentID_W = null; _FirstName_W = null; _LastName_W = null; _Age_W = null; _HireDate_W = null; _Salary_W = null; _IsActive_W = null; this._entity.Query.FlushWhereParameters(); } private BusinessEntity _entity; private TearOffWhereParameter _tearOff; } public WhereClause Where { get { if(_whereClause == null) { _whereClause = new WhereClause(this); } return _whereClause; } } private WhereClause _whereClause = null; #endregion #region Aggregate Clause public class AggregateClause { public AggregateClause(BusinessEntity entity) { this._entity = entity; } public TearOffAggregateParameter TearOff { get { if(_tearOff == null) { _tearOff = new TearOffAggregateParameter(this); } return _tearOff; } } #region AggregateParameter TearOff's public class TearOffAggregateParameter { public TearOffAggregateParameter(AggregateClause clause) { this._clause = clause; } public AggregateParameter ID { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.ID, Parameters.ID); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter DepartmentID { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.DepartmentID, Parameters.DepartmentID); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter FirstName { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.FirstName, Parameters.FirstName); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter LastName { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.LastName, Parameters.LastName); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter Age { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.Age, Parameters.Age); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter HireDate { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.HireDate, Parameters.HireDate); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter Salary { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.Salary, Parameters.Salary); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter IsActive { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.IsActive, Parameters.IsActive); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } private AggregateClause _clause; } #endregion public AggregateParameter ID { get { if(_ID_W == null) { _ID_W = TearOff.ID; } return _ID_W; } } public AggregateParameter DepartmentID { get { if(_DepartmentID_W == null) { _DepartmentID_W = TearOff.DepartmentID; } return _DepartmentID_W; } } public AggregateParameter FirstName { get { if(_FirstName_W == null) { _FirstName_W = TearOff.FirstName; } return _FirstName_W; } } public AggregateParameter LastName { get { if(_LastName_W == null) { _LastName_W = TearOff.LastName; } return _LastName_W; } } public AggregateParameter Age { get { if(_Age_W == null) { _Age_W = TearOff.Age; } return _Age_W; } } public AggregateParameter HireDate { get { if(_HireDate_W == null) { _HireDate_W = TearOff.HireDate; } return _HireDate_W; } } public AggregateParameter Salary { get { if(_Salary_W == null) { _Salary_W = TearOff.Salary; } return _Salary_W; } } public AggregateParameter IsActive { get { if(_IsActive_W == null) { _IsActive_W = TearOff.IsActive; } return _IsActive_W; } } private AggregateParameter _ID_W = null; private AggregateParameter _DepartmentID_W = null; private AggregateParameter _FirstName_W = null; private AggregateParameter _LastName_W = null; private AggregateParameter _Age_W = null; private AggregateParameter _HireDate_W = null; private AggregateParameter _Salary_W = null; private AggregateParameter _IsActive_W = null; public void AggregateClauseReset() { _ID_W = null; _DepartmentID_W = null; _FirstName_W = null; _LastName_W = null; _Age_W = null; _HireDate_W = null; _Salary_W = null; _IsActive_W = null; this._entity.Query.FlushAggregateParameters(); } private BusinessEntity _entity; private TearOffAggregateParameter _tearOff; } public AggregateClause Aggregate { get { if(_aggregateClause == null) { _aggregateClause = new AggregateClause(this); } return _aggregateClause; } } private AggregateClause _aggregateClause = null; #endregion protected override IDbCommand GetInsertCommand() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_AggregateTestInsert]"; CreateParameters(cmd); SqlParameter p; p = cmd.Parameters[Parameters.ID.ParameterName]; p.Direction = ParameterDirection.Output; return cmd; } protected override IDbCommand GetUpdateCommand() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_AggregateTestUpdate]"; CreateParameters(cmd); return cmd; } protected override IDbCommand GetDeleteCommand() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_AggregateTestDelete]"; SqlParameter p; p = cmd.Parameters.Add(Parameters.ID); p.SourceColumn = ColumnNames.ID; p.SourceVersion = DataRowVersion.Current; return cmd; } private IDbCommand CreateParameters(SqlCommand cmd) { SqlParameter p; p = cmd.Parameters.Add(Parameters.ID); p.SourceColumn = ColumnNames.ID; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.DepartmentID); p.SourceColumn = ColumnNames.DepartmentID; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.FirstName); p.SourceColumn = ColumnNames.FirstName; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.LastName); p.SourceColumn = ColumnNames.LastName; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Age); p.SourceColumn = ColumnNames.Age; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.HireDate); p.SourceColumn = ColumnNames.HireDate; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Salary); p.SourceColumn = ColumnNames.Salary; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.IsActive); p.SourceColumn = ColumnNames.IsActive; p.SourceVersion = DataRowVersion.Current; return cmd; } } }
//--------------------------------------------------------------------------- // // File: HtmlParser.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Parser for Html-to-Xaml converter // //--------------------------------------------------------------------------- using System; using System.Xml; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; // StringBuilder // important TODOS: // TODO 1. Start tags: The ParseXmlElement function has been modified to be called after both the // angle bracket < and element name have been read, instead of just the < bracket and some valid name character, // previously the case. This change was made so that elements with optional closing tags could read a new // element's start tag and decide whether they were required to close. However, there is a question of whether to // handle this in the parser or lexical analyzer. It is currently handled in the parser - the lexical analyzer still // recognizes a start tag opener as a '<' + valid name start char; it is the parser that reads the actual name. // this is correct behavior assuming that the name is a valid html name, because the lexical analyzer should not know anything // about optional closing tags, etc. UPDATED: 10/13/2004: I am updating this to read the whole start tag of something // that is not an HTML, treat it as empty, and add it to the tree. That way the converter will know it's there, but // it will hvae no content. We could also partially recover by trying to look up and match names if they are similar // TODO 2. Invalid element names: However, it might make sense to give the lexical analyzer the ability to identify // a valid html element name and not return something as a start tag otherwise. For example, if we type <good>, should // the lexical analyzer return that it has found the start of an element when this is not the case in HTML? But this will // require implementing a lookahead token in the lexical analyzer so that it can treat an invalid element name as text. One // character of lookahead will not be enough. // TODO 3. Attributes: The attribute recovery is poor when reading attribute values in quotes - if no closing quotes are found, // the lexical analyzer just keeps reading and if it eventually reaches the end of file, it would have just skipped everything. // There are a couple of ways to deal with this: 1) stop reading attributes when we encounter a '>' character - this doesn't allow // the '>' character to be used in attribute values, but it can still be used as an entity. 2) Maintain a HTML-specific list // of attributes and their values that each html element can take, and if we find correct attribute namesand values for an // element we use them regardless of the quotes, this way we could just ignore something invalid. One more option: 3) Read ahead // in the quoted value and if we find an end of file, we can return to where we were and process as text. However this requires // a lot of lookahead and a resettable reader. // TODO 4: elements with optional closing tags: For elements with optional closing tags, we always close the element if we find // that one of it's ancestors has closed. This condition may be too broad and we should develop a better heuristic. We should also // improve the heuristics for closing certain elements when the next element starts // TODO 5. Nesting: Support for unbalanced nesting, e.g. <b> <i> </b> </i>: this is not presently supported. To support it we may need // to maintain two xml elements, one the element that represents what has already been read and another represents what we are presently reading. // Then if we encounter an unbalanced nesting tag we could close the element that was supposed to close, save the current element // and store it in the list of already-read content, and then open a new element to which all tags that are currently open // can be applied. Is there a better way to do this? Should we do it at all? // TODO 6. Elements with optional starting tags: there are 4 such elements in the HTML 4 specification - html, tbody, body and head. // The current recovery doesn;t do anything for any of these elements except the html element, because it's not critical - head // and body elementscan be contained within html element, and tbody is contained within table. To extend this for XHTML // extensions, and to recover in case other elements are missing start tags, we would need to insert an extra recursive call // to ParseXmlElement for the missing start tag. It is suggested to do this by giving ParseXmlElement an argument that specifies // a name to use. If this argument is null, it assumes its name is the next token from the lexical analyzer and continues // exactly as it does now. However, if the argument contains a valid html element name then it takes that value as its name // and continues as before. This way, if the next token is the element that should actually be its child, it will see // the name in the next step and initiate a recursive call. We would also need to add some logic in the loop for when a start tag // is found - if the start tag is not compatible with current context and indicates that a start tag has been missed, then we // can initiate the extra recursive call and give it the name of the missed start tag. The issues are when to insert this logic, // and if we want to support it over multiple missing start tags. If we insert it at the time a start tag is read in element // text, then we can support only one missing start tag, since the extra call will read the next start tag and make a recursive // call without checking the context. This is a conceptual problem, and the check should be made just before a recursive call, // with the choice being whether we should supply an element name as argument, or leave it as NULL and read from the input // TODO 7: Context: Is it appropriate to keep track of context here? For example, should we only expect td, tr elements when // reading a table and ignore them otherwise? This may be too much of a load on the parser, I think it's better if the converter // deals with it namespace HTMLConverter { /// <summary> /// HtmlParser class accepts a string of possibly badly formed Html, parses it and returns a string /// of well-formed Html that is as close to the original string in content as possible /// </summary> internal class HtmlParser { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// Constructor. Initializes the _htmlLexicalAnalayzer element with the given input string /// </summary> /// <param name="inputString"> /// string to parsed into well-formed Html /// </param> private HtmlParser(string inputString) { // Create an output xml document _document = new XmlDocument(); // initialize open tag stack _openedElements = new Stack<XmlElement>(); _pendingInlineElements = new Stack<XmlElement>(); // initialize lexical analyzer _htmlLexicalAnalyzer = new HtmlLexicalAnalyzer(inputString); // get first token from input, expecting text _htmlLexicalAnalyzer.GetNextContentToken(); } #endregion Constructors // --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// Instantiates an HtmlParser element and calls the parsing function on the given input string /// </summary> /// <param name="htmlString"> /// Input string of pssibly badly-formed Html to be parsed into well-formed Html /// </param> /// <returns> /// XmlElement rep /// </returns> internal static XmlElement ParseHtml(string htmlString) { HtmlParser htmlParser = new HtmlParser(htmlString); XmlElement htmlRootElement = htmlParser.ParseHtmlContent(); return htmlRootElement; } // ..................................................................... // // Html Header on Clipboard // // ..................................................................... // Html header structure. // Version:1.0 // StartHTML:000000000 // EndHTML:000000000 // StartFragment:000000000 // EndFragment:000000000 // StartSelection:000000000 // EndSelection:000000000 internal const string HtmlHeader = "Version:1.0\r\nStartHTML:{0:D10}\r\nEndHTML:{1:D10}\r\nStartFragment:{2:D10}\r\nEndFragment:{3:D10}\r\nStartSelection:{4:D10}\r\nEndSelection:{5:D10}\r\n"; internal const string HtmlStartFragmentComment = "<!--StartFragment-->"; internal const string HtmlEndFragmentComment = "<!--EndFragment-->"; /// <summary> /// Extracts Html string from clipboard data by parsing header information in htmlDataString /// </summary> /// <param name="htmlDataString"> /// String representing Html clipboard data. This includes Html header /// </param> /// <returns> /// String containing only the Html data part of htmlDataString, without header /// </returns> internal static string ExtractHtmlFromClipboardData(string htmlDataString) { int startHtmlIndex = htmlDataString.IndexOf("StartHTML:"); if (startHtmlIndex < 0) { return "ERROR: Urecognized html header"; } // TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length), // which could be wrong assumption. We need to implement more flrxible parsing here startHtmlIndex = Int32.Parse(htmlDataString.Substring(startHtmlIndex + "StartHTML:".Length, "0123456789".Length)); if (startHtmlIndex < 0 || startHtmlIndex > htmlDataString.Length) { return "ERROR: Urecognized html header"; } int endHtmlIndex = htmlDataString.IndexOf("EndHTML:"); if (endHtmlIndex < 0) { return "ERROR: Urecognized html header"; } // TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length), // which could be wrong assumption. We need to implement more flrxible parsing here endHtmlIndex = Int32.Parse(htmlDataString.Substring(endHtmlIndex + "EndHTML:".Length, "0123456789".Length)); if (endHtmlIndex > htmlDataString.Length) { endHtmlIndex = htmlDataString.Length; } return htmlDataString.Substring(startHtmlIndex, endHtmlIndex - startHtmlIndex); } /// <summary> /// Adds Xhtml header information to Html data string so that it can be placed on clipboard /// </summary> /// <param name="htmlString"> /// Html string to be placed on clipboard with appropriate header /// </param> /// <returns> /// String wrapping htmlString with appropriate Html header /// </returns> internal static string AddHtmlClipboardHeader(string htmlString) { StringBuilder stringBuilder = new StringBuilder(); // each of 6 numbers is represented by "{0:D10}" in the format string // must actually occupy 10 digit positions ("0123456789") int startHTML = HtmlHeader.Length + 6 * ("0123456789".Length - "{0:D10}".Length); int endHTML = startHTML + htmlString.Length; int startFragment = htmlString.IndexOf(HtmlStartFragmentComment, 0); if (startFragment >= 0) { startFragment = startHTML + startFragment + HtmlStartFragmentComment.Length; } else { startFragment = startHTML; } int endFragment = htmlString.IndexOf(HtmlEndFragmentComment, 0); if (endFragment >= 0) { endFragment = startHTML + endFragment; } else { endFragment = endHTML; } // Create HTML clipboard header string stringBuilder.AppendFormat(HtmlHeader, startHTML, endHTML, startFragment, endFragment, startFragment, endFragment); // Append HTML body. stringBuilder.Append(htmlString); return stringBuilder.ToString(); } #endregion Internal Methods // --------------------------------------------------------------------- // // Private methods // // --------------------------------------------------------------------- #region Private Methods private void InvariantAssert(bool condition, string message) { if (!condition) { throw new Exception("Assertion error: " + message); } } /// <summary> /// Parses the stream of html tokens starting /// from the name of top-level element. /// Returns XmlElement representing the top-level /// html element /// </summary> private XmlElement ParseHtmlContent() { // Create artificial root elelemt to be able to group multiple top-level elements // We create "html" element which may be a duplicate of real HTML element, which is ok, as HtmlConverter will swallow it painlessly.. XmlElement htmlRootElement = _document.CreateElement("html", XhtmlNamespace); OpenStructuringElement(htmlRootElement); while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF) { if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.OpeningTagStart) { _htmlLexicalAnalyzer.GetNextTagToken(); if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name) { string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower(); _htmlLexicalAnalyzer.GetNextTagToken(); // Create an element XmlElement htmlElement = _document.CreateElement(htmlElementName, XhtmlNamespace); // Parse element attributes ParseAttributes(htmlElement); if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.EmptyTagEnd || HtmlSchema.IsEmptyElement(htmlElementName)) { // It is an element without content (because of explicit slash or based on implicit knowledge aboout html) AddEmptyElement(htmlElement); } else if (HtmlSchema.IsInlineElement(htmlElementName)) { // Elements known as formatting are pushed to some special // pending stack, which allows them to be transferred // over block tags - by doing this we convert // overlapping tags into normal heirarchical element structure. OpenInlineElement(htmlElement); } else if (HtmlSchema.IsBlockElement(htmlElementName) || HtmlSchema.IsKnownOpenableElement(htmlElementName)) { // This includes no-scope elements OpenStructuringElement(htmlElement); } else { // Do nothing. Skip the whole opening tag. // Ignoring all unknown elements on their start tags. // Thus we will ignore them on closinng tag as well. // Anyway we don't know what to do withthem on conversion to Xaml. } } else { // Note that the token following opening angle bracket must be a name - lexical analyzer must guarantee that. // Otherwise - we skip the angle bracket and continue parsing the content as if it is just text. // Add the following asserion here, right? or output "<" as a text run instead?: // InvariantAssert(false, "Angle bracket without a following name is not expected"); } } else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.ClosingTagStart) { _htmlLexicalAnalyzer.GetNextTagToken(); if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name) { string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower(); // Skip the name token. Assume that the following token is end of tag, // but do not check this. If it is not true, we simply ignore one token // - this is our recovery from bad xml in this case. _htmlLexicalAnalyzer.GetNextTagToken(); CloseElement(htmlElementName); } } else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Text) { AddTextContent(_htmlLexicalAnalyzer.NextToken); } else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Comment) { AddComment(_htmlLexicalAnalyzer.NextToken); } _htmlLexicalAnalyzer.GetNextContentToken(); } // Get rid of the artificial root element if (htmlRootElement.FirstChild is XmlElement && htmlRootElement.FirstChild == htmlRootElement.LastChild && htmlRootElement.FirstChild.LocalName.ToLower() == "html") { htmlRootElement = (XmlElement)htmlRootElement.FirstChild; } return htmlRootElement; } private XmlElement CreateElementCopy(XmlElement htmlElement) { XmlElement htmlElementCopy = _document.CreateElement(htmlElement.LocalName, XhtmlNamespace); for (int i = 0; i < htmlElement.Attributes.Count; i++) { XmlAttribute attribute = htmlElement.Attributes[i]; htmlElementCopy.SetAttribute(attribute.Name, attribute.Value); } return htmlElementCopy; } private void AddEmptyElement(XmlElement htmlEmptyElement) { InvariantAssert(_openedElements.Count > 0, "AddEmptyElement: Stack of opened elements cannot be empty, as we have at least one artificial root element"); XmlElement htmlParent = _openedElements.Peek(); htmlParent.AppendChild(htmlEmptyElement); } private void OpenInlineElement(XmlElement htmlInlineElement) { _pendingInlineElements.Push(htmlInlineElement); } // Opens structurig element such as Div or Table etc. private void OpenStructuringElement(XmlElement htmlElement) { // Close all pending inline elements // All block elements are considered as delimiters for inline elements // which forces all inline elements to be closed and re-opened in the following // structural element (if any). // By doing that we guarantee that all inline elements appear only within most nested blocks if (HtmlSchema.IsBlockElement(htmlElement.LocalName)) { while (_openedElements.Count > 0 && HtmlSchema.IsInlineElement(_openedElements.Peek().LocalName)) { XmlElement htmlInlineElement = _openedElements.Pop(); InvariantAssert(_openedElements.Count > 0, "OpenStructuringElement: stack of opened elements cannot become empty here"); _pendingInlineElements.Push(CreateElementCopy(htmlInlineElement)); } } // Add this block element to its parent if (_openedElements.Count > 0) { XmlElement htmlParent = _openedElements.Peek(); // Check some known block elements for auto-closing (LI and P) if (HtmlSchema.ClosesOnNextElementStart(htmlParent.LocalName, htmlElement.LocalName)) { _openedElements.Pop(); htmlParent = _openedElements.Count > 0 ? _openedElements.Peek() : null; } if (htmlParent != null) { // NOTE: // Actually we never expect null - it would mean two top-level P or LI (without a parent). // In such weird case we will loose all paragraphs except the first one... htmlParent.AppendChild(htmlElement); } } // Push it onto a stack _openedElements.Push(htmlElement); } private bool IsElementOpened(string htmlElementName) { foreach (XmlElement openedElement in _openedElements) { if (openedElement.LocalName == htmlElementName) { return true; } } return false; } private void CloseElement(string htmlElementName) { // Check if the element is opened and already added to the parent InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element"); // Check if the element is opened and still waiting to be added to the parent if (_pendingInlineElements.Count > 0 && _pendingInlineElements.Peek().LocalName == htmlElementName) { // Closing an empty inline element. // Note that HtmlConverter will skip empty inlines, but for completeness we keep them here on parser level. XmlElement htmlInlineElement = _pendingInlineElements.Pop(); InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element"); XmlElement htmlParent = _openedElements.Peek(); htmlParent.AppendChild(htmlInlineElement); return; } else if (IsElementOpened(htmlElementName)) { while (_openedElements.Count > 1) // we never pop the last element - the artificial root { // Close all unbalanced elements. XmlElement htmlOpenedElement = _openedElements.Pop(); if (htmlOpenedElement.LocalName == htmlElementName) { return; } if (HtmlSchema.IsInlineElement(htmlOpenedElement.LocalName)) { // Unbalances Inlines will be transfered to the next element content _pendingInlineElements.Push(CreateElementCopy(htmlOpenedElement)); } } } // If element was not opened, we simply ignore the unbalanced closing tag return; } private void AddTextContent(string textContent) { OpenPendingInlineElements(); InvariantAssert(_openedElements.Count > 0, "AddTextContent: Stack of opened elements cannot be empty, as we have at least one artificial root element"); XmlElement htmlParent = _openedElements.Peek(); XmlText textNode = _document.CreateTextNode(textContent); htmlParent.AppendChild(textNode); } private void AddComment(string comment) { OpenPendingInlineElements(); InvariantAssert(_openedElements.Count > 0, "AddComment: Stack of opened elements cannot be empty, as we have at least one artificial root element"); XmlElement htmlParent = _openedElements.Peek(); XmlComment xmlComment = _document.CreateComment(comment); htmlParent.AppendChild(xmlComment); } // Moves all inline elements pending for opening to actual document // and adds them to current open stack. private void OpenPendingInlineElements() { if (_pendingInlineElements.Count > 0) { XmlElement htmlInlineElement = _pendingInlineElements.Pop(); OpenPendingInlineElements(); InvariantAssert(_openedElements.Count > 0, "OpenPendingInlineElements: Stack of opened elements cannot be empty, as we have at least one artificial root element"); XmlElement htmlParent = _openedElements.Peek(); htmlParent.AppendChild(htmlInlineElement); _openedElements.Push(htmlInlineElement); } } private void ParseAttributes(XmlElement xmlElement) { while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF && // _htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.TagEnd && // _htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EmptyTagEnd) { // read next attribute (name=value) if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name) { string attributeName = _htmlLexicalAnalyzer.NextToken; _htmlLexicalAnalyzer.GetNextEqualSignToken(); _htmlLexicalAnalyzer.GetNextAtomToken(); string attributeValue = _htmlLexicalAnalyzer.NextToken; xmlElement.SetAttribute(attributeName, attributeValue); } _htmlLexicalAnalyzer.GetNextTagToken(); } } #endregion Private Methods // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields internal const string XhtmlNamespace = "http://www.w3.org/1999/xhtml"; private HtmlLexicalAnalyzer _htmlLexicalAnalyzer; // document from which all elements are created private XmlDocument _document; // stack for open elements Stack<XmlElement> _openedElements; Stack<XmlElement> _pendingInlineElements; #endregion Private Fields } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using Aurora.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; namespace Aurora.Modules.Chat { public class OfflineMessageModule : ISharedRegionModule { private readonly List<IScene> m_SceneList = new List<IScene>(); private bool enabled = true; private bool m_ForwardOfflineGroupMessages = true; private string m_RestURL = String.Empty; #region ISharedRegionModule Members public void Initialise(IConfigSource config) { IConfig cnf = config.Configs["Messaging"]; if (cnf == null) { enabled = false; return; } if (cnf != null && cnf.GetString("OfflineMessageModule", "None") != "OfflineMessageModule") { enabled = false; return; } m_RestURL = cnf.GetString("OfflineMessageURL", ""); if (m_RestURL == "") { MainConsole.Instance.Error("[OFFLINE MESSAGING] Module was enabled, but no URL is given, disabling"); enabled = false; return; } m_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", m_ForwardOfflineGroupMessages); } public void AddRegion(IScene scene) { if (!enabled) return; lock (m_SceneList) m_SceneList.Add(scene); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnClosingClient += OnClosingClient; } public void RegionLoaded(IScene scene) { if (!enabled) return; if (scene.RequestModuleInterface<IMessageTransferModule>() == null) { scene.EventManager.OnNewClient -= OnNewClient; enabled = false; m_SceneList.Clear(); MainConsole.Instance.Error("[OFFLINE MESSAGING] No message transfer module is enabled. Diabling offline messages"); } else scene.RequestModuleInterface<IMessageTransferModule>().OnUndeliveredMessage += UndeliveredMessage; } public void RemoveRegion(IScene scene) { if (!enabled) return; lock (m_SceneList) m_SceneList.Remove(scene); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnClosingClient -= OnClosingClient; } public void PostInitialise() { if (!enabled) return; MainConsole.Instance.Debug("[OFFLINE MESSAGING] Offline messages enabled"); } public string Name { get { return "OfflineMessageModule"; } } public Type ReplaceableInterface { get { return null; } } public void Close() { } #endregion private IScene FindScene(UUID agentID) { return (from s in m_SceneList let presence = s.GetScenePresence(agentID) where presence != null && !presence.IsChildAgent select s).FirstOrDefault(); } private IClientAPI FindClient(UUID agentID) { return (from s in m_SceneList select s.GetScenePresence(agentID) into presence where presence != null && !presence.IsChildAgent select presence.ControllingClient). FirstOrDefault(); } private void OnNewClient(IClientAPI client) { client.OnRetrieveInstantMessages += RetrieveInstantMessages; } private void OnClosingClient(IClientAPI client) { client.OnRetrieveInstantMessages -= RetrieveInstantMessages; } private void RetrieveInstantMessages(IClientAPI client) { if (m_RestURL != "") { MainConsole.Instance.DebugFormat("[OFFLINE MESSAGING] Retrieving stored messages for {0}", client.AgentId); List<GridInstantMessage> msglist = SynchronousRestObjectRequester.MakeRequest <UUID, List<GridInstantMessage>>( "POST", m_RestURL + "/RetrieveMessages/", client.AgentId); foreach (GridInstantMessage im in msglist) { // client.SendInstantMessage(im); // Send through scene event manager so all modules get a chance // to look at this message before it gets delivered. // // Needed for proper state management for stored group // invitations // IScene s = FindScene(client.AgentId); if (s != null) s.EventManager.TriggerIncomingInstantMessage(im); } } } private void UndeliveredMessage(GridInstantMessage im, string reason) { if ((im.offline != 0) && (!im.fromGroup || (im.fromGroup && m_ForwardOfflineGroupMessages))) { bool success = SynchronousRestObjectRequester.MakeRequest<GridInstantMessage, bool>( "POST", m_RestURL + "/SaveMessage/", im); if (im.dialog == (byte) InstantMessageDialog.MessageFromAgent) { IClientAPI client = FindClient(im.fromAgentID); if (client == null) return; client.SendInstantMessage(new GridInstantMessage( null, im.toAgentID, "System", im.fromAgentID, (byte) InstantMessageDialog.MessageFromAgent, "User is not logged in. " + (success ? "Message saved." : "Message not saved"), false, new Vector3())); } } } } }
using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Linq; using System.Reflection; // ReSharper disable UnusedMember.Global #if BUILD_PEANUTBUTTER_INTERNAL namespace Imported.PeanutButter.Utils #else namespace PeanutButter.Utils #endif { /// <summary> /// Differentiates between PropertyOrField storage for properties or fields /// </summary> #if BUILD_PEANUTBUTTER_INTERNAL internal #else public #endif enum PropertyOrFieldTypes { /// <summary> /// This member is a Property /// </summary> Property, /// <summary> /// This member is a Field /// </summary> Field } /// <summary> /// Represents a property or a field on an object /// </summary> #if BUILD_PEANUTBUTTER_INTERNAL internal #else public #endif interface IPropertyOrField { /// <summary> /// Name of the property or field /// </summary> string Name { get; } /// <summary> /// Type of the property or field /// </summary> Type Type { get; } /// <summary> /// Write access to property or field /// </summary> bool CanWrite { get; } /// <summary> /// Read access to property or field /// </summary> bool CanRead { get; } /// <summary> /// The type on which this property or field is declared /// </summary> Type DeclaringType { get; } /// <summary> /// The type from which this property or field is read /// - this may not be the DeclaringType as the property /// or field may be inherited /// - this must be explicitly provided by callers /// </summary> Type HostingType { get; } /// <summary> /// Returns the ancestral distance between the DeclaringType /// and the HostingType (0 if they are the same type) /// </summary> int AncestralDistance { get; } /// <summary> /// Gets the value of the property or field for the provided host /// </summary> /// <param name="host"></param> /// <returns></returns> object GetValue(object host); /// <summary> /// Attempts to get the value of the property /// - if the getter throws, returns false and the output exception is set /// - if the getter succeeds, returns true and the output value is set /// </summary> /// <param name="host"></param> /// <param name="value"></param> /// <param name="exception"></param> /// <returns></returns> bool TryGetValue(object host, out object value, out Exception exception); /// <summary> /// Sets the value of the property or field on the provided host /// </summary> /// <param name="host"></param> /// <param name="value"></param> void SetValue(object host, object value); /// <summary> /// Sets the value for the field or property /// as found on the provided host /// </summary> /// <param name="host"></param> /// <param name="value"></param> /// <typeparam name="T"></typeparam> void SetValue<T>(ref T host, object value); } /// <summary> /// Provides a single storage / representation /// for a Property or a Field /// </summary> [DebuggerDisplay("{MemberType} {Type} {Name} read: {CanRead} write: {CanWrite}")] #if BUILD_PEANUTBUTTER_INTERNAL internal #else public #endif class PropertyOrField : IPropertyOrField { /// <summary> /// Creates a PropertyOrField container for a provided PropertyInfo /// </summary> /// <param name="propertyInfo"></param> /// <returns></returns> public static PropertyOrField Create(PropertyInfo propertyInfo) { return new PropertyOrField(propertyInfo); } /// <summary> /// Creates a PropertyOrField container for a provided FieldInfo /// </summary> /// <param name="fieldInfo"></param> /// <returns></returns> public static PropertyOrField Create(FieldInfo fieldInfo) { return new PropertyOrField(fieldInfo); } private static readonly BindingFlags SearchBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; /// <summary> /// Attempts to find a property or field with the given name on /// a type - will scan public, private, static and instance properties /// and fields. It's up to the caller to know what do to with that (: /// </summary> /// <param name="type"></param> /// <param name="name"></param> /// <exception cref="ArgumentException">thrown when the property or field is not found</exception> /// <returns></returns> public static PropertyOrField Find( Type type, string name ) { return TryFind(type, name) ?? throw new ArgumentException( $"No property or field named '{name}' found on type '{type}'", nameof(name) ); } private static readonly ConcurrentDictionary<Tuple<Type, string>, PropertyOrField> FindCache = new(); /// <summary> /// Attempts to find a property or field with the given name on /// a type - will scan public, private, static and instance properties /// and fields. It's up to the caller to know what do to with that (: /// </summary> /// <param name="type"></param> /// <param name="name"></param> /// <returns></returns> public static PropertyOrField TryFind( Type type, string name ) { var cacheKey = Tuple.Create(type, name); if (FindCache.TryGetValue(cacheKey, out var result)) { return result; } var propInfo = type.GetProperties( SearchBindingFlags ).FirstOrDefault(pi => pi.Name == name); if (propInfo is not null) { result = Create(propInfo); FindCache.TryAdd(cacheKey, result); return result; } var fieldInfo = type.GetFields( SearchBindingFlags ).FirstOrDefault(fi => fi.Name == name); if (fieldInfo is null) { FindCache.TryAdd(cacheKey, null); return null; } result = Create(fieldInfo); FindCache.TryAdd(cacheKey, result); return result; } /// <inheritdoc /> public string Name { get; } /// <inheritdoc /> public Type Type { get; } /// <inheritdoc /> public bool CanWrite { get; } /// <inheritdoc /> public bool CanRead { get; } /// <summary> /// Is this a Property or a Field? /// </summary> #if BUILD_PEANUTBUTTER_INTERNAL internal #else public #endif PropertyOrFieldTypes MemberType { get; } /// <inheritdoc /> public Type DeclaringType { get; } /// <inheritdoc /> public Type HostingType { get; } /// <inheritdoc /> public int AncestralDistance { get; } private readonly Func<object, object> _getValue; private readonly Action<object, object> _setValue; /// <summary> /// Constructs the PropertyOrField around a property /// </summary> /// <param name="prop"></param> public PropertyOrField( PropertyInfo prop ) : this(prop, prop.DeclaringType) { } /// <summary> /// Constructs the PropertyOrField around a property, relative /// to an hosting type (ie, without assuming that the DeclaringType /// is the hosting type for the property) /// </summary> /// <param name="prop"></param> /// <param name="hostingType"></param> public PropertyOrField( PropertyInfo prop, Type hostingType ) { if (prop is null) { throw new ArgumentNullException(nameof(prop)); } _getValue = prop.GetValue; _setValue = prop.SetValue; Name = prop.Name; Type = prop.PropertyType; DeclaringType = prop.DeclaringType; MemberType = PropertyOrFieldTypes.Property; CanRead = prop.CanRead; CanWrite = prop.CanWrite; HostingType = hostingType ?? throw new ArgumentNullException(nameof(hostingType)); AncestralDistance = CalculateAncestralDistance(); } /// <summary> /// Implicitly converts a PropertyInfo object to a PropertyOrField /// </summary> /// <param name="prop"></param> /// <returns></returns> public static implicit operator PropertyOrField(PropertyInfo prop) { return new PropertyOrField(prop); } /// <summary> /// Implicitly converts a FieldInfo object to a FieldOrField /// </summary> /// <param name="field"></param> /// <returns></returns> public static implicit operator PropertyOrField( FieldInfo field ) { return new PropertyOrField(field); } /// <summary> /// Constructs the PropertyOrField around a field /// </summary> /// <param name="field"></param> public PropertyOrField( FieldInfo field ) : this(field, field.DeclaringType) { } /// <summary> /// Constructs the PropertyOrField around a field /// </summary> /// <param name="field"></param> /// <param name="hostingType"></param> public PropertyOrField( FieldInfo field, Type hostingType ) { if (field is null) { throw new ArgumentNullException(nameof(field)); } _getValue = field.GetValue; _setValue = field.SetValue; Name = field.Name; Type = field.FieldType; DeclaringType = field.DeclaringType; MemberType = PropertyOrFieldTypes.Field; CanRead = true; CanWrite = true; HostingType = hostingType ?? throw new ArgumentNullException(nameof(hostingType)); AncestralDistance = CalculateAncestralDistance(); } /// <inheritdoc /> public object GetValue(object host) { return _getValue(host); } /// <inheritdoc /> public bool TryGetValue(object host, out object value, out Exception exception) { try { exception = default; value = GetValue(host); return true; } catch (Exception ex) { value = default; exception = ex; return false; } } /// <inheritdoc /> public void SetValue(object host, object value) { if (value is null) { if (!Type.IsNullableType()) { throw new ArgumentException($"Cannot set type {Type} to null"); } _setValue(host, null); return; } if (!value.TryImplicitlyCastTo(Type, out var castValue)) { throw new ArgumentException( $"Cannot set value '{value}' of type {value.GetType()} for target {Type}" ); } _setValue(host, castValue); } /// <inheritdoc /> public void SetValue<T>(ref T host, object value) { var asObject = (object)host; _setValue(asObject, value); // required for referenced by-val sets to work (ie struct values) host = (T)asObject; } private int CalculateAncestralDistance() { if (DeclaringType == HostingType) { return 0; } var result = 0; var current = HostingType; while ( current != typeof(object) && current != DeclaringType ) { result++; current = current?.BaseType; } if (current is null && DeclaringType != typeof(object)) { throw new ArgumentException( $"{DeclaringType} is not an ancestor of {HostingType}" ); } return result; } } }
#region File Description //----------------------------------------------------------------------------- // ContentBuilder.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using BaamStudios.AnimationExtractorPipeline; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; #endregion namespace BaamStudios.AnimationExtractor { /// <summary> /// This class wraps the MSBuild functionality needed to build XNA Framework /// content dynamically at runtime. It creates a temporary MSBuild project /// in memory, and adds whatever content files you choose to this project. /// It then builds the project, which will create compiled .xnb content files /// in a temporary directory. After the build finishes, you can use a regular /// ContentManager to load these temporary .xnb files in the usual way. /// </summary> class ContentBuilder : IDisposable { #region Fields // What importers or processors should we load? const string xnaVersion = ", Version=4.0.0.0, PublicKeyToken=842cf8be1de50553"; static string[] pipelineAssemblies = { "Microsoft.Xna.Framework.Content.Pipeline.FBXImporter" + xnaVersion, "Microsoft.Xna.Framework.Content.Pipeline.XImporter" + xnaVersion, "Microsoft.Xna.Framework.Content.Pipeline.TextureImporter" + xnaVersion, "Microsoft.Xna.Framework.Content.Pipeline.EffectImporter" + xnaVersion, // If you want to use custom importers or processors from // a Content Pipeline Extension Library, add them here. // // If your extension DLL is installed in the GAC, you should refer to it by assembly // name, eg. "MyPipelineExtension, Version=1.0.0.0, PublicKeyToken=1234567812345678". // // If the extension DLL is not in the GAC, you should refer to it by // file path, eg. "c:/MyProject/bin/MyPipelineExtension.dll". Assembly.GetAssembly(typeof(AnimationExtractorModelProcessor)).Location }; // MSBuild objects used to dynamically build content. Project buildProject; ProjectRootElement projectRootElement; BuildParameters buildParameters; List<ProjectItem> projectItems = new List<ProjectItem>(); ErrorLogger errorLogger; // Temporary directories used by the content build. string buildDirectory; string processDirectory; string baseDirectory; // Generate unique directory names if there is more than one ContentBuilder. static int directorySalt; // Have we been disposed? bool isDisposed; #endregion #region Properties /// <summary> /// Gets the output directory, which will contain the generated .xnb files. /// </summary> public string OutputDirectory { get { return Path.Combine(buildDirectory, "bin/Content"); } } #endregion #region Initialization /// <summary> /// Creates a new content builder. /// </summary> public ContentBuilder() { CreateTempDirectory(); CreateBuildProject(); } /// <summary> /// Finalizes the content builder. /// </summary> ~ContentBuilder() { Dispose(false); } /// <summary> /// Disposes the content builder when it is no longer required. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Implements the standard .NET IDisposable pattern. /// </summary> protected virtual void Dispose(bool disposing) { if (!isDisposed) { isDisposed = true; DeleteTempDirectory(); } } #endregion #region MSBuild /// <summary> /// Creates a temporary MSBuild content project in memory. /// </summary> void CreateBuildProject() { string projectPath = Path.Combine(buildDirectory, "content.contentproj"); string outputPath = Path.Combine(buildDirectory, "bin"); // Create the build project. projectRootElement = ProjectRootElement.Create(projectPath); // Include the standard targets file that defines how to build XNA Framework content. projectRootElement.AddImport("$(MSBuildExtensionsPath)\\Microsoft\\XNA Game Studio\\" + "v4.0\\Microsoft.Xna.GameStudio.ContentPipeline.targets"); buildProject = new Project(projectRootElement); buildProject.SetProperty("XnaPlatform", "Windows"); buildProject.SetProperty("XnaProfile", "Reach"); buildProject.SetProperty("XnaFrameworkVersion", "v4.0"); buildProject.SetProperty("Configuration", "Release"); buildProject.SetProperty("OutputPath", outputPath); // Register any custom importers or processors. foreach (string pipelineAssembly in pipelineAssemblies) { buildProject.AddItem("Reference", pipelineAssembly); } // Hook up our custom error logger. errorLogger = new ErrorLogger(); buildParameters = new BuildParameters(ProjectCollection.GlobalProjectCollection); buildParameters.Loggers = new ILogger[] { errorLogger }; } /// <summary> /// Adds a new content file to the MSBuild project. The importer and /// processor are optional: if you leave the importer null, it will /// be autodetected based on the file extension, and if you leave the /// processor null, data will be passed through without any processing. /// </summary> public void Add(string filename, string name, string importer, string processor) { ProjectItem item = buildProject.AddItem("Compile", filename)[0]; item.SetMetadataValue("Link", Path.GetFileName(filename)); item.SetMetadataValue("Name", name); if (!string.IsNullOrEmpty(importer)) item.SetMetadataValue("Importer", importer); if (!string.IsNullOrEmpty(processor)) item.SetMetadataValue("Processor", processor); projectItems.Add(item); } /// <summary> /// Removes all content files from the MSBuild project. /// </summary> public void Clear() { buildProject.RemoveItems(projectItems); projectItems.Clear(); } /// <summary> /// Builds all the content files which have been added to the project, /// dynamically creating .xnb files in the OutputDirectory. /// Returns an error message if the build fails. /// </summary> public string Build() { // Clear any previous errors. errorLogger.Errors.Clear(); // Create and submit a new asynchronous build request. BuildManager.DefaultBuildManager.BeginBuild(buildParameters); BuildRequestData request = new BuildRequestData(buildProject.CreateProjectInstance(), new string[0]); BuildSubmission submission = BuildManager.DefaultBuildManager.PendBuildRequest(request); submission.ExecuteAsync(null, null); // Wait for the build to finish. submission.WaitHandle.WaitOne(); BuildManager.DefaultBuildManager.EndBuild(); // If the build failed, return an error string. if (submission.BuildResult.OverallResult == BuildResultCode.Failure) { return string.Join("\n", errorLogger.Errors.ToArray()); } return null; } #endregion #region Temp Directories /// <summary> /// Creates a temporary directory in which to build content. /// </summary> void CreateTempDirectory() { // Start with a standard base name: // // %temp%\WinFormsContentLoading.ContentBuilder baseDirectory = Path.Combine(Path.GetTempPath(), GetType().FullName); // Include our process ID, in case there is more than // one copy of the program running at the same time: // // %temp%\WinFormsContentLoading.ContentBuilder\<ProcessId> int processId = Process.GetCurrentProcess().Id; processDirectory = Path.Combine(baseDirectory, processId.ToString()); // Include a salt value, in case the program // creates more than one ContentBuilder instance: // // %temp%\WinFormsContentLoading.ContentBuilder\<ProcessId>\<Salt> directorySalt++; buildDirectory = Path.Combine(processDirectory, directorySalt.ToString()); // Create our temporary directory. Directory.CreateDirectory(buildDirectory); PurgeStaleTempDirectories(); } /// <summary> /// Deletes our temporary directory when we are finished with it. /// </summary> void DeleteTempDirectory() { Directory.Delete(buildDirectory, true); // If there are no other instances of ContentBuilder still using their // own temp directories, we can delete the process directory as well. if (Directory.GetDirectories(processDirectory).Length == 0) { Directory.Delete(processDirectory); // If there are no other copies of the program still using their // own temp directories, we can delete the base directory as well. if (Directory.GetDirectories(baseDirectory).Length == 0) { Directory.Delete(baseDirectory); } } } /// <summary> /// Ideally, we want to delete our temp directory when we are finished using /// it. The DeleteTempDirectory method (called by whichever happens first out /// of Dispose or our finalizer) does exactly that. Trouble is, sometimes /// these cleanup methods may never execute. For instance if the program /// crashes, or is halted using the debugger, we never get a chance to do /// our deleting. The next time we start up, this method checks for any temp /// directories that were left over by previous runs which failed to shut /// down cleanly. This makes sure these orphaned directories will not just /// be left lying around forever. /// </summary> void PurgeStaleTempDirectories() { // Check all subdirectories of our base location. foreach (string directory in Directory.GetDirectories(baseDirectory)) { // The subdirectory name is the ID of the process which created it. int processId; if (int.TryParse(Path.GetFileName(directory), out processId)) { try { // Is the creator process still running? Process.GetProcessById(processId); } catch (ArgumentException) { // If the process is gone, we can delete its temp directory. Directory.Delete(directory, true); } } } } #endregion } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.NATV2Binding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonVLANFilterList))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBNATV2NATStatistics))] public partial class LocalLBNATV2 : iControlInterface { public LocalLBNATV2() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] public void create( string [] nats, string [] orig_addrs, string [] trans_addrs, string [] traffic_groups, CommonVLANFilterList [] vlans ) { this.Invoke("create", new object [] { nats, orig_addrs, trans_addrs, traffic_groups, vlans}); } public System.IAsyncResult Begincreate(string [] nats,string [] orig_addrs,string [] trans_addrs,string [] traffic_groups,CommonVLANFilterList [] vlans, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { nats, orig_addrs, trans_addrs, traffic_groups, vlans}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_nats //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] public void delete_all_nats( ) { this.Invoke("delete_all_nats", new object [0]); } public System.IAsyncResult Begindelete_all_nats(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_nats", new object[0], callback, asyncState); } public void Enddelete_all_nats(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_nat //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] public void delete_nat( string [] nats ) { this.Invoke("delete_nat", new object [] { nats}); } public System.IAsyncResult Begindelete_nat(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_nat", new object[] { nats}, callback, asyncState); } public void Enddelete_nat(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBNATV2NATStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((LocalLBNATV2NATStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public LocalLBNATV2NATStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBNATV2NATStatistics)(results[0])); } //----------------------------------------------------------------------- // get_arp_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_arp_state( string [] nats ) { object [] results = this.Invoke("get_arp_state", new object [] { nats}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_arp_state(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_arp_state", new object[] { nats}, callback, asyncState); } public CommonEnabledState [] Endget_arp_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_auto_lasthop //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonAutoLasthop [] get_auto_lasthop( string [] nats ) { object [] results = this.Invoke("get_auto_lasthop", new object [] { nats}); return ((CommonAutoLasthop [])(results[0])); } public System.IAsyncResult Beginget_auto_lasthop(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_auto_lasthop", new object[] { nats}, callback, asyncState); } public CommonAutoLasthop [] Endget_auto_lasthop(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonAutoLasthop [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] nats ) { object [] results = this.Invoke("get_description", new object [] { nats}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { nats}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_enabled_state( string [] nats ) { object [] results = this.Invoke("get_enabled_state", new object [] { nats}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_enabled_state(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_enabled_state", new object[] { nats}, callback, asyncState); } public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_origin_address //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_origin_address( string [] nats ) { object [] results = this.Invoke("get_origin_address", new object [] { nats}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_origin_address(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_origin_address", new object[] { nats}, callback, asyncState); } public string [] Endget_origin_address(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBNATV2NATStatistics get_statistics( string [] nats ) { object [] results = this.Invoke("get_statistics", new object [] { nats}); return ((LocalLBNATV2NATStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { nats}, callback, asyncState); } public LocalLBNATV2NATStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBNATV2NATStatistics)(results[0])); } //----------------------------------------------------------------------- // get_traffic_group //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_traffic_group( string [] nats ) { object [] results = this.Invoke("get_traffic_group", new object [] { nats}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_traffic_group(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_traffic_group", new object[] { nats}, callback, asyncState); } public string [] Endget_traffic_group(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_translation_address //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_translation_address( string [] nats ) { object [] results = this.Invoke("get_translation_address", new object [] { nats}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_translation_address(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_translation_address", new object[] { nats}, callback, asyncState); } public string [] Endget_translation_address(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_vlan //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonVLANFilterList [] get_vlan( string [] nats ) { object [] results = this.Invoke("get_vlan", new object [] { nats}); return ((CommonVLANFilterList [])(results[0])); } public System.IAsyncResult Beginget_vlan(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vlan", new object[] { nats}, callback, asyncState); } public CommonVLANFilterList [] Endget_vlan(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonVLANFilterList [])(results[0])); } //----------------------------------------------------------------------- // is_traffic_group_inherited //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_traffic_group_inherited( string [] nats ) { object [] results = this.Invoke("is_traffic_group_inherited", new object [] { nats}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_traffic_group_inherited(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_traffic_group_inherited", new object[] { nats}, callback, asyncState); } public bool [] Endis_traffic_group_inherited(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] public void reset_statistics( string [] nats ) { this.Invoke("reset_statistics", new object [] { nats}); } public System.IAsyncResult Beginreset_statistics(string [] nats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { nats}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_arp_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] public void set_arp_state( string [] nats, CommonEnabledState [] states ) { this.Invoke("set_arp_state", new object [] { nats, states}); } public System.IAsyncResult Beginset_arp_state(string [] nats,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_arp_state", new object[] { nats, states}, callback, asyncState); } public void Endset_arp_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_auto_lasthop //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] public void set_auto_lasthop( string [] nats, CommonAutoLasthop [] values ) { this.Invoke("set_auto_lasthop", new object [] { nats, values}); } public System.IAsyncResult Beginset_auto_lasthop(string [] nats,CommonAutoLasthop [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_auto_lasthop", new object[] { nats, values}, callback, asyncState); } public void Endset_auto_lasthop(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] public void set_description( string [] nats, string [] descriptions ) { this.Invoke("set_description", new object [] { nats, descriptions}); } public System.IAsyncResult Beginset_description(string [] nats,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { nats, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] public void set_enabled_state( string [] nats, CommonEnabledState [] states ) { this.Invoke("set_enabled_state", new object [] { nats, states}); } public System.IAsyncResult Beginset_enabled_state(string [] nats,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_enabled_state", new object[] { nats, states}, callback, asyncState); } public void Endset_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_origin_address //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] public void set_origin_address( string [] nats, string [] addrs ) { this.Invoke("set_origin_address", new object [] { nats, addrs}); } public System.IAsyncResult Beginset_origin_address(string [] nats,string [] addrs, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_origin_address", new object[] { nats, addrs}, callback, asyncState); } public void Endset_origin_address(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_traffic_group //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] public void set_traffic_group( string [] nats, string [] traffic_groups ) { this.Invoke("set_traffic_group", new object [] { nats, traffic_groups}); } public System.IAsyncResult Beginset_traffic_group(string [] nats,string [] traffic_groups, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_traffic_group", new object[] { nats, traffic_groups}, callback, asyncState); } public void Endset_traffic_group(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_vlan //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NATV2", RequestNamespace="urn:iControl:LocalLB/NATV2", ResponseNamespace="urn:iControl:LocalLB/NATV2")] public void set_vlan( string [] nats, CommonVLANFilterList [] vlans ) { this.Invoke("set_vlan", new object [] { nats, vlans}); } public System.IAsyncResult Beginset_vlan(string [] nats,CommonVLANFilterList [] vlans, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_vlan", new object[] { nats, vlans}, callback, asyncState); } public void Endset_vlan(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.NATV2.NATStatisticEntry", Namespace = "urn:iControl")] public partial class LocalLBNATV2NATStatisticEntry { private string natField; public string nat { get { return this.natField; } set { this.natField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.NATV2.NATStatistics", Namespace = "urn:iControl")] public partial class LocalLBNATV2NATStatistics { private LocalLBNATV2NATStatisticEntry [] statisticsField; public LocalLBNATV2NATStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.IO; using System.Linq.Expressions; using System.Web.UI; using Glass.Mapper.Sc.IoC; using Sitecore.Data.Items; namespace Glass.Mapper.Sc.Web.Ui { /// <summary> /// Class AbstractGlassUserControl /// </summary> public abstract class AbstractGlassUserControl : UserControl { private TextWriter _writer; private IRenderingContext _renderingContext; private ISitecoreContext _sitecoreContext; private IGlassHtml _glassHtml; protected AbstractGlassUserControl(ISitecoreContextFactory sitecoreContextFactory) { SitecoreContextFactory = sitecoreContextFactory; } protected AbstractGlassUserControl(ISitecoreContext context, IGlassHtml glassHtml, IRenderingContext renderingContext) : this(IoC.SitecoreContextFactory.Default) { _renderingContext = renderingContext; _glassHtml = glassHtml; _sitecoreContext = context; } /// <summary> /// Initializes a new instance of the <see cref="AbstractGlassUserControl"/> class. /// </summary> /// <param name="context">The context.</param> /// <param name="glassHtml">The glass html</param> protected AbstractGlassUserControl(ISitecoreContext context, IGlassHtml glassHtml) : this(context, glassHtml, null) { } protected AbstractGlassUserControl(ISitecoreContext context) : this(context, ((Sc.IoC.DependencyResolver)context.GlassContext.DependencyResolver).GlassHtmlFactory.GetGlassHtml(context)) { } /// <summary> /// Initializes a new instance of the <see cref="AbstractGlassUserControl"/> class. /// </summary> protected AbstractGlassUserControl() : this(IoC.SitecoreContextFactory.Default) { } public ISitecoreContextFactory SitecoreContextFactory { get; protected set; } public virtual IRenderingContext RenderingContext { get { return _renderingContext ?? (_renderingContext = new RenderingContextUserControlWrapper(this)); } set { _renderingContext = value; } } protected TextWriter Output { get { return _writer ?? this.Response.Output; } } /// <summary> /// Gets a value indicating whether this instance is in editing mode. /// </summary> /// <value><c>true</c> if this instance is in editing mode; otherwise, <c>false</c>.</value> public bool IsInEditingMode { get { return Sc.GlassHtml.IsInEditingMode; } } /// <summary> /// Represents the current Sitecore context /// </summary> /// <value>The sitecore context.</value> public virtual ISitecoreContext SitecoreContext { get { return _sitecoreContext ?? ( _sitecoreContext = SitecoreContextFactory.GetSitecoreContext()); } set { _sitecoreContext = value; } } /// <summary> /// Access to rendering helpers /// </summary> /// <value>The glass HTML.</value> public virtual IGlassHtml GlassHtml { get { return _glassHtml ??( _glassHtml = SitecoreContext.GlassHtml); } set { _glassHtml = value; } } /// <summary> /// The custom data source for the sublayout /// </summary> /// <value>The data source.</value> public string DataSource { get { return RenderingContext.GetDataSource(); } } /// <summary> /// Returns either the item specified by the DataSource or the current context item /// </summary> /// <value>The layout item.</value> public Item LayoutItem { get { return DataSourceItem ?? ContextItem; } } /// <summary> /// Returns either the item specified by the current context item /// </summary> /// <value>The layout item.</value> public Item ContextItem { get { return Sitecore.Context.Item; } } /// <summary> /// Returns the item specificed by the data source only. Returns null if no datasource set /// </summary> public Item DataSourceItem { get { return DataSource.IsNullOrEmpty() ? null : Sitecore.Context.Database.GetItem(DataSource); } } /// <summary> /// Returns the Context Item as strongly typed /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T GetContextItem<T>(bool isLazy = false, bool inferType = false) where T : class { return SitecoreContext.GetCurrentItem<T>(isLazy, inferType); } /// <summary> /// Returns the Data Source Item as strongly typed /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T GetDataSourceItem<T>(bool isLazy = false, bool inferType = false) where T : class { string dataSource = RenderingContext.GetDataSource(); return !String.IsNullOrEmpty(dataSource) ? SitecoreContext.GetItem<T>(dataSource, isLazy, inferType) : null; } /// <summary> /// Returns the DataSource item or the Context Item as strongly typed /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T GetLayoutItem<T>(bool isLazy = false, bool inferType = false) where T : class { string dataSource = RenderingContext.GetDataSource(); return !String.IsNullOrEmpty(dataSource) ? GetDataSourceItem<T>(isLazy, inferType) : GetContextItem<T>(isLazy, inferType); } /// <summary> /// Makes a field editable via the Page Editor. Use the Model property as the target item, e.g. model =&gt; model.Title where Title is field name. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model">The model.</param> /// <param name="field">The field.</param> /// <param name="parameters">The parameters.</param> /// <returns>System.String.</returns> public string Editable<T>(T model, Expression<Func<T, object>> field, object parameters = null) { return GlassHtml.Editable(model, field, parameters); } /// <summary> /// Makes a field editable via the Page Editor. Use the Model property as the target item, e.g. model =&gt; model.Title where Title is field name. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model">The model.</param> /// <param name="field">The field.</param> /// <param name="standardOutput">The standard output.</param> /// <param name="parameters">The parameters.</param> /// <returns>System.String.</returns> public string Editable<T>(T model, Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, object parameters = null) { return GlassHtml.Editable(model, field, standardOutput, parameters); } /// <summary> /// Renders an image allowing simple page editor support /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model that contains the image field</param> /// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param> /// <param name="parameters">Image parameters, e.g. width, height</param> /// <param name="isEditable">Indicates if the field should be editable</param> /// <param name="outputHeightWidth">Indicates if the height and width attributes should be outputted when rendering the image</param> /// <returns></returns> public virtual string RenderImage<T>(T model, Expression<Func<T, object>> field, object parameters = null, bool isEditable = false, bool outputHeightWidth = true) { return GlassHtml.RenderImage(model, field, parameters, isEditable, outputHeightWidth); } /// <summary> /// Render HTML for a link with contents /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model</param> /// <param name="field">The link field to user</param> /// <param name="attributes">Any additional link attributes</param> /// <param name="isEditable">Make the link editable</param> /// <returns></returns> public virtual RenderingResult BeginRenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false) { return GlassHtml.BeginRenderLink(model, field, this.Output, attributes, isEditable); } /// <summary> /// Render HTML for a link /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model</param> /// <param name="field">The link field to user</param> /// <param name="attributes">Any additional link attributes</param> /// <param name="isEditable">Make the link editable</param> /// <param name="contents">Content to override the default decription or item name</param> /// <returns></returns> public virtual string RenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false, string contents=null) { return GlassHtml.RenderLink(model, field, attributes, isEditable, contents); } /// <summary> /// Returns an Sitecore Edit Frame /// </summary> /// <returns> /// GlassEditFrame. /// </returns> public GlassEditFrame BeginEditFrame<T>(T model, string title = null, params Expression<Func<T, object>>[] fields) where T : class { return GlassHtml.EditFrame(model, title, this.Output, fields); } public override void RenderControl(HtmlTextWriter writer) { this._writer = writer; base.RenderControl(writer); } public virtual string RenderingParameters { get { return RenderingContext.GetRenderingParameters(); } } public virtual TParam GetRenderingParameters<TParam>() where TParam : class { return RenderingParameters.HasValue() ? GlassHtml.GetRenderingParameters<TParam>(RenderingParameters) : default(TParam); } } }
namespace Gu.Wpf.UiAutomation { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Windows; using System.Windows.Automation; public partial class UiElement { public static UiElement FromPoint(Point point) { return FromAutomationElement(AutomationElement.FromPoint(point)); } /// <summary> /// Find the first <see cref="Button"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public Button FindButton(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.Button, name), x => new Button(x), Retry.Time); /// <summary> /// Find the first <see cref="Calendar"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public Calendar FindCalendar(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.Calendar, name), x => new Calendar(x), Retry.Time); /// <summary> /// Find the first <see cref="CalendarDayButton"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public CalendarDayButton FindCalendarDayButton(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.CalendarDayButton, name), x => new CalendarDayButton(x), Retry.Time); /// <summary> /// Find the first <see cref="CheckBox"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public CheckBox FindCheckBox(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.CheckBox, name), x => new CheckBox(x), Retry.Time); /// <summary> /// Find the first <see cref="ComboBox"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public ComboBox FindComboBox(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ComboBox, name), x => new ComboBox(x), Retry.Time); /// <summary> /// Find the first <see cref="DataGrid"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public DataGrid FindDataGrid(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.DataGrid, name), x => new DataGrid(x), Retry.Time); /// <summary> /// Find the first <see cref="DatePicker"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public DatePicker FindDatePicker(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.DatePicker, name), x => new DatePicker(x), Retry.Time); /// <summary> /// Find the first <see cref="Frame"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public Frame FindFrame(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.Frame, name), x => new Frame(x), Retry.Time); /// <summary> /// Find the first <see cref="Label"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public Label FindLabel(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.Label, name), x => new Label(x), Retry.Time); /// <summary> /// Find the first <see cref="GridSplitter"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public GridSplitter FindGridSplitter(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.GridSplitter, name), x => new GridSplitter(x), Retry.Time); /// <summary> /// Find the first <see cref="GroupBox"/> box by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public GroupBox FindGroupBox(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.GroupBox, name), x => new GroupBox(x), Retry.Time); /// <summary> /// Find the first <see cref="Expander"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public Expander FindExpander(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.Expander, name), x => new Expander(x), Retry.Time); /// <summary> /// Find the first <see cref="Menu"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public Menu FindMenu(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.Menu, name), x => new Menu(x), Retry.Time); /// <summary> /// Find the first <see cref="MenuItem"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public MenuItem FindMenuItem(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.MenuItem, name), x => new MenuItem(x), Retry.Time); /// <summary> /// Find the first <see cref="HorizontalScrollBar"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public HorizontalScrollBar FindHorizontalScrollBar(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.HorizontalScrollBar, name), x => new HorizontalScrollBar(x), Retry.Time); /// <summary> /// Find the first <see cref="VerticalScrollBar"/> bar by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public VerticalScrollBar FindVerticalScrollBar(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.VerticalScrollBar, name), x => new VerticalScrollBar(x), Retry.Time); /// <summary> /// Find the first <see cref="ListBox"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public ListBox FindListBox(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ListBox, name), x => new ListBox(x), Retry.Time); /// <summary> /// Find the first <see cref="ListView"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public ListView FindListView(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ListView, name), x => new ListView(x), Retry.Time); /// <summary> /// Find the first <see cref="OpenFileDialog"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public OpenFileDialog FindOpenFileDialog(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.OpenFileDialog, name), x => new OpenFileDialog(x), Retry.Time); /// <summary> /// Find the first <see cref="PasswordBox"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public PasswordBox FindPasswordBox(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.PasswordBox, name), x => new PasswordBox(x), Retry.Time); /// <summary> /// Find the first <see cref="RichTextBox"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public RichTextBox FindRichTextBox(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.RichTextBox, name), x => new RichTextBox(x), Retry.Time); /// <summary> /// Find the first <see cref="ProgressBar"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public ProgressBar FindProgressBar(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ProgressBar, name), x => new ProgressBar(x), Retry.Time); /// <summary> /// Find the first <see cref="RadioButton"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public RadioButton FindRadioButton(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.RadioButton, name), x => new RadioButton(x), Retry.Time); /// <summary> /// Find the first <see cref="RepeatButton"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public RepeatButton FindRepeatButton(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.RepeatButton, name), x => new RepeatButton(x), Retry.Time); /// <summary> /// Find the first <see cref="SaveFileDialog"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public SaveFileDialog FindSaveFileDialog(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.SaveFileDialog, name), x => new SaveFileDialog(x), Retry.Time); /// <summary> /// Find the first <see cref="Separator"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public Separator FindSeparator(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.Separator, name), x => new Separator(x), Retry.Time); /// <summary> /// Find the first <see cref="Slider"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public Slider FindSlider(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.Slider, name), x => new Slider(x), Retry.Time); /// <summary> /// Find the first <see cref="ScrollViewer"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public ScrollViewer FindScrollViewer(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ScrollViewer, name), x => new ScrollViewer(x), Retry.Time); /// <summary> /// Find the first <see cref="TextBlock"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public TextBlock FindTextBlock(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.TextBlock, name), x => new TextBlock(x), Retry.Time); /// <summary> /// Find the first <see cref="TextBox"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public TextBox FindTextBox(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.TextBox, name), x => new TextBox(x), Retry.Time); /// <summary> /// Find the first <see cref="TextBoxBase"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public TextBoxBase FindTextBoxBase(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.TextBoxBase, name), x => new TextBoxBase(x), Retry.Time); /// <summary> /// Find the first <see cref="ToggleButton"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public ToggleButton FindToggleButton(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ToggleButton, name), x => new ToggleButton(x), Retry.Time); /// <summary> /// Find the first <see cref="ToolTip"/>. /// </summary> public ToolTip FindToolTip() => this.Window .FindPopup() .FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ToolTip, this.HelpText), x => new ToolTip(x), Retry.Time); /// <summary> /// Find the first <see cref="TabControl"/> by x:Name, Content or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public TabControl FindTabControl(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.TabControl, name), x => new TabControl(x), Retry.Time); /// <summary> /// Find the first <see cref="TitleBar"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public TitleBar FindTitleBar(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.TitleBar, name), x => new TitleBar(x), Retry.Time); /// <summary> /// Find the first <see cref="ToolBar"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public ToolBar FindToolBar(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ToolBar, name), x => new ToolBar(x), Retry.Time); /// <summary> /// Find the first <see cref="TreeView"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public TreeView FindTreeView(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.TreeView, name), x => new TreeView(x), Retry.Time); /// <summary> /// Find the first <see cref="UserControl"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public UserControl FindUserControl(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.UserControl, name), x => new UserControl(x), Retry.Time); /// <summary> /// Find the first <see cref="StatusBar"/> by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> public StatusBar FindStatusBar(string? name = null) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.StatusBar, name), x => new StatusBar(x), Retry.Time); /// <summary> /// Find the first descendant by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> /// <param name="controlType">The control type.</param> public UiElement FindDescendant(string name, ControlType controlType) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ByControlType(controlType), name), Retry.Time); /// <summary> /// Find the first element by x:Name, Header or AutomationID. /// </summary> /// <param name="name">x:Name, Content or AutomationID.</param> /// <param name="controlType">The control type.</param> /// <param name="wrap">The function to produce a T from the match. Normally x => new Foo(x).</param> public T FindDescendant<T>(string name, ControlType controlType, Func<AutomationElement, T> wrap) where T : UiElement => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ByControlType(controlType), name), wrap, Retry.Time); public UiElement FindDescendant(ControlType controlType) => this.FindFirst( TreeScope.Descendants, Conditions.ByControlType(controlType), Retry.Time); public T FindDescendant<T>(ControlType controlType, Func<AutomationElement, T> wrap) where T : UiElement => this.FindFirst( TreeScope.Descendants, Conditions.ByControlType(controlType), wrap, Retry.Time); public UiElement FindDescendant(ControlType controlType, int index) => this.FindAt( TreeScope.Descendants, Conditions.ByControlType(controlType), index, Retry.Time); public T FindDescendant<T>(ControlType controlType, int index, Func<AutomationElement, T> wrap) where T : UiElement => this.FindAt( TreeScope.Descendants, Conditions.ByControlType(controlType), index, wrap, Retry.Time); public UiElement FindDescendant(ControlType controlType, string name) => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ByControlType(controlType), name), Retry.Time); public T FindDescendant<T>(ControlType controlType, string name, Func<AutomationElement, T> wrap) where T : UiElement => this.FindFirst( TreeScope.Descendants, this.CreateCondition(Conditions.ByControlType(controlType), name), wrap, Retry.Time); public UiElement FindDescendant(string name) => this.FindFirst( TreeScope.Descendants, Conditions.ByNameOrAutomationId(name), Retry.Time); /// <summary> /// Finds all elements in the given tree scope and with the given condition. /// </summary> public IReadOnlyList<UiElement> FindAll(TreeScope treeScope, System.Windows.Automation.Condition condition) { return this.AutomationElement.FindAll(treeScope, condition, FromAutomationElement); } /// <summary> /// Finds all elements in the given tree scope and with the given condition. /// </summary> public IReadOnlyList<T> FindAll<T>(TreeScope treeScope, System.Windows.Automation.Condition condition, Func<AutomationElement, T> wrap) where T : UiElement { return this.AutomationElement.FindAll(treeScope, condition, wrap); } /// <summary> /// Finds all elements in the given tree scope and with the given condition within the given timeout. /// </summary> public IReadOnlyList<UiElement> FindAll(TreeScope treeScope, System.Windows.Automation.Condition condition, TimeSpan timeOut) { if (this.TryFindAll(treeScope, condition, timeOut, out var result)) { return result; } throw new InvalidOperationException($"Did not find an element matching {condition}."); } /// <summary> /// Finds all elements in the given tree scope and with the given condition within the given timeout. /// </summary> public bool TryFindAll(TreeScope treeScope, System.Windows.Automation.Condition condition, TimeSpan timeOut, [NotNullWhen(true)]out IReadOnlyList<UiElement>? result) { if (condition is null) { throw new ArgumentNullException(nameof(condition)); } return this.TryFindAll(treeScope, condition, FromAutomationElement, timeOut, out result); } /// <summary> /// Finds all elements in the given tree scope and with the given condition within the given timeout. /// </summary> public bool TryFindAll<T>(TreeScope treeScope, System.Windows.Automation.Condition condition, Func<AutomationElement, T> wrap, TimeSpan timeOut, [NotNullWhen(true)]out IReadOnlyList<T>? result) where T : UiElement { if (condition is null) { throw new ArgumentNullException(nameof(condition)); } if (wrap is null) { throw new ArgumentNullException(nameof(wrap)); } result = null; var start = DateTime.Now; while (!Retry.IsTimeouted(start, timeOut)) { result = this.AutomationElement.FindAll(treeScope, condition, wrap); if (result is { } && result.Count > 0) { return true; } Wait.For(Retry.PollInterval); } return result is { }; } /// <summary> /// Finds the first element which is in the given tree scope with the given condition. /// </summary> public UiElement FindFirst(TreeScope treeScope, System.Windows.Automation.Condition condition) { if (condition is null) { throw new ArgumentNullException(nameof(condition)); } return this.FindFirst(treeScope, condition, Retry.Time); } /// <summary> /// Finds the first element which is in the given tree scope with the given condition. /// </summary> public T FindFirst<T>(TreeScope treeScope, System.Windows.Automation.Condition condition, Func<AutomationElement, T> wrap) where T : UiElement { if (condition is null) { throw new ArgumentNullException(nameof(condition)); } if (wrap is null) { throw new ArgumentNullException(nameof(wrap)); } return this.FindFirst(treeScope, condition, wrap, Retry.Time); } /// <summary> /// Finds the first element which is in the given tree scope with the given condition within the given timeout period. /// </summary> public UiElement FindFirst(TreeScope treeScope, System.Windows.Automation.Condition condition, TimeSpan timeOut) { if (condition is null) { throw new ArgumentNullException(nameof(condition)); } if (this.TryFindFirst(treeScope, condition, timeOut, out var result)) { return result; } throw new InvalidOperationException($"Did not find an element matching {condition.Description()}."); } /// <summary> /// Finds the first element which is in the given tree scope with the given condition within the given timeout period. /// </summary> public bool TryFindFirst(TreeScope treeScope, System.Windows.Automation.Condition condition, TimeSpan timeOut, [NotNullWhen(true)]out UiElement? result) { if (condition is null) { throw new ArgumentNullException(nameof(condition)); } result = null; var start = DateTime.Now; while (!Retry.IsTimeouted(start, timeOut)) { result = this.AutomationElement.FindFirst(treeScope, condition, FromAutomationElement); if (result is { }) { return true; } Wait.For(Retry.PollInterval); } return result is { }; } /// <summary> /// Finds the first element which is in the given tree scope with the given condition within the given timeout period. /// </summary> public T FindFirst<T>(TreeScope treeScope, System.Windows.Automation.Condition condition, Func<AutomationElement, T> wrap, TimeSpan timeOut) where T : UiElement { if (condition is null) { throw new ArgumentNullException(nameof(condition)); } if (wrap is null) { throw new ArgumentNullException(nameof(wrap)); } if (this.TryFindFirst(treeScope, condition, wrap, timeOut, out var result)) { return result; } throw new InvalidOperationException($"Did not find a {typeof(T).Name} matching {condition.Description()}."); } /// <summary> /// Finds the first element which is in the given tree scope with the given condition within the given timeout period. /// </summary> public bool TryFindFirst<T>(TreeScope treeScope, System.Windows.Automation.Condition condition, Func<AutomationElement, T> wrap, TimeSpan timeOut, [NotNullWhen(true)]out T? result) where T : UiElement { if (condition is null) { throw new ArgumentNullException(nameof(condition)); } if (wrap is null) { throw new ArgumentNullException(nameof(wrap)); } result = null; var start = DateTime.Now; do { if (this.AutomationElement.TryFindFirst(treeScope, condition, out var element)) { result = wrap(element); return true; } Wait.For(Retry.PollInterval); } while (!Retry.IsTimeouted(start, timeOut)); return result is { }; } /// <summary> /// Finds the first element which is in the given tree scope with the given condition within the given timeout period. /// </summary> public UiElement FindAt(TreeScope treeScope, System.Windows.Automation.Condition condition, int index, TimeSpan timeOut) { if (condition is null) { throw new ArgumentNullException(nameof(condition)); } if (this.TryFindAt(treeScope, condition, index, timeOut, out var result)) { return result; } throw new InvalidOperationException($"Did not find an element matching {condition.Description()} at index {index}."); } /// <summary> /// Finds the first element which is in the given tree scope with the given condition within the given timeout period. /// </summary> public bool TryFindAt(TreeScope treeScope, System.Windows.Automation.Condition condition, int index, TimeSpan timeOut, [NotNullWhen(true)]out UiElement? result) { if (condition is null) { throw new ArgumentNullException(nameof(condition)); } result = null; var start = DateTime.Now; while (!Retry.IsTimeouted(start, timeOut)) { result = this.AutomationElement.FindIndexed(treeScope, condition, index, FromAutomationElement); if (result is { }) { return true; } Wait.For(Retry.PollInterval); } return result is { }; } /// <summary> /// Finds the first element which is in the given tree scope with the given condition within the given timeout period. /// </summary> public T FindAt<T>(TreeScope treeScope, System.Windows.Automation.Condition condition, int index, Func<AutomationElement, T> wrap, TimeSpan timeOut) where T : UiElement { if (wrap is null) { throw new ArgumentNullException(nameof(wrap)); } if (condition is null) { throw new ArgumentNullException(nameof(condition)); } if (this.TryFindAt(treeScope, condition, index, wrap, timeOut, out var result)) { return result; } throw new InvalidOperationException($"Did not find an element matching {condition.Description()} at index {index}."); } /// <summary> /// Finds the first element which is in the given tree scope with the given condition within the given timeout period. /// </summary> public bool TryFindAt<T>(TreeScope treeScope, System.Windows.Automation.Condition condition, int index, Func<AutomationElement, T> wrap, TimeSpan timeOut, [NotNullWhen(true)] out T? result) where T : UiElement { if (condition is null) { throw new ArgumentNullException(nameof(condition)); } if (wrap is null) { throw new ArgumentNullException(nameof(wrap)); } result = null; var start = DateTime.Now; while (!Retry.IsTimeouted(start, timeOut)) { if (this.AutomationElement.TryFindIndexed(treeScope, condition, index, out var element)) { result = wrap(element); return true; } Wait.For(Retry.PollInterval); } return result is { }; } public UiElement FindFirstChild() { return this.FindFirst(TreeScope.Children, System.Windows.Automation.Condition.TrueCondition, Retry.Time); } public T FindFirstChild<T>(Func<AutomationElement, T> wrap) where T : UiElement { return this.FindFirst(TreeScope.Children, System.Windows.Automation.Condition.TrueCondition, wrap, Retry.Time); } public UiElement FindChildAt(int index) { return this.FindAt(TreeScope.Children, System.Windows.Automation.Condition.TrueCondition, index, Retry.Time); } public UiElement FindFirstChild(string automationId) { return this.FindFirst(TreeScope.Children, Conditions.ByAutomationId(automationId)); } public UiElement FindFirstChild(System.Windows.Automation.Condition condition) { return this.FindFirst(TreeScope.Children, condition); } public T FindFirstChild<T>(System.Windows.Automation.Condition condition, Func<AutomationElement, T> wrap) where T : UiElement { return this.FindFirst(TreeScope.Children, condition, wrap); } public IReadOnlyList<UiElement> FindAllChildren() { return this.FindAll(TreeScope.Children, System.Windows.Automation.Condition.TrueCondition); } public IReadOnlyList<T> FindAllChildren<T>(Func<AutomationElement, T> wrap) where T : UiElement { return this.AutomationElement.FindAll(TreeScope.Children, System.Windows.Automation.Condition.TrueCondition, wrap); } public IReadOnlyList<T> FindAllChildren<T>(System.Windows.Automation.Condition condition, Func<AutomationElement, T> wrap) where T : UiElement { return this.AutomationElement.FindAll(TreeScope.Children, condition, wrap); } public IReadOnlyList<UiElement> FindAllChildren(System.Windows.Automation.Condition condition) { return this.AutomationElement.FindAll(TreeScope.Children, condition, FromAutomationElement); } public UiElement FindFirstDescendant() { return this.FindFirst(TreeScope.Descendants, System.Windows.Automation.Condition.TrueCondition); } public T FindFirstDescendant<T>(Func<AutomationElement, T> wrap) where T : UiElement { return this.FindFirst(TreeScope.Descendants, System.Windows.Automation.Condition.TrueCondition, wrap); } public UiElement FindFirstDescendant(string automationId) { return this.FindFirst(TreeScope.Descendants, Conditions.ByAutomationId(automationId)); } public T FindFirstDescendant<T>(string automationId, Func<AutomationElement, T> wrap) where T : UiElement { return this.FindFirst(TreeScope.Descendants, Conditions.ByAutomationId(automationId), wrap); } public UiElement FindFirstDescendant(ControlType controlType) { return this.FindFirst(TreeScope.Descendants, Conditions.ByControlType(controlType)); } public T FindFirstDescendant<T>(ControlType controlType, Func<AutomationElement, T> wrap) where T : UiElement { return this.FindFirst(TreeScope.Descendants, Conditions.ByControlType(controlType), wrap); } public UiElement FindFirstDescendant(System.Windows.Automation.Condition condition) { return this.FindFirst(TreeScope.Descendants, condition); } public IReadOnlyList<UiElement> FindAllDescendants() { return this.FindAll(TreeScope.Descendants, System.Windows.Automation.Condition.TrueCondition); } public IReadOnlyList<UiElement> FindAllDescendants(System.Windows.Automation.Condition condition) { return this.FindAll(TreeScope.Descendants, condition); } /// <summary> /// Finds the first element by looping thru all conditions. /// </summary> public UiElement? FindFirstNested(params System.Windows.Automation.Condition[] nestedConditions) { var currentElement = this; foreach (var condition in nestedConditions) { currentElement = currentElement.FindFirstChild(condition); if (currentElement is null) { return null; } } return currentElement; } /// <summary> /// Finds all elements by looping thru all conditions. /// </summary> public IReadOnlyList<UiElement>? FindAllNested(params System.Windows.Automation.Condition[] nestedConditions) { var currentElement = this; for (var i = 0; i < nestedConditions.Length - 1; i++) { var condition = nestedConditions[i]; currentElement = currentElement.FindFirstChild(condition); if (currentElement is null) { return null; } } return currentElement.FindAllChildren(nestedConditions.Last()); } /// <summary> /// Finds for the first item which matches the given xpath. /// </summary> public UiElement? FindFirstByXPath(string xPath) { var xPathNavigator = new AutomationElementXPathNavigator(this); var nodeItem = xPathNavigator.SelectSingleNode(xPath); return (UiElement?)nodeItem?.UnderlyingObject; } /// <summary> /// Finds all items which match the given xpath. /// </summary> public IReadOnlyList<UiElement> FindAllByXPath(string xPath) { var xPathNavigator = new AutomationElementXPathNavigator(this); var itemNodeIterator = xPathNavigator.Select(xPath); var itemList = new List<UiElement>(); while (itemNodeIterator.MoveNext()) { var automationItem = (UiElement)itemNodeIterator.Current.UnderlyingObject; itemList.Add(automationItem); } return itemList.ToArray(); } #pragma warning disable CA1822 public System.Windows.Automation.Condition CreateCondition(System.Windows.Automation.Condition controlTypeCondition, string? name) #pragma warning restore CA1822 { if (name is null) { return controlTypeCondition; } return new AndCondition( controlTypeCondition, Conditions.ByNameOrAutomationId(name)); } } }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; using System.Threading; using OpenHome.Net.Core; using OpenHome.Net.ControlPoint; namespace OpenHome.Net.ControlPoint.Proxies { public interface ICpProxyUpnpOrgConnectionManager2 : ICpProxy, IDisposable { void SyncGetProtocolInfo(out String aSource, out String aSink); void BeginGetProtocolInfo(CpProxy.CallbackAsyncComplete aCallback); void EndGetProtocolInfo(IntPtr aAsyncHandle, out String aSource, out String aSink); void SyncPrepareForConnection(String aRemoteProtocolInfo, String aPeerConnectionManager, int aPeerConnectionID, String aDirection, out int aConnectionID, out int aAVTransportID, out int aRcsID); void BeginPrepareForConnection(String aRemoteProtocolInfo, String aPeerConnectionManager, int aPeerConnectionID, String aDirection, CpProxy.CallbackAsyncComplete aCallback); void EndPrepareForConnection(IntPtr aAsyncHandle, out int aConnectionID, out int aAVTransportID, out int aRcsID); void SyncConnectionComplete(int aConnectionID); void BeginConnectionComplete(int aConnectionID, CpProxy.CallbackAsyncComplete aCallback); void EndConnectionComplete(IntPtr aAsyncHandle); void SyncGetCurrentConnectionIDs(out String aConnectionIDs); void BeginGetCurrentConnectionIDs(CpProxy.CallbackAsyncComplete aCallback); void EndGetCurrentConnectionIDs(IntPtr aAsyncHandle, out String aConnectionIDs); void SyncGetCurrentConnectionInfo(int aConnectionID, out int aRcsID, out int aAVTransportID, out String aProtocolInfo, out String aPeerConnectionManager, out int aPeerConnectionID, out String aDirection, out String aStatus); void BeginGetCurrentConnectionInfo(int aConnectionID, CpProxy.CallbackAsyncComplete aCallback); void EndGetCurrentConnectionInfo(IntPtr aAsyncHandle, out int aRcsID, out int aAVTransportID, out String aProtocolInfo, out String aPeerConnectionManager, out int aPeerConnectionID, out String aDirection, out String aStatus); void SetPropertySourceProtocolInfoChanged(System.Action aSourceProtocolInfoChanged); String PropertySourceProtocolInfo(); void SetPropertySinkProtocolInfoChanged(System.Action aSinkProtocolInfoChanged); String PropertySinkProtocolInfo(); void SetPropertyCurrentConnectionIDsChanged(System.Action aCurrentConnectionIDsChanged); String PropertyCurrentConnectionIDs(); } internal class SyncGetProtocolInfoUpnpOrgConnectionManager2 : SyncProxyAction { private CpProxyUpnpOrgConnectionManager2 iService; private String iSource; private String iSink; public SyncGetProtocolInfoUpnpOrgConnectionManager2(CpProxyUpnpOrgConnectionManager2 aProxy) { iService = aProxy; } public String Source() { return iSource; } public String Sink() { return iSink; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndGetProtocolInfo(aAsyncHandle, out iSource, out iSink); } }; internal class SyncPrepareForConnectionUpnpOrgConnectionManager2 : SyncProxyAction { private CpProxyUpnpOrgConnectionManager2 iService; private int iConnectionID; private int iAVTransportID; private int iRcsID; public SyncPrepareForConnectionUpnpOrgConnectionManager2(CpProxyUpnpOrgConnectionManager2 aProxy) { iService = aProxy; } public int ConnectionID() { return iConnectionID; } public int AVTransportID() { return iAVTransportID; } public int RcsID() { return iRcsID; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndPrepareForConnection(aAsyncHandle, out iConnectionID, out iAVTransportID, out iRcsID); } }; internal class SyncConnectionCompleteUpnpOrgConnectionManager2 : SyncProxyAction { private CpProxyUpnpOrgConnectionManager2 iService; public SyncConnectionCompleteUpnpOrgConnectionManager2(CpProxyUpnpOrgConnectionManager2 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndConnectionComplete(aAsyncHandle); } }; internal class SyncGetCurrentConnectionIDsUpnpOrgConnectionManager2 : SyncProxyAction { private CpProxyUpnpOrgConnectionManager2 iService; private String iConnectionIDs; public SyncGetCurrentConnectionIDsUpnpOrgConnectionManager2(CpProxyUpnpOrgConnectionManager2 aProxy) { iService = aProxy; } public String ConnectionIDs() { return iConnectionIDs; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndGetCurrentConnectionIDs(aAsyncHandle, out iConnectionIDs); } }; internal class SyncGetCurrentConnectionInfoUpnpOrgConnectionManager2 : SyncProxyAction { private CpProxyUpnpOrgConnectionManager2 iService; private int iRcsID; private int iAVTransportID; private String iProtocolInfo; private String iPeerConnectionManager; private int iPeerConnectionID; private String iDirection; private String iStatus; public SyncGetCurrentConnectionInfoUpnpOrgConnectionManager2(CpProxyUpnpOrgConnectionManager2 aProxy) { iService = aProxy; } public int RcsID() { return iRcsID; } public int AVTransportID() { return iAVTransportID; } public String ProtocolInfo() { return iProtocolInfo; } public String PeerConnectionManager() { return iPeerConnectionManager; } public int PeerConnectionID() { return iPeerConnectionID; } public String Direction() { return iDirection; } public String Status() { return iStatus; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndGetCurrentConnectionInfo(aAsyncHandle, out iRcsID, out iAVTransportID, out iProtocolInfo, out iPeerConnectionManager, out iPeerConnectionID, out iDirection, out iStatus); } }; /// <summary> /// Proxy for the upnp.org:ConnectionManager:2 UPnP service /// </summary> public class CpProxyUpnpOrgConnectionManager2 : CpProxy, IDisposable, ICpProxyUpnpOrgConnectionManager2 { private OpenHome.Net.Core.Action iActionGetProtocolInfo; private OpenHome.Net.Core.Action iActionPrepareForConnection; private OpenHome.Net.Core.Action iActionConnectionComplete; private OpenHome.Net.Core.Action iActionGetCurrentConnectionIDs; private OpenHome.Net.Core.Action iActionGetCurrentConnectionInfo; private PropertyString iSourceProtocolInfo; private PropertyString iSinkProtocolInfo; private PropertyString iCurrentConnectionIDs; private System.Action iSourceProtocolInfoChanged; private System.Action iSinkProtocolInfoChanged; private System.Action iCurrentConnectionIDsChanged; private Mutex iPropertyLock; /// <summary> /// Constructor /// </summary> /// <remarks>Use CpProxy::[Un]Subscribe() to enable/disable querying of state variable and reporting of their changes.</remarks> /// <param name="aDevice">The device to use</param> public CpProxyUpnpOrgConnectionManager2(CpDevice aDevice) : base("schemas-upnp-org", "ConnectionManager", 2, aDevice) { OpenHome.Net.Core.Parameter param; List<String> allowedValues = new List<String>(); iActionGetProtocolInfo = new OpenHome.Net.Core.Action("GetProtocolInfo"); param = new ParameterString("Source", allowedValues); iActionGetProtocolInfo.AddOutputParameter(param); param = new ParameterString("Sink", allowedValues); iActionGetProtocolInfo.AddOutputParameter(param); iActionPrepareForConnection = new OpenHome.Net.Core.Action("PrepareForConnection"); param = new ParameterString("RemoteProtocolInfo", allowedValues); iActionPrepareForConnection.AddInputParameter(param); param = new ParameterString("PeerConnectionManager", allowedValues); iActionPrepareForConnection.AddInputParameter(param); param = new ParameterInt("PeerConnectionID"); iActionPrepareForConnection.AddInputParameter(param); allowedValues.Add("Input"); allowedValues.Add("Output"); param = new ParameterString("Direction", allowedValues); iActionPrepareForConnection.AddInputParameter(param); allowedValues.Clear(); param = new ParameterInt("ConnectionID"); iActionPrepareForConnection.AddOutputParameter(param); param = new ParameterInt("AVTransportID"); iActionPrepareForConnection.AddOutputParameter(param); param = new ParameterInt("RcsID"); iActionPrepareForConnection.AddOutputParameter(param); iActionConnectionComplete = new OpenHome.Net.Core.Action("ConnectionComplete"); param = new ParameterInt("ConnectionID"); iActionConnectionComplete.AddInputParameter(param); iActionGetCurrentConnectionIDs = new OpenHome.Net.Core.Action("GetCurrentConnectionIDs"); param = new ParameterString("ConnectionIDs", allowedValues); iActionGetCurrentConnectionIDs.AddOutputParameter(param); iActionGetCurrentConnectionInfo = new OpenHome.Net.Core.Action("GetCurrentConnectionInfo"); param = new ParameterInt("ConnectionID"); iActionGetCurrentConnectionInfo.AddInputParameter(param); param = new ParameterInt("RcsID"); iActionGetCurrentConnectionInfo.AddOutputParameter(param); param = new ParameterInt("AVTransportID"); iActionGetCurrentConnectionInfo.AddOutputParameter(param); param = new ParameterString("ProtocolInfo", allowedValues); iActionGetCurrentConnectionInfo.AddOutputParameter(param); param = new ParameterString("PeerConnectionManager", allowedValues); iActionGetCurrentConnectionInfo.AddOutputParameter(param); param = new ParameterInt("PeerConnectionID"); iActionGetCurrentConnectionInfo.AddOutputParameter(param); allowedValues.Add("Input"); allowedValues.Add("Output"); param = new ParameterString("Direction", allowedValues); iActionGetCurrentConnectionInfo.AddOutputParameter(param); allowedValues.Clear(); allowedValues.Add("OK"); allowedValues.Add("ContentFormatMismatch"); allowedValues.Add("InsufficientBandwidth"); allowedValues.Add("UnreliableChannel"); allowedValues.Add("Unknown"); param = new ParameterString("Status", allowedValues); iActionGetCurrentConnectionInfo.AddOutputParameter(param); allowedValues.Clear(); iSourceProtocolInfo = new PropertyString("SourceProtocolInfo", SourceProtocolInfoPropertyChanged); AddProperty(iSourceProtocolInfo); iSinkProtocolInfo = new PropertyString("SinkProtocolInfo", SinkProtocolInfoPropertyChanged); AddProperty(iSinkProtocolInfo); iCurrentConnectionIDs = new PropertyString("CurrentConnectionIDs", CurrentConnectionIDsPropertyChanged); AddProperty(iCurrentConnectionIDs); iPropertyLock = new Mutex(); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aSource"></param> /// <param name="aSink"></param> public void SyncGetProtocolInfo(out String aSource, out String aSink) { SyncGetProtocolInfoUpnpOrgConnectionManager2 sync = new SyncGetProtocolInfoUpnpOrgConnectionManager2(this); BeginGetProtocolInfo(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aSource = sync.Source(); aSink = sync.Sink(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndGetProtocolInfo().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginGetProtocolInfo(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionGetProtocolInfo, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionGetProtocolInfo.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentString((ParameterString)iActionGetProtocolInfo.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aSource"></param> /// <param name="aSink"></param> public void EndGetProtocolInfo(IntPtr aAsyncHandle, out String aSource, out String aSink) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aSource = Invocation.OutputString(aAsyncHandle, index++); aSink = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aRemoteProtocolInfo"></param> /// <param name="aPeerConnectionManager"></param> /// <param name="aPeerConnectionID"></param> /// <param name="aDirection"></param> /// <param name="aConnectionID"></param> /// <param name="aAVTransportID"></param> /// <param name="aRcsID"></param> public void SyncPrepareForConnection(String aRemoteProtocolInfo, String aPeerConnectionManager, int aPeerConnectionID, String aDirection, out int aConnectionID, out int aAVTransportID, out int aRcsID) { SyncPrepareForConnectionUpnpOrgConnectionManager2 sync = new SyncPrepareForConnectionUpnpOrgConnectionManager2(this); BeginPrepareForConnection(aRemoteProtocolInfo, aPeerConnectionManager, aPeerConnectionID, aDirection, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aConnectionID = sync.ConnectionID(); aAVTransportID = sync.AVTransportID(); aRcsID = sync.RcsID(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndPrepareForConnection().</remarks> /// <param name="aRemoteProtocolInfo"></param> /// <param name="aPeerConnectionManager"></param> /// <param name="aPeerConnectionID"></param> /// <param name="aDirection"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginPrepareForConnection(String aRemoteProtocolInfo, String aPeerConnectionManager, int aPeerConnectionID, String aDirection, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionPrepareForConnection, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionPrepareForConnection.InputParameter(inIndex++), aRemoteProtocolInfo)); invocation.AddInput(new ArgumentString((ParameterString)iActionPrepareForConnection.InputParameter(inIndex++), aPeerConnectionManager)); invocation.AddInput(new ArgumentInt((ParameterInt)iActionPrepareForConnection.InputParameter(inIndex++), aPeerConnectionID)); invocation.AddInput(new ArgumentString((ParameterString)iActionPrepareForConnection.InputParameter(inIndex++), aDirection)); int outIndex = 0; invocation.AddOutput(new ArgumentInt((ParameterInt)iActionPrepareForConnection.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentInt((ParameterInt)iActionPrepareForConnection.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentInt((ParameterInt)iActionPrepareForConnection.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aConnectionID"></param> /// <param name="aAVTransportID"></param> /// <param name="aRcsID"></param> public void EndPrepareForConnection(IntPtr aAsyncHandle, out int aConnectionID, out int aAVTransportID, out int aRcsID) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aConnectionID = Invocation.OutputInt(aAsyncHandle, index++); aAVTransportID = Invocation.OutputInt(aAsyncHandle, index++); aRcsID = Invocation.OutputInt(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aConnectionID"></param> public void SyncConnectionComplete(int aConnectionID) { SyncConnectionCompleteUpnpOrgConnectionManager2 sync = new SyncConnectionCompleteUpnpOrgConnectionManager2(this); BeginConnectionComplete(aConnectionID, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndConnectionComplete().</remarks> /// <param name="aConnectionID"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginConnectionComplete(int aConnectionID, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionConnectionComplete, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentInt((ParameterInt)iActionConnectionComplete.InputParameter(inIndex++), aConnectionID)); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndConnectionComplete(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aConnectionIDs"></param> public void SyncGetCurrentConnectionIDs(out String aConnectionIDs) { SyncGetCurrentConnectionIDsUpnpOrgConnectionManager2 sync = new SyncGetCurrentConnectionIDsUpnpOrgConnectionManager2(this); BeginGetCurrentConnectionIDs(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aConnectionIDs = sync.ConnectionIDs(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndGetCurrentConnectionIDs().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginGetCurrentConnectionIDs(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionGetCurrentConnectionIDs, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionGetCurrentConnectionIDs.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aConnectionIDs"></param> public void EndGetCurrentConnectionIDs(IntPtr aAsyncHandle, out String aConnectionIDs) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aConnectionIDs = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aConnectionID"></param> /// <param name="aRcsID"></param> /// <param name="aAVTransportID"></param> /// <param name="aProtocolInfo"></param> /// <param name="aPeerConnectionManager"></param> /// <param name="aPeerConnectionID"></param> /// <param name="aDirection"></param> /// <param name="aStatus"></param> public void SyncGetCurrentConnectionInfo(int aConnectionID, out int aRcsID, out int aAVTransportID, out String aProtocolInfo, out String aPeerConnectionManager, out int aPeerConnectionID, out String aDirection, out String aStatus) { SyncGetCurrentConnectionInfoUpnpOrgConnectionManager2 sync = new SyncGetCurrentConnectionInfoUpnpOrgConnectionManager2(this); BeginGetCurrentConnectionInfo(aConnectionID, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aRcsID = sync.RcsID(); aAVTransportID = sync.AVTransportID(); aProtocolInfo = sync.ProtocolInfo(); aPeerConnectionManager = sync.PeerConnectionManager(); aPeerConnectionID = sync.PeerConnectionID(); aDirection = sync.Direction(); aStatus = sync.Status(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndGetCurrentConnectionInfo().</remarks> /// <param name="aConnectionID"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginGetCurrentConnectionInfo(int aConnectionID, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionGetCurrentConnectionInfo, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentInt((ParameterInt)iActionGetCurrentConnectionInfo.InputParameter(inIndex++), aConnectionID)); int outIndex = 0; invocation.AddOutput(new ArgumentInt((ParameterInt)iActionGetCurrentConnectionInfo.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentInt((ParameterInt)iActionGetCurrentConnectionInfo.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentString((ParameterString)iActionGetCurrentConnectionInfo.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentString((ParameterString)iActionGetCurrentConnectionInfo.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentInt((ParameterInt)iActionGetCurrentConnectionInfo.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentString((ParameterString)iActionGetCurrentConnectionInfo.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentString((ParameterString)iActionGetCurrentConnectionInfo.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aRcsID"></param> /// <param name="aAVTransportID"></param> /// <param name="aProtocolInfo"></param> /// <param name="aPeerConnectionManager"></param> /// <param name="aPeerConnectionID"></param> /// <param name="aDirection"></param> /// <param name="aStatus"></param> public void EndGetCurrentConnectionInfo(IntPtr aAsyncHandle, out int aRcsID, out int aAVTransportID, out String aProtocolInfo, out String aPeerConnectionManager, out int aPeerConnectionID, out String aDirection, out String aStatus) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aRcsID = Invocation.OutputInt(aAsyncHandle, index++); aAVTransportID = Invocation.OutputInt(aAsyncHandle, index++); aProtocolInfo = Invocation.OutputString(aAsyncHandle, index++); aPeerConnectionManager = Invocation.OutputString(aAsyncHandle, index++); aPeerConnectionID = Invocation.OutputInt(aAsyncHandle, index++); aDirection = Invocation.OutputString(aAsyncHandle, index++); aStatus = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Set a delegate to be run when the SourceProtocolInfo state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyUpnpOrgConnectionManager2 instance will not overlap.</remarks> /// <param name="aSourceProtocolInfoChanged">The delegate to run when the state variable changes</param> public void SetPropertySourceProtocolInfoChanged(System.Action aSourceProtocolInfoChanged) { lock (iPropertyLock) { iSourceProtocolInfoChanged = aSourceProtocolInfoChanged; } } private void SourceProtocolInfoPropertyChanged() { lock (iPropertyLock) { ReportEvent(iSourceProtocolInfoChanged); } } /// <summary> /// Set a delegate to be run when the SinkProtocolInfo state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyUpnpOrgConnectionManager2 instance will not overlap.</remarks> /// <param name="aSinkProtocolInfoChanged">The delegate to run when the state variable changes</param> public void SetPropertySinkProtocolInfoChanged(System.Action aSinkProtocolInfoChanged) { lock (iPropertyLock) { iSinkProtocolInfoChanged = aSinkProtocolInfoChanged; } } private void SinkProtocolInfoPropertyChanged() { lock (iPropertyLock) { ReportEvent(iSinkProtocolInfoChanged); } } /// <summary> /// Set a delegate to be run when the CurrentConnectionIDs state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyUpnpOrgConnectionManager2 instance will not overlap.</remarks> /// <param name="aCurrentConnectionIDsChanged">The delegate to run when the state variable changes</param> public void SetPropertyCurrentConnectionIDsChanged(System.Action aCurrentConnectionIDsChanged) { lock (iPropertyLock) { iCurrentConnectionIDsChanged = aCurrentConnectionIDsChanged; } } private void CurrentConnectionIDsPropertyChanged() { lock (iPropertyLock) { ReportEvent(iCurrentConnectionIDsChanged); } } /// <summary> /// Query the value of the SourceProtocolInfo property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the SourceProtocolInfo property</returns> public String PropertySourceProtocolInfo() { PropertyReadLock(); String val; try { val = iSourceProtocolInfo.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Query the value of the SinkProtocolInfo property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the SinkProtocolInfo property</returns> public String PropertySinkProtocolInfo() { PropertyReadLock(); String val; try { val = iSinkProtocolInfo.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Query the value of the CurrentConnectionIDs property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the CurrentConnectionIDs property</returns> public String PropertyCurrentConnectionIDs() { PropertyReadLock(); String val; try { val = iCurrentConnectionIDs.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Must be called for each class instance. Must be called before Core.Library.Close(). /// </summary> public void Dispose() { lock (this) { if (iHandle == IntPtr.Zero) return; DisposeProxy(); iHandle = IntPtr.Zero; } iActionGetProtocolInfo.Dispose(); iActionPrepareForConnection.Dispose(); iActionConnectionComplete.Dispose(); iActionGetCurrentConnectionIDs.Dispose(); iActionGetCurrentConnectionInfo.Dispose(); iSourceProtocolInfo.Dispose(); iSinkProtocolInfo.Dispose(); iCurrentConnectionIDs.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Configuration.Internal; using System.Diagnostics; namespace System.Configuration { [DebuggerDisplay("FactoryRecord {ConfigKey}")] internal class FactoryRecord : IConfigErrorInfo { private const int FlagAllowLocation = 0x0001; // Does the factory allow location directives? private const int FlagRestartOnExternalChanges = 0x0002; // Restart on external changes? // Does access to the section require unrestricted ConfigurationPermission? private const int FlagRequirePermission = 0x0004; private const int FlagIsGroup = 0x0008; // factory represents a group private const int FlagIsFromTrustedConfigRecord = 0x0010; // Factory is defined in trusted config record private const int FlagIsUndeclared = 0x0040; // Factory is not declared - either implicit or unrecognized private List<ConfigurationException> _errors; // errors private SimpleBitVector32 _flags; // factory flags // constructor used for Clone() private FactoryRecord( string configKey, string group, string name, object factory, string factoryTypeName, SimpleBitVector32 flags, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition, OverrideModeSetting overrideModeDefault, string filename, int lineNumber, ICollection<ConfigurationException> errors) { ConfigKey = configKey; Group = group; Name = name; Factory = factory; FactoryTypeName = factoryTypeName; _flags = flags; AllowDefinition = allowDefinition; AllowExeDefinition = allowExeDefinition; OverrideModeDefault = overrideModeDefault; Filename = filename; LineNumber = lineNumber; AddErrors(errors); } // constructor used for group internal FactoryRecord(string configKey, string group, string name, string factoryTypeName, string filename, int lineNumber) { ConfigKey = configKey; Group = group; Name = name; FactoryTypeName = factoryTypeName; IsGroup = true; Filename = filename; LineNumber = lineNumber; } // constructor used for a section internal FactoryRecord( string configKey, string group, string name, string factoryTypeName, bool allowLocation, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition, OverrideModeSetting overrideModeDefault, bool restartOnExternalChanges, bool requirePermission, bool isFromTrustedConfigRecord, bool isUndeclared, string filename, int lineNumber) { ConfigKey = configKey; Group = group; Name = name; FactoryTypeName = factoryTypeName; AllowDefinition = allowDefinition; AllowExeDefinition = allowExeDefinition; OverrideModeDefault = overrideModeDefault; AllowLocation = allowLocation; RestartOnExternalChanges = restartOnExternalChanges; RequirePermission = requirePermission; IsFromTrustedConfigRecord = isFromTrustedConfigRecord; IsUndeclared = isUndeclared; Filename = filename; LineNumber = lineNumber; } internal string ConfigKey { get; } internal string Group { get; } internal string Name { get; } internal object Factory { get; set; } internal string FactoryTypeName { get; set; } internal ConfigurationAllowDefinition AllowDefinition { get; set; } internal ConfigurationAllowExeDefinition AllowExeDefinition { get; set; } internal OverrideModeSetting OverrideModeDefault { get; } internal bool AllowLocation { get { return _flags[FlagAllowLocation]; } set { _flags[FlagAllowLocation] = value; } } internal bool RestartOnExternalChanges { get { return _flags[FlagRestartOnExternalChanges]; } set { _flags[FlagRestartOnExternalChanges] = value; } } internal bool RequirePermission { get { return _flags[FlagRequirePermission]; } set { _flags[FlagRequirePermission] = value; } } internal bool IsGroup { get { return _flags[FlagIsGroup]; } set { _flags[FlagIsGroup] = value; } } internal bool IsFromTrustedConfigRecord { get { return _flags[FlagIsFromTrustedConfigRecord]; } set { _flags[FlagIsFromTrustedConfigRecord] = value; } } internal bool IsUndeclared { get { return _flags[FlagIsUndeclared]; } set { _flags[FlagIsUndeclared] = value; } } internal bool HasFile => LineNumber >= 0; internal List<ConfigurationException> Errors => _errors; internal bool HasErrors => ErrorsHelper.GetHasErrors(_errors); // This is used in HttpConfigurationRecord.EnsureSectionFactory() to give file and line source // when a section handler type is invalid or cannot be loaded. public string Filename { get; set; } public int LineNumber { get; set; } // by cloning we contain a single copy of the strings referred to in the factory and section records internal FactoryRecord CloneSection(string filename, int lineNumber) { return new FactoryRecord(ConfigKey, Group, Name, Factory, FactoryTypeName, _flags, AllowDefinition, AllowExeDefinition, OverrideModeDefault, filename, lineNumber, Errors); } // by cloning we contain a single copy of the strings referred to in the factory and section records internal FactoryRecord CloneSectionGroup(string factoryTypeName, string filename, int lineNumber) { if (FactoryTypeName != null) factoryTypeName = FactoryTypeName; return new FactoryRecord(ConfigKey, Group, Name, Factory, factoryTypeName, _flags, AllowDefinition, AllowExeDefinition, OverrideModeDefault, filename, lineNumber, Errors); } internal bool IsEquivalentType(IInternalConfigHost host, string typeName) { try { if (FactoryTypeName == typeName) return true; Type t1, t2; if (host != null) { t1 = TypeUtil.GetType(host, typeName, false); t2 = TypeUtil.GetType(host, FactoryTypeName, false); } else { t1 = TypeUtil.GetType(typeName, false); t2 = TypeUtil.GetType(FactoryTypeName, false); } return (t1 != null) && (t1 == t2); } catch { } return false; } internal bool IsEquivalentSectionGroupFactory(IInternalConfigHost host, string typeName) { if ((typeName == null) || (FactoryTypeName == null)) return true; return IsEquivalentType(host, typeName); } internal bool IsEquivalentSectionFactory( IInternalConfigHost host, string typeName, bool allowLocation, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition, bool restartOnExternalChanges, bool requirePermission) { if ((allowLocation != AllowLocation) || (allowDefinition != AllowDefinition) || (allowExeDefinition != AllowExeDefinition) || (restartOnExternalChanges != RestartOnExternalChanges) || (requirePermission != RequirePermission)) return false; return IsEquivalentType(host, typeName); } internal void AddErrors(ICollection<ConfigurationException> coll) { ErrorsHelper.AddErrors(ref _errors, coll); } internal void ThrowOnErrors() { ErrorsHelper.ThrowOnErrors(_errors); } internal bool IsIgnorable() { if (Factory != null) return Factory is IgnoreSectionHandler; return (FactoryTypeName != null) && FactoryTypeName.Contains("System.Configuration.IgnoreSection"); } } }
using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json; namespace Citrina { public class Board : IBoard { /// <summary> /// Creates a new topic on a community's discussion board. /// </summary> public Task<ApiRequest<int?>> AddTopicApi(int? groupId = null, string title = null, string text = null, bool? fromGroup = null, IEnumerable<string> attachments = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["title"] = title, ["text"] = text, ["from_group"] = RequestHelpers.ParseBoolean(fromGroup), ["attachments"] = RequestHelpers.ParseEnumerable(attachments), }; return RequestManager.CreateRequestAsync<int?>("board.addTopic", null, request); } /// <summary> /// Closes a topic on a community's discussion board so that comments cannot be posted. /// </summary> public Task<ApiRequest<bool?>> CloseTopicApi(int? groupId = null, int? topicId = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("board.closeTopic", null, request); } /// <summary> /// Adds a comment on a topic on a community's discussion board. /// </summary> public Task<ApiRequest<int?>> CreateCommentApi(int? groupId = null, int? topicId = null, string message = null, IEnumerable<string> attachments = null, bool? fromGroup = null, int? stickerId = null, string guid = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), ["message"] = message, ["attachments"] = RequestHelpers.ParseEnumerable(attachments), ["from_group"] = RequestHelpers.ParseBoolean(fromGroup), ["sticker_id"] = stickerId?.ToString(), ["guid"] = guid, }; return RequestManager.CreateRequestAsync<int?>("board.createComment", null, request); } /// <summary> /// Deletes a comment on a topic on a community's discussion board. /// </summary> public Task<ApiRequest<bool?>> DeleteCommentApi(int? groupId = null, int? topicId = null, int? commentId = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), ["comment_id"] = commentId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("board.deleteComment", null, request); } /// <summary> /// Deletes a topic from a community's discussion board. /// </summary> public Task<ApiRequest<bool?>> DeleteTopicApi(int? groupId = null, int? topicId = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("board.deleteTopic", null, request); } /// <summary> /// Edits a comment on a topic on a community's discussion board. /// </summary> public Task<ApiRequest<bool?>> EditCommentApi(int? groupId = null, int? topicId = null, int? commentId = null, string message = null, IEnumerable<string> attachments = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), ["comment_id"] = commentId?.ToString(), ["message"] = message, ["attachments"] = RequestHelpers.ParseEnumerable(attachments), }; return RequestManager.CreateRequestAsync<bool?>("board.editComment", null, request); } /// <summary> /// Edits the title of a topic on a community's discussion board. /// </summary> public Task<ApiRequest<bool?>> EditTopicApi(int? groupId = null, int? topicId = null, string title = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), ["title"] = title, }; return RequestManager.CreateRequestAsync<bool?>("board.editTopic", null, request); } /// <summary> /// Pins a topic (fixes its place) to the top of a community's discussion board. /// </summary> public Task<ApiRequest<bool?>> FixTopicApi(int? groupId = null, int? topicId = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("board.fixTopic", null, request); } /// <summary> /// Returns a list of comments on a topic on a community's discussion board. /// </summary> public Task<ApiRequest<BoardGetCommentsResponse>> GetCommentsApi(int? groupId = null, int? topicId = null, bool? needLikes = null, int? startCommentId = null, int? offset = null, int? count = null, bool? extended = null, string sort = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), ["need_likes"] = RequestHelpers.ParseBoolean(needLikes), ["start_comment_id"] = startCommentId?.ToString(), ["offset"] = offset?.ToString(), ["count"] = count?.ToString(), ["extended"] = RequestHelpers.ParseBoolean(extended), ["sort"] = sort, }; return RequestManager.CreateRequestAsync<BoardGetCommentsResponse>("board.getComments", null, request); } /// <summary> /// Returns a list of comments on a topic on a community's discussion board. /// </summary> public Task<ApiRequest<BoardGetCommentsExtendedResponse>> GetCommentsApi(int? groupId = null, int? topicId = null, bool? needLikes = null, int? startCommentId = null, int? offset = null, int? count = null, bool? extended = null, string sort = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), ["need_likes"] = RequestHelpers.ParseBoolean(needLikes), ["start_comment_id"] = startCommentId?.ToString(), ["offset"] = offset?.ToString(), ["count"] = count?.ToString(), ["extended"] = RequestHelpers.ParseBoolean(extended), ["sort"] = sort, }; return RequestManager.CreateRequestAsync<BoardGetCommentsExtendedResponse>("board.getComments", null, request); } /// <summary> /// Returns a list of topics on a community's discussion board. /// </summary> public Task<ApiRequest<BoardGetTopicsResponse>> GetTopicsApi(int? groupId = null, IEnumerable<int> topicIds = null, int? order = null, int? offset = null, int? count = null, bool? extended = null, int? preview = null, int? previewLength = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_ids"] = RequestHelpers.ParseEnumerable(topicIds), ["order"] = order?.ToString(), ["offset"] = offset?.ToString(), ["count"] = count?.ToString(), ["extended"] = RequestHelpers.ParseBoolean(extended), ["preview"] = preview?.ToString(), ["preview_length"] = previewLength?.ToString(), }; return RequestManager.CreateRequestAsync<BoardGetTopicsResponse>("board.getTopics", null, request); } /// <summary> /// Returns a list of topics on a community's discussion board. /// </summary> public Task<ApiRequest<BoardGetTopicsExtendedResponse>> GetTopicsApi(int? groupId = null, IEnumerable<int> topicIds = null, int? order = null, int? offset = null, int? count = null, bool? extended = null, int? preview = null, int? previewLength = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_ids"] = RequestHelpers.ParseEnumerable(topicIds), ["order"] = order?.ToString(), ["offset"] = offset?.ToString(), ["count"] = count?.ToString(), ["extended"] = RequestHelpers.ParseBoolean(extended), ["preview"] = preview?.ToString(), ["preview_length"] = previewLength?.ToString(), }; return RequestManager.CreateRequestAsync<BoardGetTopicsExtendedResponse>("board.getTopics", null, request); } /// <summary> /// Re-opens a previously closed topic on a community's discussion board. /// </summary> public Task<ApiRequest<bool?>> OpenTopicApi(int? groupId = null, int? topicId = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("board.openTopic", null, request); } /// <summary> /// Restores a comment deleted from a topic on a community's discussion board. /// </summary> public Task<ApiRequest<bool?>> RestoreCommentApi(int? groupId = null, int? topicId = null, int? commentId = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), ["comment_id"] = commentId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("board.restoreComment", null, request); } /// <summary> /// Unpins a pinned topic from the top of a community's discussion board. /// </summary> public Task<ApiRequest<bool?>> UnfixTopicApi(int? groupId = null, int? topicId = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["topic_id"] = topicId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("board.unfixTopic", null, request); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; using NUnit.Framework; using QuantConnect.Data; using System.Collections.Generic; using QuantConnect.Securities.Option; namespace QuantConnect.Tests.Common { [TestFixture] public class SymbolTests { [Theory] [TestCaseSource(nameof(GetSymbolCreateTestCaseData))] public void SymbolCreate(string ticker, SecurityType securityType, string market, Symbol expected) { Assert.AreEqual(Symbol.Create(ticker, securityType, market), expected); } private static TestCaseData[] GetSymbolCreateTestCaseData() { return new [] { new TestCaseData("SPY", SecurityType.Equity, Market.USA, new Symbol(SecurityIdentifier.GenerateEquity("SPY", Market.USA), "SPY")), new TestCaseData("EURUSD", SecurityType.Forex, Market.FXCM, new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.FXCM), "EURUSD")), new TestCaseData("SPY", SecurityType.Option, Market.USA, new Symbol(SecurityIdentifier.GenerateOption(SecurityIdentifier.DefaultDate, Symbols.SPY.ID, Market.USA, 0, default(OptionRight), default(OptionStyle)), "?SPY")) }; } [Test] public void SymbolCreateBaseWithUnderlyingEquity() { var type = typeof(BaseData); var equitySymbol = Symbol.Create("TWX", SecurityType.Equity, Market.USA); var symbol = Symbol.CreateBase(type, equitySymbol, Market.USA); var symbolIDSymbol = symbol.ID.Symbol.Split(new[] { ".BaseData" }, StringSplitOptions.None).First(); Assert.IsTrue(symbol.SecurityType == SecurityType.Base); Assert.IsTrue(symbol.HasUnderlying); Assert.AreEqual(symbol.Underlying, equitySymbol); Assert.AreEqual(symbol.ID.Date, new DateTime(1998, 1, 2)); Assert.AreEqual("AOL", symbolIDSymbol); Assert.AreEqual(symbol.Underlying.ID.Symbol, symbolIDSymbol); Assert.AreEqual(symbol.Underlying.ID.Date, symbol.ID.Date); Assert.AreEqual(symbol.Underlying.Value, equitySymbol.Value); Assert.AreEqual(symbol.Underlying.Value, symbol.Value); } [Test] public void SymbolCreateBaseWithUnderlyingOption() { var type = typeof(BaseData); var optionSymbol = Symbol.CreateOption("TWX", Market.USA, OptionStyle.American, OptionRight.Call, 100, new DateTime(2050, 12, 31)); var symbol = Symbol.CreateBase(type, optionSymbol, Market.USA); var symbolIDSymbol = symbol.ID.Symbol.Split(new[] { ".BaseData" }, StringSplitOptions.None).First(); Assert.IsTrue(symbol.SecurityType == SecurityType.Base); Assert.IsTrue(symbol.HasUnderlying); Assert.AreEqual(symbol.Underlying, optionSymbol); Assert.IsTrue(symbol.Underlying.HasUnderlying); Assert.AreEqual(symbol.Underlying.Underlying.SecurityType, SecurityType.Equity); Assert.AreEqual(new DateTime(2050, 12, 31), symbol.ID.Date); Assert.AreEqual("AOL", symbolIDSymbol); Assert.AreEqual(symbol.Underlying.ID.Symbol, symbolIDSymbol); Assert.AreEqual(symbol.Underlying.ID.Date, symbol.ID.Date); Assert.AreEqual(symbol.Underlying.Value, symbol.Value); Assert.AreEqual(symbol.Underlying.Underlying.ID.Symbol, symbolIDSymbol); Assert.AreNotEqual(symbol.Underlying.Underlying.ID.Date, symbol.ID.Date); Assert.IsTrue(symbol.Value.StartsWith(symbol.Underlying.Underlying.Value)); Assert.AreEqual(symbol.Underlying.Underlying.ID.Symbol, symbol.Underlying.ID.Symbol); Assert.AreNotEqual(symbol.Underlying.Underlying.ID.Date, symbol.Underlying.ID.Date); Assert.IsTrue(symbol.Underlying.Value.StartsWith(symbol.Underlying.Underlying.Value)); } [Test] public void SymbolCreateWithOptionSecurityTypeCreatesCanonicalOptionSymbol() { var symbol = Symbol.Create("SPY", SecurityType.Option, Market.USA); var sid = symbol.ID; Assert.AreEqual(SecurityIdentifier.DefaultDate, sid.Date); Assert.AreEqual(0m, sid.StrikePrice); Assert.AreEqual(default(OptionRight), sid.OptionRight); Assert.AreEqual(default(OptionStyle), sid.OptionStyle); } [Test] public void CanonicalOptionSymbolAliasHasQuestionMark() { var symbol = Symbol.Create("SPY", SecurityType.Option, Market.USA); Assert.AreEqual("?SPY", symbol.Value); } [Test] public void UsesSidForDictionaryKey() { var sid = SecurityIdentifier.GenerateEquity("SPY", Market.USA); var dictionary = new Dictionary<Symbol, int> { {new Symbol(sid, "value"), 1} }; var key = new Symbol(sid, "other value"); Assert.IsTrue(dictionary.ContainsKey(key)); } [Test] public void CreatesOptionWithUnderlying() { var option = Symbol.CreateOption("XLRE", Market.USA, OptionStyle.American, OptionRight.Call, 21m, new DateTime(2016, 08, 19)); Assert.AreEqual(option.ID.Date, new DateTime(2016, 08, 19)); Assert.AreEqual(option.ID.StrikePrice, 21m); Assert.AreEqual(option.ID.OptionRight, OptionRight.Call); Assert.AreEqual(option.ID.OptionStyle, OptionStyle.American); Assert.AreEqual(option.Underlying.ID.Symbol, "XLRE"); } [Test] public void CompareToItselfReturnsZero() { var sym = new Symbol(SecurityIdentifier.GenerateForex("sym", Market.FXCM), "sym"); Assert.AreEqual(0, sym.CompareTo(sym)); } [Test] public void ComparesTheSameAsStringCompare() { var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a"); var z = new Symbol(SecurityIdentifier.GenerateForex("z", Market.FXCM), "z"); Assert.AreEqual(string.Compare("a", "z", StringComparison.Ordinal), a.CompareTo(z)); Assert.AreEqual(string.Compare("z", "a", StringComparison.Ordinal), z.CompareTo(a)); } [Test] public void ComparesTheSameAsStringCompareAndIgnoresCase() { var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a"); var z = new Symbol(SecurityIdentifier.GenerateForex("z", Market.FXCM), "z"); Assert.AreEqual(string.Compare("a", "Z", StringComparison.OrdinalIgnoreCase), a.CompareTo(z)); Assert.AreEqual(string.Compare("z", "A", StringComparison.OrdinalIgnoreCase), z.CompareTo(a)); } [Test] public void ComparesAgainstStringWithoutException() { var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a"); Assert.AreEqual(0, a.CompareTo("a")); } [Test] public void ComparesAgainstStringIgnoringCase() { var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a"); Assert.AreEqual(0, a.CompareTo("A")); } [Test] public void EqualsAgainstNullOrEmpty() { var validSymbol = Symbols.SPY; var emptySymbol = Symbol.Empty; var emptySymbolInstance = new Symbol(SecurityIdentifier.Empty, string.Empty); Symbol nullSymbol = null; Assert.IsTrue(emptySymbol.Equals(nullSymbol)); Assert.IsTrue(Symbol.Empty.Equals(nullSymbol)); Assert.IsTrue(emptySymbolInstance.Equals(nullSymbol)); Assert.IsTrue(emptySymbol.Equals(emptySymbol)); Assert.IsTrue(Symbol.Empty.Equals(emptySymbol)); Assert.IsTrue(emptySymbolInstance.Equals(emptySymbol)); Assert.IsFalse(validSymbol.Equals(nullSymbol)); Assert.IsFalse(validSymbol.Equals(emptySymbol)); Assert.IsFalse(validSymbol.Equals(emptySymbolInstance)); Assert.IsFalse(Symbol.Empty.Equals(validSymbol)); } [Test] public void ComparesAgainstNullOrEmpty() { var validSymbol = Symbols.SPY; var emptySymbol = Symbol.Empty; Symbol nullSymbol = null; Assert.IsTrue(nullSymbol == emptySymbol); Assert.IsFalse(nullSymbol != emptySymbol); Assert.IsTrue(emptySymbol == nullSymbol); Assert.IsFalse(emptySymbol != nullSymbol); Assert.IsTrue(validSymbol != null); Assert.IsTrue(emptySymbol == null); Assert.IsTrue(nullSymbol == null); Assert.IsFalse(validSymbol == null); Assert.IsFalse(emptySymbol != null); Assert.IsFalse(nullSymbol != null); Assert.IsTrue(validSymbol != Symbol.Empty); Assert.IsTrue(emptySymbol == Symbol.Empty); Assert.IsTrue(nullSymbol == Symbol.Empty); Assert.IsFalse(validSymbol == Symbol.Empty); Assert.IsFalse(emptySymbol != Symbol.Empty); Assert.IsFalse(nullSymbol != Symbol.Empty); Assert.IsTrue(null != validSymbol); Assert.IsTrue(null == emptySymbol); Assert.IsTrue(null == nullSymbol); Assert.IsFalse(null == validSymbol); Assert.IsFalse(null != emptySymbol); Assert.IsFalse(null != nullSymbol); Assert.IsTrue(Symbol.Empty != validSymbol); Assert.IsTrue(Symbol.Empty == emptySymbol); Assert.IsTrue(Symbol.Empty == nullSymbol); Assert.IsFalse(Symbol.Empty == validSymbol); Assert.IsFalse(Symbol.Empty != emptySymbol); Assert.IsFalse(Symbol.Empty != nullSymbol); } [Test] public void ImplicitOperatorsAreInverseFunctions() { #pragma warning disable 0618 // This test requires implicit operators var eurusd = new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.FXCM), "EURUSD"); string stringEurusd = eurusd; Symbol symbolEurusd = stringEurusd; Assert.AreEqual(eurusd, symbolEurusd); #pragma warning restore 0618 } [Test] public void ImplicitOperatorsReturnSIDOnFailure() { #pragma warning disable 0618 // This test requires implicit operators // this doesn't exist in the symbol cache var eurusd = new Symbol(SecurityIdentifier.GenerateForex("NOT-A-SECURITY", Market.FXCM), "EURUSD"); string stringEurusd = eurusd; Assert.AreEqual(eurusd.ID.ToString(), stringEurusd); Assert.Throws<ArgumentException>(() => { Symbol symbol = "this will not resolve to a proper Symbol instance"; }); Symbol notASymbol = "NotASymbol"; Assert.AreNotEqual(Symbol.Empty, notASymbol); Assert.IsTrue(notASymbol.ToString().Contains("NotASymbol")); #pragma warning restore 0618 } [Test] public void ImplicitFromStringChecksSymbolCache() { #pragma warning disable 0618 // This test requires implicit operators SymbolCache.Set("EURUSD", Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM)); string ticker = "EURUSD"; Symbol actual = ticker; var expected = SymbolCache.GetSymbol(ticker); Assert.AreEqual(expected, actual); SymbolCache.Clear(); #pragma warning restore 0618 } [Test] public void ImplicitFromStringParsesSid() { #pragma warning disable 0618 // This test requires implicit operators SymbolCache.Set("EURUSD", Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM)); var expected = SymbolCache.GetSymbol("EURUSD"); string sid = expected.ID.ToString(); Symbol actual = sid; Assert.AreEqual(expected, actual); SymbolCache.Clear(); #pragma warning restore 0618 } [Test] public void ImplicitFromWithinStringLiftsSecondArgument() { #pragma warning disable 0618 // This test requires implicit operators SymbolCache.Clear(); SymbolCache.Set("EURUSD", Symbols.EURUSD); var expected = SymbolCache.GetSymbol("EURUSD"); string stringValue = expected; string notFound = "EURGBP 8G"; var expectedNotFoundSymbol = Symbols.EURGBP; string sid = expected.ID.ToString(); Symbol actual = sid; if (!(expected == stringValue)) { Assert.Fail("Failed expected == string"); } else if (!(stringValue == expected)) { Assert.Fail("Failed string == expected"); } else if (expected != stringValue) { Assert.Fail("Failed expected != string"); } else if (stringValue != expected) { Assert.Fail("Failed string != expected"); } Symbol notFoundSymbol = notFound; Assert.AreEqual(expectedNotFoundSymbol, notFoundSymbol); SymbolCache.Clear(); #pragma warning restore 0618 } [Test] public void TestIfWeDetectCorrectlyWeekliesAndStandardOptionsBeforeFeb2015() { var symbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2012, 09, 22)); var weeklySymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2012, 09, 07)); Assert.True(OptionSymbol.IsStandard(symbol)); Assert.False(OptionSymbol.IsStandard(weeklySymbol)); Assert.AreEqual(new DateTime(2012, 09, 21)/*Friday*/, OptionSymbol.GetLastDayOfTrading(symbol)); Assert.AreEqual(new DateTime(2012, 09, 07)/*Friday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol)); } [Test] public void TestIfWeDetectCorrectlyWeekliesAndStandardOptionsAfterFeb2015() { var symbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2016, 02, 19)); var weeklySymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2016, 02, 05)); Assert.True(OptionSymbol.IsStandard(symbol)); Assert.False(OptionSymbol.IsStandard(weeklySymbol)); Assert.AreEqual(new DateTime(2016, 02, 19)/*Friday*/, OptionSymbol.GetLastDayOfTrading(symbol)); Assert.AreEqual(new DateTime(2016, 02, 05)/*Friday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol)); } [Test] public void TestIfWeDetectCorrectlyWeeklies() { var weeklySymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2020, 04, 10)); var monthlysymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2020, 04, 17)); Assert.True(OptionSymbol.IsWeekly(weeklySymbol)); Assert.False(OptionSymbol.IsWeekly(monthlysymbol)); Assert.AreEqual(new DateTime(2020, 04, 17)/*Friday*/, OptionSymbol.GetLastDayOfTrading(monthlysymbol)); //Good Friday on 10th so should be 9th Assert.AreEqual(new DateTime(2020, 04, 09)/*Thursday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol)); } [Test] public void HasUnderlyingSymbolReturnsTrueWhenSpecifyingCorrectUnderlying() { Assert.IsTrue(Symbols.SPY_C_192_Feb19_2016.HasUnderlyingSymbol(Symbols.SPY)); } [Test] public void HasUnderlyingSymbolReturnsFalsWhenSpecifyingIncorrectUnderlying() { Assert.IsFalse(Symbols.SPY_C_192_Feb19_2016.HasUnderlyingSymbol(Symbols.AAPL)); } [Test] public void TestIfFridayLastTradingDayIsHolidaysThenMoveToPreviousThursday() { var saturdayAfterGoodFriday = new DateTime(2014, 04, 19); var thursdayBeforeGoodFriday = saturdayAfterGoodFriday.AddDays(-2); var symbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, saturdayAfterGoodFriday); Assert.AreEqual(thursdayBeforeGoodFriday, OptionSymbol.GetLastDayOfTrading(symbol)); } [TestCase("ES", "ES")] [TestCase("GC", "OG")] [TestCase("ZT", "OZT")] public void FutureOptionsWithDifferentUnderlyingGlobexTickersAreMapped(string futureTicker, string expectedFutureOptionTicker) { var future = Symbol.CreateFuture(futureTicker, Market.CME, DateTime.UtcNow.Date); var canonicalFutureOption = Symbol.CreateOption( future, Market.CME, default(OptionStyle), default(OptionRight), default(decimal), SecurityIdentifier.DefaultDate); var nonCanonicalFutureOption = Symbol.CreateOption( future, Market.CME, default(OptionStyle), default(OptionRight), default(decimal), new DateTime(2020, 12, 18)); Assert.AreEqual(canonicalFutureOption.Underlying.ID.Symbol, futureTicker); Assert.AreEqual(canonicalFutureOption.ID.Symbol, expectedFutureOptionTicker); Assert.IsTrue(canonicalFutureOption.Value.StartsWith("?" + futureTicker)); Assert.AreEqual(nonCanonicalFutureOption.Underlying.ID.Symbol, futureTicker); Assert.AreEqual(nonCanonicalFutureOption.ID.Symbol, expectedFutureOptionTicker); Assert.IsTrue(nonCanonicalFutureOption.Value.StartsWith(expectedFutureOptionTicker)); } [Test] public void SymbolWithSidContainingUnderlyingCreatedWithoutNullUnderlying() { var future = Symbol.CreateFuture("ES", Market.CME, new DateTime(2020, 6, 19)); var optionSid = SecurityIdentifier.GenerateOption( future.ID.Date, future.ID, future.ID.Market, 3500m, OptionRight.Call, OptionStyle.American); var option = new Symbol(optionSid, "ES"); Assert.IsNotNull(option.Underlying); Assert.AreEqual(future, option.Underlying); } [TestCase("CL XKJAZ588SI4H", "CL", "CL21F21")] // Future [TestCase("CL JL", "CL", "/CL")] // Canonical Future [TestCase("ES 1S4 | ES XLDTU1KH5XC1", "CL", "?ES21F21")] // Future Option Canonical [TestCase("ES XKGCMV4QK9VO | ES XLDTU1KH5XC1", "ES", "ES21F21 201218C00000000")] // Future Option [TestCase("SPY 2U | SPY R735QTJ8XC9X", "SPY", "?SPY")] // Option Canonical [TestCase("GOOCV 305RBQ2BZBZT2 | GOOCV VP83T1ZUHROL", "GOOCV", "GOOCV 151224P00750000")] // Option [TestCase("SPY R735QTJ8XC9X", "SPY", "SPY")] // Equity [TestCase("EURGBP 8G", "EURGBP", "EURGBP")] // Forex [TestCase("BTCUSD XJ", "BTCUSD", "BTCUSD")] // Crypto public void SymbolAlias(string identifier, string ticker, string expectedValue) { var symbol = new Symbol(SecurityIdentifier.Parse(identifier), ticker); Assert.AreEqual(expectedValue, symbol.Value); } [TestCase("CL XKJAZ588SI4H", "CL", "CL21F21")] // Future [TestCase("CL JL", "CL", "/CL")] // Canonical Future [TestCase("ES 1S4 | ES XLDTU1KH5XC1", "ES", "?ES21F21")] // Future Option Canonical [TestCase("ES XKGCMV4QK9VO | ES XLDTU1KH5XC1", "ES", "ES21F21 201218C00000000")] // Future Option [TestCase("SPY 2U | SPY R735QTJ8XC9X", "SPY", "?SPY")] // Option Canonical [TestCase("GOOCV 305RBQ2BZBZT2 | GOOCV VP83T1ZUHROL", "GOOCV", "GOOCV 151224P00750000")] // Option [TestCase("SPY R735QTJ8XC9X", "SPY", null)] // Equity [TestCase("EURGBP 8G", "EURGBP", null)] // Forex [TestCase("BTCUSD XJ", "BTCUSD", null)] // Crypto public void SymbolCanonical(string identifier, string ticker, string expectedValue) { var symbol = new Symbol(SecurityIdentifier.Parse(identifier), ticker); if (expectedValue != null) { var result = symbol.Canonical; Assert.IsNotNull(result); Assert.AreSame(result, symbol.Canonical); Assert.IsTrue(result.IsCanonical()); Assert.IsTrue(result.Value.Contains(ticker)); Assert.AreEqual(symbol.SecurityType, result.SecurityType); Assert.AreEqual(symbol.ID.Market, result.ID.Market); } else { Assert.Throws<InvalidOperationException>(() => { var canonical = symbol.Canonical; }); } } [TestCase("SPY", "SPY", "SPY 2T")] [TestCase("NWSA", "FOXA", "NWSA 2T")] [TestCase("NWSA", "FOXA", "NWSA 2S|NWSA 2T")] [TestCase("QQQQ", "QQQ", "QQQQ 2S|QQQQ 31|QQQQ 2T")] public void SymbolAndUnderlyingSymbolsMapped(string ticker, string mappedTicker, string sid) { var symbol = new Symbol(SecurityIdentifier.Parse(sid), ticker); var symbolChain = symbol; do { Assert.AreEqual(symbolChain.Value, ticker); symbolChain = symbolChain.Underlying; } while (symbolChain != null); symbol = symbol.UpdateMappedSymbol(mappedTicker); symbolChain = symbol; do { Console.WriteLine(symbolChain.ToString() + "; Value: " + symbolChain.Value); if (symbolChain.SecurityType == SecurityType.Base || symbolChain.RequiresMapping()) { Assert.AreEqual(mappedTicker, symbolChain.Value); } else { Assert.AreNotEqual(mappedTicker, symbolChain.Value); } symbolChain = symbolChain.Underlying; } while (symbolChain != null); } [Test] public void SymbolReferenceNotMappedOnUpdate() { var symbol = Symbol.Create("NWSA", SecurityType.Equity, Market.USA); var customSymbol = Symbol.CreateBase(typeof(BaseData), symbol, Market.USA); var mappedSymbol = customSymbol.UpdateMappedSymbol("FOXA"); Assert.AreNotEqual(customSymbol.Value, mappedSymbol.Value); Assert.AreNotEqual(customSymbol.Underlying.Value, mappedSymbol.Underlying.Value); Assert.AreNotEqual(symbol.Value, mappedSymbol.Underlying.Value); } } }
#pragma warning disable 169 // ReSharper disable InconsistentNaming namespace NEventStore { using System; using System.Collections.Generic; using System.Linq; using NEventStore.Persistence; using NEventStore.Persistence.AcceptanceTests; using NEventStore.Persistence.AcceptanceTests.BDD; using Xunit; using Xunit.Should; public class OptimisticPipelineHookTests { public class when_committing_with_a_sequence_beyond_the_known_end_of_a_stream : using_commit_hooks { private const int HeadStreamRevision = 5; private const int HeadCommitSequence = 1; private const int ExpectedNextCommitSequence = HeadCommitSequence + 1; private const int BeyondEndOfStreamCommitSequence = ExpectedNextCommitSequence + 1; private ICommit _alreadyCommitted; private CommitAttempt _beyondEndOfStream; private Exception _thrown; protected override void Context() { _alreadyCommitted = BuildCommitStub(HeadStreamRevision, HeadCommitSequence); _beyondEndOfStream = BuildCommitAttemptStub(HeadStreamRevision + 1, BeyondEndOfStreamCommitSequence); Hook.PostCommit(_alreadyCommitted); } protected override void Because() { _thrown = Catch.Exception(() => Hook.PreCommit(_beyondEndOfStream)); } [Fact] public void should_throw_a_PersistenceException() { _thrown.ShouldBeInstanceOf<StorageException>(); } } public class when_committing_with_a_revision_beyond_the_known_end_of_a_stream : using_commit_hooks { private const int HeadCommitSequence = 1; private const int HeadStreamRevision = 1; private const int NumberOfEventsBeingCommitted = 1; private const int ExpectedNextStreamRevision = HeadStreamRevision + 1 + NumberOfEventsBeingCommitted; private const int BeyondEndOfStreamRevision = ExpectedNextStreamRevision + 1; private ICommit _alreadyCommitted; private CommitAttempt _beyondEndOfStream; private Exception _thrown; protected override void Context() { _alreadyCommitted = BuildCommitStub(HeadStreamRevision, HeadCommitSequence); _beyondEndOfStream = BuildCommitAttemptStub(BeyondEndOfStreamRevision, HeadCommitSequence + 1); Hook.PostCommit(_alreadyCommitted); } protected override void Because() { _thrown = Catch.Exception(() => Hook.PreCommit(_beyondEndOfStream)); } [Fact] public void should_throw_a_PersistenceException() { _thrown.ShouldBeInstanceOf<StorageException>(); } } public class when_committing_with_a_sequence_less_or_equal_to_the_most_recent_sequence_for_the_stream : using_commit_hooks { private const int HeadStreamRevision = 42; private const int HeadCommitSequence = 42; private const int DupliateCommitSequence = HeadCommitSequence; private CommitAttempt Attempt; private ICommit Committed; private Exception thrown; protected override void Context() { Committed = BuildCommitStub(HeadStreamRevision, HeadCommitSequence); Attempt = BuildCommitAttemptStub(HeadStreamRevision + 1, DupliateCommitSequence); Hook.PostCommit(Committed); } protected override void Because() { thrown = Catch.Exception(() => Hook.PreCommit(Attempt)); } [Fact] public void should_throw_a_ConcurrencyException() { thrown.ShouldBeInstanceOf<ConcurrencyException>(); } } public class when_committing_with_a_revision_less_or_equal_to_than_the_most_recent_revision_read_for_the_stream : using_commit_hooks { private const int HeadStreamRevision = 3; private const int HeadCommitSequence = 2; private const int DuplicateStreamRevision = HeadStreamRevision; private ICommit _committed; private CommitAttempt _failedAttempt; private Exception _thrown; protected override void Context() { _committed = BuildCommitStub(HeadStreamRevision, HeadCommitSequence); _failedAttempt = BuildCommitAttemptStub(DuplicateStreamRevision, HeadCommitSequence + 1); Hook.PostCommit(_committed); } protected override void Because() { _thrown = Catch.Exception(() => Hook.PreCommit(_failedAttempt)); } [Fact] public void should_throw_a_ConcurrencyException() { _thrown.ShouldBeInstanceOf<ConcurrencyException>(); } } public class when_committing_with_a_commit_sequence_less_than_or_equal_to_the_most_recent_commit_for_the_stream : using_commit_hooks { private const int DuplicateCommitSequence = 1; private CommitAttempt _failedAttempt; private ICommit _successfulAttempt; private Exception _thrown; protected override void Context() { _successfulAttempt = BuildCommitStub(1, DuplicateCommitSequence); _failedAttempt = BuildCommitAttemptStub(2, DuplicateCommitSequence); Hook.PostCommit(_successfulAttempt); } protected override void Because() { _thrown = Catch.Exception(() => Hook.PreCommit(_failedAttempt)); } [Fact] public void should_throw_a_ConcurrencyException() { _thrown.ShouldBeInstanceOf<ConcurrencyException>(); } } public class when_committing_with_a_stream_revision_less_than_or_equal_to_the_most_recent_commit_for_the_stream : using_commit_hooks { private const int DuplicateStreamRevision = 2; private CommitAttempt _failedAttempt; private ICommit _successfulAttempt; private Exception _thrown; protected override void Context() { _successfulAttempt = BuildCommitStub(DuplicateStreamRevision, 1); _failedAttempt = BuildCommitAttemptStub(DuplicateStreamRevision, 2); Hook.PostCommit(_successfulAttempt); } protected override void Because() { _thrown = Catch.Exception(() => Hook.PreCommit(_failedAttempt)); } [Fact] public void should_throw_a_ConcurrencyException() { _thrown.ShouldBeInstanceOf<ConcurrencyException>(); } } public class when_tracking_commits : SpecificationBase { private const int MaxStreamsToTrack = 2; private ICommit[] _trackedCommitAttempts; private OptimisticPipelineHook _hook; protected override void Context() { _trackedCommitAttempts = new[] { BuildCommit(Guid.NewGuid(), Guid.NewGuid()), BuildCommit(Guid.NewGuid(), Guid.NewGuid()), BuildCommit(Guid.NewGuid(), Guid.NewGuid()) }; _hook = new OptimisticPipelineHook(MaxStreamsToTrack); } protected override void Because() { foreach (var commit in _trackedCommitAttempts) { _hook.Track(commit); } } [Fact] public void should_only_contain_streams_explicitly_tracked() { ICommit untracked = BuildCommit(Guid.Empty, _trackedCommitAttempts[0].CommitId); _hook.Contains(untracked).ShouldBeFalse(); } [Fact] public void should_find_tracked_streams() { ICommit stillTracked = BuildCommit(_trackedCommitAttempts.Last().StreamId, _trackedCommitAttempts.Last().CommitId); _hook.Contains(stillTracked).ShouldBeTrue(); } [Fact] public void should_only_track_the_specified_number_of_streams() { ICommit droppedFromTracking = BuildCommit( _trackedCommitAttempts.First().StreamId, _trackedCommitAttempts.First().CommitId); _hook.Contains(droppedFromTracking).ShouldBeFalse(); } private ICommit BuildCommit(Guid streamId, Guid commitId) { return BuildCommit(streamId.ToString(), commitId); } private ICommit BuildCommit(string streamId, Guid commitId) { return new Commit(Bucket.Default, streamId, 0, commitId, 0, SystemTime.UtcNow, new LongCheckpoint(0).Value, null, null); } } public class when_purging : SpecificationBase { private ICommit _trackedCommit; private OptimisticPipelineHook _hook; protected override void Context() { _trackedCommit = BuildCommit(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()); _hook = new OptimisticPipelineHook(); _hook.Track(_trackedCommit); } protected override void Because() { _hook.OnPurge(); } [Fact] public void should_not_track_commit() { _hook.Contains(_trackedCommit).ShouldBeFalse(); } private ICommit BuildCommit(Guid bucketId, Guid streamId, Guid commitId) { return new Commit(bucketId.ToString(), streamId.ToString(), 0, commitId, 0, SystemTime.UtcNow, new LongCheckpoint(0).Value, null, null); } } public class when_purging_a_bucket : SpecificationBase { private ICommit _trackedCommitBucket1; private ICommit _trackedCommitBucket2; private OptimisticPipelineHook _hook; protected override void Context() { _trackedCommitBucket1 = BuildCommit(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()); _trackedCommitBucket2 = BuildCommit(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()); _hook = new OptimisticPipelineHook(); _hook.Track(_trackedCommitBucket1); _hook.Track(_trackedCommitBucket2); } protected override void Because() { _hook.OnPurge(_trackedCommitBucket1.BucketId); } [Fact] public void should_not_track_the_commit_in_bucket() { _hook.Contains(_trackedCommitBucket1).ShouldBeFalse(); } [Fact] public void should_track_the_commit_in_other_bucket() { _hook.Contains(_trackedCommitBucket2).ShouldBeTrue(); } private ICommit BuildCommit(Guid bucketId, Guid streamId, Guid commitId) { return new Commit(bucketId.ToString(), streamId.ToString(), 0, commitId, 0, SystemTime.UtcNow, new LongCheckpoint(0).Value, null, null); } } public class when_deleting_a_stream : SpecificationBase { private ICommit _trackedCommit; private ICommit _trackedCommitDeleted; private OptimisticPipelineHook _hook; private readonly Guid _bucketId = Guid.NewGuid(); private readonly Guid _streamIdDeleted = Guid.NewGuid(); protected override void Context() { _trackedCommit = BuildCommit(_bucketId, Guid.NewGuid(), Guid.NewGuid()); _trackedCommitDeleted = BuildCommit(_bucketId, _streamIdDeleted, Guid.NewGuid()); _hook = new OptimisticPipelineHook(); _hook.Track(_trackedCommit); _hook.Track(_trackedCommitDeleted); } protected override void Because() { _hook.OnDeleteStream(_trackedCommitDeleted.BucketId, _trackedCommitDeleted.StreamId); } [Fact] public void should_not_track_the_commit_in_the_deleted_stream() { _hook.Contains(_trackedCommitDeleted).ShouldBeFalse(); } [Fact] public void should_track_the_commit_that_is_not_in_the_deleted_stream() { _hook.Contains(_trackedCommit).ShouldBeTrue(); } private ICommit BuildCommit(Guid bucketId, Guid streamId, Guid commitId) { return new Commit(bucketId.ToString(), streamId.ToString(), 0, commitId, 0, SystemTime.UtcNow, new LongCheckpoint(0).Value, null, null); } } public abstract class using_commit_hooks : SpecificationBase { protected readonly OptimisticPipelineHook Hook = new OptimisticPipelineHook(); private readonly string _streamId = Guid.NewGuid().ToString(); protected CommitAttempt BuildCommitStub(Guid commitId) { return new CommitAttempt(_streamId, 1, commitId, 1, SystemTime.UtcNow, null, null); } protected ICommit BuildCommitStub(int streamRevision, int commitSequence) { List<EventMessage> events = new[] {new EventMessage()}.ToList(); return new Commit(Bucket.Default, _streamId, streamRevision, Guid.NewGuid(), commitSequence, SystemTime.UtcNow, new LongCheckpoint(0).Value, null, events); } protected CommitAttempt BuildCommitAttemptStub(int streamRevision, int commitSequence) { List<EventMessage> events = new[] {new EventMessage()}.ToList(); return new CommitAttempt(Bucket.Default, _streamId, streamRevision, Guid.NewGuid(), commitSequence, SystemTime.UtcNow, null, events); } protected ICommit BuildCommitStub(Guid commitId, int streamRevision, int commitSequence) { List<EventMessage> events = new[] {new EventMessage()}.ToList(); return new Commit(Bucket.Default, _streamId, streamRevision, commitId, commitSequence, SystemTime.UtcNow, new LongCheckpoint(0).Value, null, events); } } } } // ReSharper enable InconsistentNaming #pragma warning restore 169
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- function CollisionToy::create( %this ) { // Set the sandbox drag mode availability. Sandbox.allowManipulation( pull ); // Set the manipulation mode. Sandbox.useManipulation( pull ); // Configure the toy. CollisionToy.MaxBlockers = 50; CollisionToy.MaxBalls = 10; // Add configuration option. addNumericOption("Max Blockers", 1, 100, 10, "setMaxBlockers", CollisionToy.MaxBlockers, true, "Sets the number of blockers created."); addNumericOption("Max Balls", 1, 100, 10, "setMaxBalls", CollisionToy.MaxBalls, true, "Sets the number of balls created."); // Reset the toy. CollisionToy.reset(); } //----------------------------------------------------------------------------- function CollisionToy::destroy( %this ) { } //----------------------------------------------------------------------------- function CollisionToy::reset( %this ) { // Clear the scene. SandboxScene.clear(); // Create background. %this.createBackground(); // Create blockers. %this.createBlockers(); // Create balls. %this.createBalls(); } //----------------------------------------------------------------------------- function CollisionToy::createBackground( %this ) { // Create the sprite. %object = new Sprite(); // Set the sprite as "static" so it is not affected by gravity. %object.BodyType = static; // Always try to configure a scene-object prior to adding it to a scene for best performance. // Set the position. %object.Position = "0 0"; // Set the size. %object.Size = "100 75"; // Set to the furthest background layer. %object.SceneLayer = 31; // Set the scroller to use an animation! %object.Image = "ToyAssets:highlightBackground"; // Set the blend color. %object.BlendColor = SlateGray; // Create border collisions. %object.createEdgeCollisionShape( -50, -37.5, -50, 37.5 ); %object.createEdgeCollisionShape( 50, -37.5, 50, 37.5 ); %object.createEdgeCollisionShape( -50, 37.5, 50, 37.5 ); %object.createEdgeCollisionShape( -50, -34.5, 50, -34.5 ); // Add the sprite to the scene. SandboxScene.add( %object ); } //----------------------------------------------------------------------------- function CollisionToy::createBlockers( %this ) { // Create blockers. for( %n = 0; %n < CollisionToy.MaxBlockers; %n++ ) { // Choose a uniform area. %sizeX = getRandom(1, 9); %sizeY = 10 - %sizeX; // Create sprite. %object = new Sprite(); %object.BodyType = static; %object.Position = getRandom( -40, 40 ) SPC getRandom( -30, 30 ); %object.Layer = 30; %object.Size = %sizeX SPC %sizeY; %object.createPolygonBoxCollisionShape(); %object.Image = "ToyAssets:Blocks"; %object.Frame = getRandom(0,55); SandboxScene.add( %object ); } } //----------------------------------------------------------------------------- function CollisionToy::createBalls( %this ) { // Create balls. for( %n = 0; %n < CollisionToy.MaxBalls; %n++ ) { // Create the sprite. %object = new Sprite() { class = "CollisionToyBall"; }; // Always try to configure a scene-object prior to adding it to a scene for best performance. // Set the position. %object.Position = getRandom(-30,30) SPC getRandom(-30,30); // If the size is to be square then we can simply pass a single value. // This applies to any 'Vector2' engine type. %object.Size = 3; // Set the layer. %object.Layer = 20; // Create a circle collision shape. %object.setDefaultRestitution( 1 ); %object.setDefaultFriction( 0.1 ); %object.createCircleCollisionShape( 1.5 ); %object.CollisionCallback = true; // Set the sprite to use an image. This is known as "static" image mode. %object.Image = "ToyAssets:Football"; // We don't really need to do this as the frame is set to zero by default. %object.Frame = 0; // Set velocities. %object.SetLinearVelocity( getRandom(-40,40) SPC getRandom(-30,30) ); %object.SetAngularVelocity( getRandom(-360,360) ); // Add the sprite to the scene. SandboxScene.add( %object ); } } //----------------------------------------------------------------------------- function CollisionToyBall::onCollision(%this, %object, %collisionDetails) { // Finish if there are no contact points (this happens with sensors). if ( %collisionDetails.count <= 2 ) return; // Fetch the first contact point (there may possibly be two but ignore that here). %contactPosition = %collisionDetails._4 SPC %collisionDetails._5; // Create a marker sprite with a limited lifetime. // Also set this so that it can't be picked so you can't drag it via the Sandbox "pull" feature. %object = new Sprite(); %object.Position = %contactPosition; %object.Layer = 10; %object.Size = 3; %object.Image = "ToyAssets:Crosshair2"; %object.BlendColor = LimeGreen; %object.AngularVelocity = -180; %object.Lifetime = 3; %object.PickingAllowed = false; SandboxScene.add( %object ); } //----------------------------------------------------------------------------- function CollisionToy::setMaxBlockers(%this, %value) { %this.MaxBlockers = %value; } //----------------------------------------------------------------------------- function CollisionToy::setMaxBalls(%this, %value) { %this.MaxBalls = %value; }
using System; using System.Collections.Generic; using System.Reflection; using Verse.Resolvers; using Verse.Generators; namespace Verse { /// <summary> /// Utility class able to scan any type (using reflection) to automatically /// declare its fields to a decoder or encoder descriptor. /// </summary> public static class Linker { private const BindingFlags DefaultBindings = BindingFlags.Instance | BindingFlags.Public; /// <summary> /// Describe and create decoder for given schema using reflection on target entity and provided binding flags. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="schema">Entity schema</param> /// <param name="bindings">Binding flags used to filter bound fields and properties</param> /// <returns>Entity decoder</returns> public static IDecoder<TEntity> CreateDecoder<TEntity>(ISchema<TEntity> schema, BindingFlags bindings) { if (!Linker.LinkDecoder(schema.DecoderDescriptor, bindings, new Dictionary<Type, object>())) throw new ArgumentException($"can't link decoder for type '{typeof(TEntity)}'", nameof(schema)); return schema.CreateDecoder(ConstructorGenerator.CreateConstructor<TEntity>()); } /// <summary> /// Describe and create decoder for given schema using reflection on target entity. Only public instance fields /// and properties are linked. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="schema">Entity schema</param> /// <returns>Entity decoder</returns> public static IDecoder<TEntity> CreateDecoder<TEntity>(ISchema<TEntity> schema) { return Linker.CreateDecoder(schema, Linker.DefaultBindings); } /// <summary> /// Describe and create encoder for given schema using reflection on target entity and provided binding flags. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="schema">Entity schema</param> /// <param name="bindings">Binding flags used to filter bound fields and properties</param> /// <returns>Entity encoder</returns> public static IEncoder<TEntity> CreateEncoder<TEntity>(ISchema<TEntity> schema, BindingFlags bindings) { if (!Linker.LinkEncoder(schema.EncoderDescriptor, bindings, new Dictionary<Type, object>())) throw new ArgumentException($"can't link encoder for type '{typeof(TEntity)}'", nameof(schema)); return schema.CreateEncoder(); } /// <summary> /// Describe and create encoder for given schema using reflection on target entity. Only public instance fields /// and properties are linked. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="schema">Entity schema</param> /// <returns>Entity encoder</returns> public static IEncoder<TEntity> CreateEncoder<TEntity>(ISchema<TEntity> schema) { return Linker.CreateEncoder(schema, Linker.DefaultBindings); } private static bool LinkDecoder<T>(IDecoderDescriptor<T> descriptor, BindingFlags bindings, IDictionary<Type, object> parents) { var entityType = typeof(T); parents[entityType] = descriptor; if (Linker.TryLinkDecoderAsValue(descriptor)) return true; // Bind descriptor as an array of target type is also array if (entityType.IsArray) { var element = entityType.GetElementType(); var setter = MethodResolver .Create<Func<Setter<object[], IEnumerable<object>>>>(() => SetterGenerator.CreateFromEnumerable<object>()) .SetGenericArguments(element) .Invoke(null); return Linker.LinkDecoderAsArray(descriptor, bindings, element, setter, parents); } // Try to bind descriptor as an array if target type IEnumerable<> foreach (var interfaceType in entityType.GetInterfaces()) { // Make sure that interface is IEnumerable<T> and store typeof(T) if (!TypeResolver.Create(interfaceType) .HasSameDefinitionThan<IEnumerable<object>>(out var interfaceTypeArguments)) continue; var elementType = interfaceTypeArguments[0]; // Search constructor compatible with IEnumerable<> foreach (var constructor in entityType.GetConstructors()) { var parameters = constructor.GetParameters(); if (parameters.Length != 1) continue; var parameterType = parameters[0].ParameterType; if (!TypeResolver.Create(parameterType) .HasSameDefinitionThan<IEnumerable<object>>(out var parameterArguments) || parameterArguments[0] != elementType) continue; var setter = MethodResolver .Create<Func<ConstructorInfo, Setter<object, object>>>(c => SetterGenerator.CreateFromConstructor<object, object>(c)) .SetGenericArguments(entityType, parameterType) .Invoke(null, constructor); return Linker.LinkDecoderAsArray(descriptor, bindings, elementType, setter, parents); } } // Bind readable and writable instance properties foreach (var property in entityType.GetProperties(bindings)) { if (property.GetGetMethod() == null || property.GetSetMethod() == null || property.Attributes.HasFlag(PropertyAttributes.SpecialName)) continue; var setter = MethodResolver .Create<Func<PropertyInfo, Setter<object, object>>>(p => SetterGenerator.CreateFromProperty<object, object>(p)) .SetGenericArguments(entityType, property.PropertyType) .Invoke(null, property); if (!Linker.LinkDecoderAsObject(descriptor, bindings, property.PropertyType, property.Name, setter, parents)) return false; } // Bind public instance fields foreach (var field in entityType.GetFields(bindings)) { if (field.Attributes.HasFlag(FieldAttributes.SpecialName)) continue; var setter = MethodResolver .Create<Func<FieldInfo, Setter<object, object>>>(f => SetterGenerator.CreateFromField<object, object>(f)) .SetGenericArguments(entityType, field.FieldType) .Invoke(null, field); if (!Linker.LinkDecoderAsObject(descriptor, bindings, field.FieldType, field.Name, setter, parents)) return false; } return true; } private static bool LinkDecoderAsArray<TEntity>(IDecoderDescriptor<TEntity> descriptor, BindingFlags bindings, Type type, object setter, IDictionary<Type, object> parents) { var constructor = MethodResolver .Create<Func<object>>(() => ConstructorGenerator.CreateConstructor<object>()) .SetGenericArguments(type) .Invoke(null); if (parents.TryGetValue(type, out var recurse)) { MethodResolver .Create<Func<IDecoderDescriptor<TEntity>, Func<object>, Setter<TEntity, IEnumerable<object>>, IDecoderDescriptor<object>, IDecoderDescriptor<object>>>((d, c, s, p) => d.HasElements(c, s, p)) .SetGenericArguments(type) .Invoke(descriptor, constructor, setter, recurse); return true; } var itemDescriptor = MethodResolver .Create<Func<IDecoderDescriptor<TEntity>, Func<object>, Setter<TEntity, IEnumerable<object>>, IDecoderDescriptor<object>>>((d, c, s) => d.HasElements(c, s)) .SetGenericArguments(type) .Invoke(descriptor, constructor, setter); var result = MethodResolver .Create<Func<IDecoderDescriptor<object>, BindingFlags, Dictionary<Type, object>, bool>>((d, f, p) => Linker.LinkDecoder(d, f, p)) .SetGenericArguments(type) .Invoke(null, itemDescriptor, bindings, parents); return result is bool success && success; } private static bool LinkDecoderAsObject<TEntity>(IDecoderDescriptor<TEntity> descriptor, BindingFlags bindings, Type type, string name, object setter, IDictionary<Type, object> parents) { var constructor = MethodResolver .Create<Func<object>>(() => ConstructorGenerator.CreateConstructor<object>()) .SetGenericArguments(type) .Invoke(null); if (parents.TryGetValue(type, out var parent)) { MethodResolver .Create<Func<IDecoderDescriptor<TEntity>, string, Func<object>, Setter<TEntity, object>, IDecoderDescriptor<object>, IDecoderDescriptor<object>>>((d, n, c, s, p) => d.HasField(n, c, s, p)) .SetGenericArguments(type) .Invoke(descriptor, name, constructor, setter, parent); return true; } var fieldDescriptor = MethodResolver .Create<Func<IDecoderDescriptor<TEntity>, string, Func<object>, Setter<TEntity, object>, IDecoderDescriptor<object>>>((d, n, c, s) => d.HasField(n, c, s)) .SetGenericArguments(type) .Invoke(descriptor, name, constructor, setter); var result = MethodResolver .Create<Func<IDecoderDescriptor<object>, BindingFlags, Dictionary<Type, object>, bool>>((d, f, p) => Linker.LinkDecoder(d, f, p)) .SetGenericArguments(type) .Invoke(null, fieldDescriptor, bindings, parents); return result is bool success && success; } private static bool LinkEncoder<T>(IEncoderDescriptor<T> descriptor, BindingFlags bindings, IDictionary<Type, object> parents) { var entityType = typeof(T); parents[entityType] = descriptor; if (Linker.TryLinkEncoderAsValue(descriptor)) return true; // Bind descriptor as an array of target type is also array if (entityType.IsArray) { var element = entityType.GetElementType(); var getter = MethodResolver .Create<Func<Func<object, object>>>(() => GetterGenerator.CreateIdentity<object>()) .SetGenericArguments(typeof(IEnumerable<>).MakeGenericType(element)) .Invoke(null); return Linker.LinkEncoderAsArray(descriptor, bindings, element, getter, parents); } // Try to bind descriptor as an array if target type IEnumerable<> foreach (var interfaceType in entityType.GetInterfaces()) { // Make sure that interface is IEnumerable<T> and store typeof(T) if (!TypeResolver.Create(interfaceType).HasSameDefinitionThan<IEnumerable<object>>(out var arguments)) continue; var elementType = arguments[0]; var getter = MethodResolver .Create<Func<Func<object, object>>>(() => GetterGenerator.CreateIdentity<object>()) .SetGenericArguments(typeof(IEnumerable<>).MakeGenericType(elementType)) .Invoke(null); return Linker.LinkEncoderAsArray(descriptor, bindings, elementType, getter, parents); } // Bind readable and writable instance properties foreach (var property in entityType.GetProperties(bindings)) { if (property.GetGetMethod() == null || property.GetSetMethod() == null || property.Attributes.HasFlag(PropertyAttributes.SpecialName)) continue; var getter = MethodResolver .Create<Func<PropertyInfo, Func<object, object>>>(p => GetterGenerator.CreateFromProperty<object, object>(p)) .SetGenericArguments(entityType, property.PropertyType) .Invoke(null, property); if (!Linker.LinkEncoderAsObject(descriptor, bindings, property.PropertyType, property.Name, getter, parents)) return false; } // Bind public instance fields foreach (var field in entityType.GetFields(bindings)) { if (field.Attributes.HasFlag(FieldAttributes.SpecialName)) continue; var getter = MethodResolver .Create<Func<FieldInfo, Func<object, object>>>(f => GetterGenerator.CreateFromField<object, object>(f)) .SetGenericArguments(entityType, field.FieldType) .Invoke(null, field); if (!Linker.LinkEncoderAsObject(descriptor, bindings, field.FieldType, field.Name, getter, parents)) return false; } return true; } private static bool LinkEncoderAsArray<TEntity>(IEncoderDescriptor<TEntity> descriptor, BindingFlags bindings, Type type, object getter, IDictionary<Type, object> parents) { if (parents.TryGetValue(type, out var recurse)) { MethodResolver .Create<Func<IEncoderDescriptor<TEntity>, Func<TEntity, IEnumerable<object>>, IEncoderDescriptor<object>, IEncoderDescriptor<object>>>((d, a, p) => d.HasElements(a, p)) .SetGenericArguments(type) .Invoke(descriptor, getter, recurse); return true; } var itemDescriptor = MethodResolver .Create<Func<IEncoderDescriptor<TEntity>, Func<TEntity, IEnumerable<object>>, IEncoderDescriptor<object> >>((d, a) => d.HasElements(a)) .SetGenericArguments(type) .Invoke(descriptor, getter); var result = MethodResolver .Create<Func<IEncoderDescriptor<object>, BindingFlags, Dictionary<Type, object>, bool>>((d, f, p) => Linker.LinkEncoder(d, f, p)) .SetGenericArguments(type) .Invoke(null, itemDescriptor, bindings, parents); return result is bool success && success; } private static bool LinkEncoderAsObject<TEntity>(IEncoderDescriptor<TEntity> descriptor, BindingFlags bindings, Type type, string name, object getter, IDictionary<Type, object> parents) { if (parents.TryGetValue(type, out var recurse)) { MethodResolver .Create<Func<IEncoderDescriptor<TEntity>, string, Func<TEntity, object>, IEncoderDescriptor<object>, IEncoderDescriptor<object>>>((d, n, a, p) => d.HasField(n, a, p)) .SetGenericArguments(type) .Invoke(descriptor, name, getter, recurse); return true; } var fieldDescriptor = MethodResolver .Create<Func<IEncoderDescriptor<TEntity>, string, Func<TEntity, object>, IEncoderDescriptor<object>>>( (d, n, a) => d.HasField(n, a)) .SetGenericArguments(type) .Invoke(descriptor, name, getter); var result = MethodResolver .Create<Func<IEncoderDescriptor<object>, BindingFlags, Dictionary<Type, object>, bool>>((d, f, p) => Linker.LinkEncoder(d, f, p)) .SetGenericArguments(type) .Invoke(null, fieldDescriptor, bindings, parents); return result is bool success && success; } private static bool TryLinkDecoderAsValue<TEntity>(IDecoderDescriptor<TEntity> descriptor) { try { descriptor.HasValue(); return true; } catch (InvalidCastException) { // Invalid cast exception being thrown means binding fails return false; } } private static bool TryLinkEncoderAsValue<TEntity>(IEncoderDescriptor<TEntity> descriptor) { try { descriptor.HasValue(); return true; } catch (InvalidCastException) { // Invalid cast exception being thrown means binding fails return false; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Extensibility.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo; using Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; using Roslyn.Test.EditorUtilities.NavigateTo; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NavigateTo { public class NavigateToTests : AbstractNavigateToTests { protected override string Language => "csharp"; protected override TestWorkspace CreateWorkspace(string content, ExportProvider exportProvider) => TestWorkspace.CreateCSharp(content, exportProvider: exportProvider); [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task NoItemsForEmptyFile() { await TestAsync("", async w => { Assert.Empty(await _aggregator.GetItemsAsync("Hello")); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClass() { await TestAsync( @"class Foo { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", "[|Foo|]", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindVerbatimClass() { await TestAsync( @"class @static { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("static")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "static", "[|static|]", MatchKind.Exact, NavigateToItemKind.Class); // Check searching for @static too item = (await _aggregator.GetItemsAsync("@static")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "static", "[|static|]", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindNestedClass() { await TestAsync( @"class Foo { class Bar { internal class DogBed { } } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("DogBed")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DogBed", "[|DogBed|]", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMemberInANestedClass() { await TestAsync( @"class Foo { class Bar { class DogBed { public void Method() { } } } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Method")).Single(); VerifyNavigateToResultItem(item, "Method", "[|Method|]()", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo.Bar.DogBed"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindGenericClassWithConstraints() { await TestAsync( @"using System.Collections; class Foo<T> where T : IEnumerable { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", "[|Foo|]<T>", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindGenericMethodWithConstraints() { await TestAsync( @"using System; class Foo<U> { public void Bar<T>(T item) where T : IComparable<T> { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|]<T>(T)", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo<U>"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialClass() { await TestAsync( @"public partial class Foo { int a; } partial class Foo { int b; }", async w => { var expecteditem1 = new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Foo"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindTypesInMetadata() { await TestAsync( @"using System; Class Program { FileStyleUriParser f; }", async w => { var items = await _aggregator.GetItemsAsync("FileStyleUriParser"); Assert.Equal(items.Count(), 0); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClassInNamespace() { await TestAsync( @"namespace Bar { class Foo { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", "[|Foo|]", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindStruct() { await TestAsync( @"struct Bar { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupStruct, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("B")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Bar", "[|B|]ar", MatchKind.Prefix, NavigateToItemKind.Structure); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEnum() { await TestAsync( @"enum Colors { Red, Green, Blue }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnum, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("Colors")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Colors", "[|Colors|]", MatchKind.Exact, NavigateToItemKind.Enum); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEnumMember() { await TestAsync( @"enum Colors { Red, Green, Blue }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnumMember, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("R")).Single(); VerifyNavigateToResultItem(item, "Red", "[|R|]ed", MatchKind.Prefix, NavigateToItemKind.EnumItem); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindField1() { await TestAsync( @"class Foo { int bar; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("b")).Single(); VerifyNavigateToResultItem(item, "bar", "[|b|]ar", MatchKind.Prefix, NavigateToItemKind.Field, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindField2() { await TestAsync( @"class Foo { int bar; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("ba")).Single(); VerifyNavigateToResultItem(item, "bar", "[|ba|]r", MatchKind.Prefix, NavigateToItemKind.Field, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindField3() { await TestAsync( @"class Foo { int bar; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); Assert.Empty(await _aggregator.GetItemsAsync("ar")); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindVerbatimField() { await TestAsync( @"class Foo { int @string; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("string")).Single(); VerifyNavigateToResultItem(item, "string", "[|string|]", MatchKind.Exact, NavigateToItemKind.Field, additionalInfo: $"{FeaturesResources.type_space}Foo"); // Check searching for@string too item = (await _aggregator.GetItemsAsync("@string")).Single(); VerifyNavigateToResultItem(item, "string", "[|string|]", MatchKind.Exact, NavigateToItemKind.Field, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPtrField1() { await TestAsync( @"class Foo { int* bar; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); Assert.Empty(await _aggregator.GetItemsAsync("ar")); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPtrField2() { await TestAsync( @"class Foo { int* bar; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("b")).Single(); VerifyNavigateToResultItem(item, "bar", "[|b|]ar", MatchKind.Prefix, NavigateToItemKind.Field); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindConstField() { await TestAsync( @"class Foo { const int bar = 7; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupConstant, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("ba")).Single(); VerifyNavigateToResultItem(item, "bar", "[|ba|]r", MatchKind.Prefix, NavigateToItemKind.Constant); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindIndexer() { var program = @"class Foo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("this")).Single(); VerifyNavigateToResultItem(item, "this", "[|this|][int]", MatchKind.Exact, NavigateToItemKind.Property, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEvent() { var program = "class Foo { public event EventHandler ChangedEventHandler; }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEvent, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("CEH")).Single(); VerifyNavigateToResultItem(item, "ChangedEventHandler", "[|C|]hanged[|E|]vent[|H|]andler", MatchKind.Regular, NavigateToItemKind.Event, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindAutoProperty() { await TestAsync( @"class Foo { int Bar { get; set; } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("B")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|B|]ar", MatchKind.Prefix, NavigateToItemKind.Property, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMethod() { await TestAsync( @"class Foo { void DoSomething(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething()", MatchKind.Regular, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindVerbatimMethod() { await TestAsync( @"class Foo { void @static(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("static")).Single(); VerifyNavigateToResultItem(item, "static", "[|static|]()", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); // Verify if we search for @static too item = (await _aggregator.GetItemsAsync("@static")).Single(); VerifyNavigateToResultItem(item, "static", "[|static|]()", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindParameterizedMethod() { await TestAsync( @"class Foo { void DoSomething(int a, string b) { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething(int, string)", MatchKind.Regular, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindConstructor() { await TestAsync( @"class Foo { public Foo() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Foo", "[|Foo|]()", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindParameterizedConstructor() { await TestAsync( @"class Foo { public Foo(int i) { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Foo", "[|Foo|](int)", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindStaticConstructor() { await TestAsync( @"class Foo { static Foo() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method && t.Name != ".ctor"); VerifyNavigateToResultItem(item, "Foo", "[|Foo|].static Foo()", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethods() { await TestAsync("partial class Foo { partial void Bar(); } partial class Foo { partial void Bar() { Console.Write(\"hello\"); } }", async w => { var expecteditem1 = new NavigateToItem("Bar", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Bar"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethodDefinitionOnly() { await TestAsync( @"partial class Foo { partial void Bar(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethodImplementationOnly() { await TestAsync( @"partial class Foo { partial void Bar() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", MatchKind.Exact, NavigateToItemKind.Method, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindOverriddenMembers() { var program = "class Foo { public virtual string Name { get; set; } } class DogBed : Foo { public override string Name { get { return base.Name; } set {} } }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic); var expecteditem1 = new NavigateToItem("Name", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Name"); VerifyNavigateToResultItems(expecteditems, items); var item = items.ElementAt(0); var itemDisplay = item.DisplayFactory.CreateItemDisplay(item); var unused = itemDisplay.Glyph; Assert.Equal("Name", itemDisplay.Name); Assert.Equal($"{FeaturesResources.type_space}DogBed", itemDisplay.AdditionalInformation); _glyphServiceMock.Verify(); item = items.ElementAt(1); itemDisplay = item.DisplayFactory.CreateItemDisplay(item); unused = itemDisplay.Glyph; Assert.Equal("Name", itemDisplay.Name); Assert.Equal($"{FeaturesResources.type_space}Foo", itemDisplay.AdditionalInformation); _glyphServiceMock.Verify(); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindInterface() { await TestAsync( @"public interface IFoo { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupInterface, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("IF")).Single(); VerifyNavigateToResultItem(item, "IFoo", "[|IF|]oo", MatchKind.Prefix, NavigateToItemKind.Interface); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindDelegateInNamespace() { await TestAsync( @"namespace Foo { delegate void DoStuff(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupDelegate, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("DoStuff")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DoStuff", "[|DoStuff|]", MatchKind.Exact, NavigateToItemKind.Delegate); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindLambdaExpression() { await TestAsync( @"using System; class Foo { Func<int, int> sqr = x => x * x; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("sqr")).Single(); VerifyNavigateToResultItem(item, "sqr", "[|sqr|]", MatchKind.Exact, NavigateToItemKind.Field, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindArray() { await TestAsync( @"class Foo { object[] itemArray; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("itemArray")).Single(); VerifyNavigateToResultItem(item, "itemArray", "[|itemArray|]", MatchKind.Exact, NavigateToItemKind.Field, $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClassAndMethodWithSameName() { await TestAsync( @"class Foo { } class Test { void Foo() { } }", async w => { var expectedItems = new List<NavigateToItem> { new NavigateToItem("Foo", NavigateToItemKind.Method, "csharp", "Foo", null, MatchKind.Exact, true, null), new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", "Foo", null, MatchKind.Exact, true, null) }; var items = await _aggregator.GetItemsAsync("Foo"); VerifyNavigateToResultItems(expectedItems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMethodNestedInGenericTypes() { await TestAsync( @"class A<T> { class B { struct C<U> { void M() { } } } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("M")).Single(); VerifyNavigateToResultItem(item, "M", "[|M|]()", MatchKind.Exact, NavigateToItemKind.Method, additionalInfo: $"{FeaturesResources.type_space}A<T>.B.C<U>"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task OrderingOfConstructorsAndTypes() { await TestAsync( @"class C1 { C1(int i) { } } class C2 { C2(float f) { } static C2() { } }", async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("C1", NavigateToItemKind.Class, "csharp", "C1", null, MatchKind.Prefix, true, null), new NavigateToItem("C1", NavigateToItemKind.Method, "csharp", "C1", null, MatchKind.Prefix, true, null), new NavigateToItem("C2", NavigateToItemKind.Class, "csharp", "C2", null, MatchKind.Prefix, true, null), new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), // this is the static ctor new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), }; var items = (await _aggregator.GetItemsAsync("C")).ToList(); items.Sort(CompareNavigateToItems); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task NavigateToMethodWithNullableParameter() { await TestAsync( @"class C { void M(object? o) { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("M")).Single(); VerifyNavigateToResultItem(item, "M", "[|M|](object?)", MatchKind.Exact, NavigateToItemKind.Method); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task StartStopSanity() { // Verify that multiple calls to start/stop and dispose don't blow up await TestAsync( @"public class Foo { }", async w => { // Do one set of queries Assert.Single((await _aggregator.GetItemsAsync("Foo")).Where(x => x.Kind != "Method")); _provider.StopSearch(); // Do the same query again, make sure nothing was left over Assert.Single((await _aggregator.GetItemsAsync("Foo")).Where(x => x.Kind != "Method")); _provider.StopSearch(); // Dispose the provider _provider.Dispose(); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DescriptionItems() { await TestAsync("public\r\nclass\r\nFoo\r\n{ }", async w => { var item = (await _aggregator.GetItemsAsync("F")).Single(x => x.Kind != "Method"); var itemDisplay = item.DisplayFactory.CreateItemDisplay(item); var descriptionItems = itemDisplay.DescriptionItems; Action<string, string> assertDescription = (label, value) => { var descriptionItem = descriptionItems.Single(i => i.Category.Single().Text == label); Assert.Equal(value, descriptionItem.Details.Single().Text); }; assertDescription("File:", w.Documents.Single().Name); assertDescription("Line:", "3"); // one based line number assertDescription("Project:", "Test"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest1() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_keyword", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem3 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2, expecteditem3 }; var items = await _aggregator.GetItemsAsync("GK"); Assert.Equal(expecteditems.Count(), items.Count()); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest2() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = await _aggregator.GetItemsAsync("GKW"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest3() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = await _aggregator.GetItemsAsync("K W"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest4() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var items = await _aggregator.GetItemsAsync("WKG"); Assert.Empty(items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest5() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("G_K_W")).Single(); VerifyNavigateToResultItem(item, "get_key_word", "[|g|]et[|_k|]ey[|_w|]ord", MatchKind.Regular, NavigateToItemKind.Field); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest6() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Prefix, true, null), new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Prefix, null) }; var items = await _aggregator.GetItemsAsync("get word"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest7() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var items = await _aggregator.GetItemsAsync("GTW"); Assert.Empty(items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TestIndexer1() { var source = @"class C { public int this[int y] { get { } } } class D { void Foo() { var q = new C(); var b = q[4]; } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("this", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null), }; var items = await _aggregator.GetItemsAsync("this"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern1() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; var items = await _aggregator.GetItemsAsync("B.Q"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern2() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { }; var items = await _aggregator.GetItemsAsync("C.Q"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern3() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; var items = await _aggregator.GetItemsAsync("B.B.Q"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern4() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null) }; var items = await _aggregator.GetItemsAsync("Baz.Quux"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern5() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null) }; var items = await _aggregator.GetItemsAsync("F.B.B.Quux"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern6() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { }; var items = await _aggregator.GetItemsAsync("F.F.B.B.Quux"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] [WorkItem(7855, "https://github.com/dotnet/Roslyn/issues/7855")] public async Task DottedPattern7() { var source = "namespace Foo { namespace Bar { class Baz<X,Y,Z> { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; var items = await _aggregator.GetItemsAsync("Baz.Q"); VerifyNavigateToResultItems(expecteditems, items); }); } [WorkItem(1174255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174255")] [WorkItem(8009, "https://github.com/dotnet/roslyn/issues/8009")] [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task NavigateToGeneratedFiles() { using (var workspace = TestWorkspace.Create(@" <Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document FilePath=""File1.cs""> namespace N { public partial class C { public void VisibleMethod() { } } } </Document> <Document FilePath=""File1.g.cs""> namespace N { public partial class C { public void VisibleMethod_Generated() { } } } </Document> </Project> </Workspace> ", exportProvider: s_exportProvider)) { var aggregateListener = AggregateAsynchronousOperationListener.CreateEmptyListener(); _provider = new NavigateToItemProvider( workspace, _glyphServiceMock.Object, aggregateListener, workspace.ExportProvider.GetExportedValues<Lazy<INavigateToHostVersionService, VisualStudioVersionMetadata>>()); _aggregator = new NavigateToTestAggregator(_provider); var items = await _aggregator.GetItemsAsync("VisibleMethod"); var expectedItems = new List<NavigateToItem>() { new NavigateToItem("VisibleMethod", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null), new NavigateToItem("VisibleMethod_Generated", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; // The pattern matcher should match 'VisibleMethod' to both 'VisibleMethod' and 'VisibleMethod_Not', except that // the _Not method is declared in a generated file. VerifyNavigateToResultItems(expectedItems, items); } } [WorkItem(11474, "https://github.com/dotnet/roslyn/pull/11474")] [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindFuzzy1() { await TestAsync( @"class C { public void ToError() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("ToEror")).Single(); VerifyNavigateToResultItem(item, "ToError", "ToError()", MatchKind.Regular, NavigateToItemKind.Method); }); } [WorkItem(18843, "https://github.com/dotnet/roslyn/issues/18843")] [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task Test__arglist() { await TestAsync( @"class C { public void ToError(__arglist) { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("ToError")).Single(); VerifyNavigateToResultItem(item, "ToError", "[|ToError|](__arglist)", MatchKind.Exact, NavigateToItemKind.Method); }); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestAzureSpecialParametersTestClient : ServiceClient<AutoRestAzureSpecialParametersTestClient>, IAutoRestAzureSpecialParametersTestClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The subscription id, which appears in the path, always modeled in /// credentials. The value is always '1234-5678-9012-3456' /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The api version, which appears in the query, the value is always /// '2015-07-01-preview' /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IXMsClientRequestIdOperations. /// </summary> public virtual IXMsClientRequestIdOperations XMsClientRequestId { get; private set; } /// <summary> /// Gets the ISubscriptionInCredentialsOperations. /// </summary> public virtual ISubscriptionInCredentialsOperations SubscriptionInCredentials { get; private set; } /// <summary> /// Gets the ISubscriptionInMethodOperations. /// </summary> public virtual ISubscriptionInMethodOperations SubscriptionInMethod { get; private set; } /// <summary> /// Gets the IApiVersionDefaultOperations. /// </summary> public virtual IApiVersionDefaultOperations ApiVersionDefault { get; private set; } /// <summary> /// Gets the IApiVersionLocalOperations. /// </summary> public virtual IApiVersionLocalOperations ApiVersionLocal { get; private set; } /// <summary> /// Gets the ISkipUrlEncodingOperations. /// </summary> public virtual ISkipUrlEncodingOperations SkipUrlEncoding { get; private set; } /// <summary> /// Gets the IOdataOperations. /// </summary> public virtual IOdataOperations Odata { get; private set; } /// <summary> /// Gets the IHeaderOperations. /// </summary> public virtual IHeaderOperations Header { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestAzureSpecialParametersTestClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestAzureSpecialParametersTestClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestAzureSpecialParametersTestClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestAzureSpecialParametersTestClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestAzureSpecialParametersTestClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestAzureSpecialParametersTestClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestAzureSpecialParametersTestClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestAzureSpecialParametersTestClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { XMsClientRequestId = new XMsClientRequestIdOperations(this); SubscriptionInCredentials = new SubscriptionInCredentialsOperations(this); SubscriptionInMethod = new SubscriptionInMethodOperations(this); ApiVersionDefault = new ApiVersionDefaultOperations(this); ApiVersionLocal = new ApiVersionLocalOperations(this); SkipUrlEncoding = new SkipUrlEncodingOperations(this); Odata = new OdataOperations(this); Header = new HeaderOperations(this); BaseUri = new System.Uri("http://localhost"); ApiVersion = "2015-07-01-preview"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace BuildIt.CognitiveServices { using Microsoft.Rest; public partial class LinguisticsAPI : Microsoft.Rest.ServiceClient<LinguisticsAPI>, ILinguisticsAPI { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Initializes a new instance of the LinguisticsAPI class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public LinguisticsAPI(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the LinguisticsAPI class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public LinguisticsAPI(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the LinguisticsAPI class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public LinguisticsAPI(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the LinguisticsAPI class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public LinguisticsAPI(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new System.Uri("https://westus.api.cognitive.microsoft.com/linguistics/v1.0"); SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); } /// <summary> /// This API returns a list of strings representing which analyzers are /// currently registered. /// </summary> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ListanalyzersWithHttpMessagesAsync(string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("subscriptionKey", subscriptionKey); tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Listanalyzers", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "analyzers").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (subscriptionKey != null) { _queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (ocpApimSubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 429 && (int)_statusCode != 415) { var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Analyze text with specific analyzers. /// </summary> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> AnalyzetextWithHttpMessagesAsync(string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("subscriptionKey", subscriptionKey); tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Analyzetext", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "analyze").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (subscriptionKey != null) { _queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (ocpApimSubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 415 && (int)_statusCode != 429) { var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography.Asn1; using Internal.Cryptography; namespace System.Security.Cryptography { public abstract partial class RSA : AsymmetricAlgorithm { public static new RSA Create(string algName) { return (RSA)CryptoConfig.CreateFromName(algName); } public static RSA Create(int keySizeInBits) { RSA rsa = Create(); try { rsa.KeySize = keySizeInBits; return rsa; } catch { rsa.Dispose(); throw; } } public static RSA Create(RSAParameters parameters) { RSA rsa = Create(); try { rsa.ImportParameters(parameters); return rsa; } catch { rsa.Dispose(); throw; } } public abstract RSAParameters ExportParameters(bool includePrivateParameters); public abstract void ImportParameters(RSAParameters parameters); public virtual byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride(); public virtual byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride(); public virtual byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride(); public virtual bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride(); protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride(); protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride(); public virtual bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { byte[] result = Decrypt(data.ToArray(), padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { byte[] result = Encrypt(data.ToArray(), padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } protected virtual bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { byte[] result; byte[] array = ArrayPool<byte>.Shared.Rent(data.Length); try { data.CopyTo(array); result = HashData(array, 0, data.Length, hashAlgorithm); } finally { Array.Clear(array, 0, data.Length); ArrayPool<byte>.Shared.Return(array); } if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { byte[] result = SignHash(hash.ToArray(), hashAlgorithm, padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => VerifyHash(hash.ToArray(), signature.ToArray(), hashAlgorithm, padding); private static Exception DerivedClassMustOverride() => new NotImplementedException(SR.NotSupported_SubclassOverride); public virtual byte[] DecryptValue(byte[] rgb) => throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop public virtual byte[] EncryptValue(byte[] rgb) => throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) { throw new ArgumentNullException(nameof(data)); } return SignData(data, 0, data.Length, hashAlgorithm, padding); } public virtual byte[] SignData( byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, offset, count, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); } public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); } public virtual bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } if (padding == null) { throw new ArgumentNullException(nameof(padding)); } if (TryHashData(data, destination, hashAlgorithm, out int hashLength) && TrySignHash(destination.Slice(0, hashLength), destination, hashAlgorithm, padding, out bytesWritten)) { return true; } bytesWritten = 0; return false; } public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); return VerifyData(data, 0, data.Length, signature, hashAlgorithm, padding); } public virtual bool VerifyData( byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (signature == null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, offset, count, hashAlgorithm); return VerifyHash(hash, signature, hashAlgorithm, padding); } public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (signature == null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, hashAlgorithm); return VerifyHash(hash, signature, hashAlgorithm, padding); } public virtual bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } if (padding == null) { throw new ArgumentNullException(nameof(padding)); } for (int i = 256; ; i = checked(i * 2)) { int hashLength = 0; byte[] hash = ArrayPool<byte>.Shared.Rent(i); try { if (TryHashData(data, hash, hashAlgorithm, out hashLength)) { return VerifyHash(new ReadOnlySpan<byte>(hash, 0, hashLength), signature, hashAlgorithm, padding); } } finally { Array.Clear(hash, 0, hashLength); ArrayPool<byte>.Shared.Return(hash); } } } public virtual byte[] ExportRSAPrivateKey() { using (AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey()) { return pkcs1PrivateKey.Encode(); } } public virtual bool TryExportRSAPrivateKey(Span<byte> destination, out int bytesWritten) { using (AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey()) { return pkcs1PrivateKey.TryEncode(destination, out bytesWritten); } } public virtual byte[] ExportRSAPublicKey() { using (AsnWriter pkcs1PublicKey = WritePkcs1PublicKey()) { return pkcs1PublicKey.Encode(); } } public virtual bool TryExportRSAPublicKey(Span<byte> destination, out int bytesWritten) { using (AsnWriter pkcs1PublicKey = WritePkcs1PublicKey()) { return pkcs1PublicKey.TryEncode(destination, out bytesWritten); } } public override unsafe bool TryExportSubjectPublicKeyInfo(Span<byte> destination, out int bytesWritten) { // The PKCS1 RSAPublicKey format is just the modulus (KeySize bits) and Exponent (usually 3 bytes), // with each field having up to 7 bytes of overhead and then up to 6 extra bytes of overhead for the // SEQUENCE tag. // // So KeySize / 4 is ideally enough to start. int rentSize = KeySize / 4; while (true) { byte[] rented = ArrayPool<byte>.Shared.Rent(rentSize); rentSize = rented.Length; int pkcs1Size = 0; fixed (byte* rentPtr = rented) { try { if (!TryExportRSAPublicKey(rented, out pkcs1Size)) { rentSize = checked(rentSize * 2); continue; } using (AsnWriter writer = RSAKeyFormatHelper.WriteSubjectPublicKeyInfo(rented.AsSpan(0, pkcs1Size))) { return writer.TryEncode(destination, out bytesWritten); } } finally { CryptographicOperations.ZeroMemory(rented.AsSpan(0, pkcs1Size)); ArrayPool<byte>.Shared.Return(rented); } } } } public override bool TryExportPkcs8PrivateKey(Span<byte> destination, out int bytesWritten) { using (AsnWriter writer = WritePkcs8PrivateKey()) { return writer.TryEncode(destination, out bytesWritten); } } private unsafe AsnWriter WritePkcs8PrivateKey() { // A PKCS1 RSAPrivateKey is the Modulus (KeySize bits), D (~KeySize bits) // P, Q, DP, DQ, InverseQ (all ~KeySize/2 bits) // Each field can have up to 7 bytes of overhead, and then another 9 bytes // of fixed overhead. // So it should fit in 5 * KeySizeInBytes, but Exponent is a wildcard. int rentSize = checked(5 * KeySize / 8); while (true) { byte[] rented = ArrayPool<byte>.Shared.Rent(rentSize); rentSize = rented.Length; int pkcs1Size = 0; fixed (byte* rentPtr = rented) { try { if (!TryExportRSAPrivateKey(rented, out pkcs1Size)) { rentSize = checked(rentSize * 2); continue; } return RSAKeyFormatHelper.WritePkcs8PrivateKey(new ReadOnlySpan<byte>(rented, 0, pkcs1Size)); } finally { CryptographicOperations.ZeroMemory(rented.AsSpan(0, pkcs1Size)); ArrayPool<byte>.Shared.Return(rented); } } } } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); using (AsnWriter pkcs8PrivateKey = WritePkcs8PrivateKey()) using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( password, pkcs8PrivateKey, pbeParameters)) { return writer.TryEncode(destination, out bytesWritten); } } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan<char>.Empty, passwordBytes); using (AsnWriter pkcs8PrivateKey = WritePkcs8PrivateKey()) using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( passwordBytes, pkcs8PrivateKey, pbeParameters)) { return writer.TryEncode(destination, out bytesWritten); } } private AsnWriter WritePkcs1PublicKey() { RSAParameters rsaParameters = ExportParameters(false); return RSAKeyFormatHelper.WritePkcs1PublicKey(rsaParameters); } private unsafe AsnWriter WritePkcs1PrivateKey() { RSAParameters rsaParameters = ExportParameters(true); fixed (byte* dPin = rsaParameters.D) fixed (byte* pPin = rsaParameters.P) fixed (byte* qPin = rsaParameters.Q) fixed (byte* dpPin = rsaParameters.DP) fixed (byte* dqPin = rsaParameters.DQ) fixed (byte* qInvPin = rsaParameters.InverseQ) { try { return RSAKeyFormatHelper.WritePkcs1PrivateKey(rsaParameters); } finally { ClearPrivateParameters(rsaParameters); } } } public override unsafe void ImportSubjectPublicKeyInfo(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { ReadOnlyMemory<byte> pkcs1 = RSAKeyFormatHelper.ReadSubjectPublicKeyInfo( manager.Memory, out int localRead); ImportRSAPublicKey(pkcs1.Span, out _); bytesRead = localRead; } } } public virtual unsafe void ImportRSAPublicKey(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER); ReadOnlyMemory<byte> firstValue = reader.PeekEncodedValue(); int localRead = firstValue.Length; AlgorithmIdentifierAsn ignored = default; RSAKeyFormatHelper.ReadRsaPublicKey(firstValue, ignored, out RSAParameters rsaParameters); ImportParameters(rsaParameters); bytesRead = localRead; } } } public virtual unsafe void ImportRSAPrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER); ReadOnlyMemory<byte> firstValue = reader.PeekEncodedValue(); int localRead = firstValue.Length; AlgorithmIdentifierAsn ignored = default; RSAKeyFormatHelper.FromPkcs1PrivateKey(firstValue, ignored, out RSAParameters rsaParameters); fixed (byte* dPin = rsaParameters.D) fixed (byte* pPin = rsaParameters.P) fixed (byte* qPin = rsaParameters.Q) fixed (byte* dpPin = rsaParameters.DP) fixed (byte* dqPin = rsaParameters.DQ) fixed (byte* qInvPin = rsaParameters.InverseQ) { try { ImportParameters(rsaParameters); } finally { ClearPrivateParameters(rsaParameters); } } bytesRead = localRead; } } } public override unsafe void ImportPkcs8PrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { ReadOnlyMemory<byte> pkcs1 = RSAKeyFormatHelper.ReadPkcs8( manager.Memory, out int localRead); ImportRSAPrivateKey(pkcs1.Span, out _); bytesRead = localRead; } } } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { RSAKeyFormatHelper.ReadEncryptedPkcs8( source, passwordBytes, out int localRead, out RSAParameters ret); fixed (byte* dPin = ret.D) fixed (byte* pPin = ret.P) fixed (byte* qPin = ret.Q) fixed (byte* dpPin = ret.DP) fixed (byte* dqPin = ret.DQ) fixed (byte* qInvPin = ret.InverseQ) { try { ImportParameters(ret); } finally { ClearPrivateParameters(ret); } } bytesRead = localRead; } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { RSAKeyFormatHelper.ReadEncryptedPkcs8( source, password, out int localRead, out RSAParameters ret); fixed (byte* dPin = ret.D) fixed (byte* pPin = ret.P) fixed (byte* qPin = ret.Q) fixed (byte* dpPin = ret.DP) fixed (byte* dqPin = ret.DQ) fixed (byte* qInvPin = ret.InverseQ) { try { ImportParameters(ret); } finally { ClearPrivateParameters(ret); } } bytesRead = localRead; } private static void ClearPrivateParameters(in RSAParameters rsaParameters) { CryptographicOperations.ZeroMemory(rsaParameters.D); CryptographicOperations.ZeroMemory(rsaParameters.P); CryptographicOperations.ZeroMemory(rsaParameters.Q); CryptographicOperations.ZeroMemory(rsaParameters.DP); CryptographicOperations.ZeroMemory(rsaParameters.DQ); CryptographicOperations.ZeroMemory(rsaParameters.InverseQ); } public override string KeyExchangeAlgorithm => "RSA"; public override string SignatureAlgorithm => "RSA"; private static Exception HashAlgorithmNameNullOrEmpty() => new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } }
// QuickGraph Library // // Copyright (c) 2004 Jonathan de Halleux // // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from // the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // QuickGraph Library HomePage: http://www.dotnetwiki.org // Author: Jonathan de Halleux namespace QuickGraph.Web.Controls { using System; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Web.UI.Design; using System.ComponentModel; using System.Web.Caching; using System.Drawing; using QuickGraph.Algorithms; using QuickGraph.Algorithms.Graphviz; using QuickGraph.Representations; using QuickGraph.Providers; using NGraphviz; using NGraphviz.Helpers; /// <summary> /// A Cached Graphviz Web Control /// </summary> /// <remarks> /// <para> /// Only a subset of the Graphviz Ouput are supported: /// <list type="bullet"> /// <item><term>Png</term><description>Png</description></item> /// <item><term>Gif</term><description>Gif</description></item> /// <item><term>Jpeg</term><description>Jpeg</description></item> /// <item><term>Svg</term><description>SVG</description></item> /// <item><term>Svgz</term><description>SVGZ</description></item> /// </list> /// </para> /// <para> /// Clearly, the best choice is SVGZ if your client supports it: it's /// vectorial, compressed and anti-aliased! /// </para> /// </remarks> [Designer(typeof(QuickGraph.Web.Design.GraphvizDesigner))] public class GraphvizControl : Panel, INamingContainer { private TimeSpan m_TimeOut; private GraphvizAlgorithm m_Algo; private String m_RelativePath; private Size m_ImageSize; private String m_CustomCacheKey; /// <summary> /// Default constructor /// </summary> public GraphvizControl() { m_Algo = new GraphvizAlgorithm( new AdjacencyGraph(true) ); RelativePath = ""; m_TimeOut = new TimeSpan(0,0,0,0,0); m_ImageSize = new Size(0,0); m_CustomCacheKey = null; } /// <summary> /// Creates the child controls /// </summary> protected override void CreateChildControls() { Algo.Renderer.TempDir = ServerPath; Controls.Add(new LiteralControl("<table><tr><td>")); // getting cache file name String fileName = CachedImageFileName; if (fileName == null) { // creating image fileName = CachedImageFileName = NewImageFileName; Algo.Write(ServerFileName(fileName)); } String relFileName = RelativeFileName(fileName); // Svg rendering if (Algo.ImageType == GraphvizImageType.Svg) { String embed = String.Format( "<embed src=\"{0}\" pluginspage=\"http://www.adobe.com/svg/viewer/install/\" type=\"image/svg+xml\" {1} />", relFileName, SizeToString() ); Controls.Add(new LiteralControl(embed)); } // Zipped SVG rendering else if (Algo.ImageType == GraphvizImageType.Svgz) { String embed = String.Format( "<embed src=\"{0}\" pluginspage=\"http://www.adobe.com/svg/viewer/install/\" type=\"image/svgz+xml\" {1} />", relFileName, SizeToString() ); Controls.Add(new LiteralControl(embed)); } // Raster image types else { HtmlImage img = new HtmlImage(); Controls.Add(img); img.Src = relFileName; if (m_ImageSize.Width != 0) img.Width = m_ImageSize.Width; if (m_ImageSize.Height != 0) img.Height = m_ImageSize.Height; } // adding info Controls.Add(new LiteralControl("</td></tr><tr><td><font size=-3>")); /* DateTime dt = File.GetCreationTime(ServerPath + '\\' + fileName); Controls.Add(new LiteralControl( String.Format("Graph Creation Time: {0}. Powered by <a href=\"http://www.dotnetwiki.org\">DotNetWiki.org</a>.",dt.ToLocalTime()) ) ); */ Controls.Add(new LiteralControl("</font></td></tr></table>")); } /// <summary> /// Rendering algorithm /// </summary> [Description("Graphviz Algorithm")] public GraphvizAlgorithm Algo { get { return m_Algo; } } /// <summary> /// Rendered image caching time out. 0 disables caching. /// </summary> [Description("Caching timeout of the generated image")] public TimeSpan TimeOut { get { return m_TimeOut; } set { m_TimeOut = value; } } /// <summary> /// Path the temporary files are outputted. Map to server location /// internaly. /// </summary> [Description("Temporary files output path")] public String RelativePath { get { return m_RelativePath; } set { m_RelativePath = value; //Algo.Renderer.TempDir = m_RelativePath; } } /// <summary> /// Image width in pixels. If 0 not used /// </summary> [Description("Output image width")] public int ImageWidth { get { return m_ImageSize.Width; } set { m_ImageSize.Width = value; } } /// <summary> /// Image height in pixels. If 0, not used /// </summary> [Description("Output image height")] public int ImageHeight { get { return m_ImageSize.Height; } set { m_ImageSize.Height = value; } } /// <summary> /// Mapped Server path /// </summary> protected String ServerPath { get { return Context.Server.MapPath(RelativePath); } } /// <summary> /// Maps file name to server path /// </summary> /// <param name="name"></param> /// <returns></returns> protected string ServerFileName(string name) { if (name==null) throw new ArgumentNullException("file name"); return String.Format("{0}\\{1}",ServerPath,name); } /// <summary> /// Maps file name to relative url path /// </summary> /// <param name="name"></param> /// <returns></returns> protected string RelativeFileName(string name) { if (name==null) throw new ArgumentNullException("file name"); if (RelativePath.Length == 0) return name; else return String.Format("{0}\\{1}",RelativePath,name); } /// <summary> /// Resets the cached image /// </summary> public void ResetCache() { Context.Cache.Remove( CacheKey ); } /// <summary> /// A user defined cache key. /// </summary> public String CustomCacheKey { get { return m_CustomCacheKey; } set { ResetCache(); m_CustomCacheKey = value; } } /// <summary> /// Generates a unique cache key /// </summary> protected String CacheKey { get { if (CustomCacheKey != null) return CustomCacheKey; else return "DotControl" + ID; } } /// <summary> /// Provides a new image name /// </summary> protected String NewImageFileName { get { return String.Format("dot_render{0}.{1}", DateTime.Now.ToFileTime(), Algo.ImageType.ToString().ToLower() ); } } /// <summary> /// Returns the last generated file (cached) /// </summary> /// <returns>latest generated file path or null if nothing on cache</returns> protected String CachedImageFileName { get { // getting cache Object o = Context.Cache[CacheKey]; if (o == null) return null; else return (String)o; } set { if (value == null) throw new ArgumentNullException("CachedImageFileName"); Context.Cache.Add( CacheKey, value, null, DateTime.Now + TimeOut, TimeSpan.Zero, CacheItemPriority.Normal, null ); } } /// <summary> /// True if the graph is currently on cache /// </summary> public bool IsCached { get { return CachedImageFileName != null; } } /// <summary> /// Renders image size to Xml Attributes /// </summary> /// <returns>attributes representing the size</returns> internal String SizeToString() { StringWriter sw =new StringWriter(); if (m_ImageSize.Width != 0) sw.Write(" width={0} ",m_ImageSize.Width); if (m_ImageSize.Height != 0) sw.Write(" height={0} ",m_ImageSize.Height); return sw.ToString(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Authorization { using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; /// <summary> /// RoleAssignmentsOperations operations. /// </summary> public partial interface IRoleAssignmentsOperations { /// <summary> /// Gets role assignments for a resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceProviderNamespace'> /// The namespace of the resource provider. /// </param> /// <param name='parentResourcePath'> /// The parent resource identity. /// </param> /// <param name='resourceType'> /// The resource type of the resource. /// </param> /// <param name='resourceName'> /// The name of the resource to get role assignments for. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RoleAssignment>>> ListForResourceWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets role assignments for a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RoleAssignment>>> ListForResourceGroupWithHttpMessagesAsync(string resourceGroupName, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a role assignment. /// </summary> /// <param name='scope'> /// The scope of the role assignment to delete. /// </param> /// <param name='roleAssignmentName'> /// The name of the role assignment to delete. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RoleAssignment>> DeleteWithHttpMessagesAsync(string scope, string roleAssignmentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a role assignment. /// </summary> /// <param name='scope'> /// The scope of the role assignment to create. The scope can be any /// REST resource instance. For example, use /// '/subscriptions/{subscription-id}/' for a subscription, /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' /// for a resource group, and /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' /// for a resource. /// </param> /// <param name='roleAssignmentName'> /// The name of the role assignment to create. It can be any valid GUID. /// </param> /// <param name='properties'> /// Role assignment properties. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RoleAssignment>> CreateWithHttpMessagesAsync(string scope, string roleAssignmentName, RoleAssignmentProperties properties = default(RoleAssignmentProperties), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the specified role assignment. /// </summary> /// <param name='scope'> /// The scope of the role assignment. /// </param> /// <param name='roleAssignmentName'> /// The name of the role assignment to get. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RoleAssignment>> GetWithHttpMessagesAsync(string scope, string roleAssignmentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a role assignment. /// </summary> /// <param name='roleAssignmentId'> /// The ID of the role assignment to delete. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RoleAssignment>> DeleteByIdWithHttpMessagesAsync(string roleAssignmentId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a role assignment by ID. /// </summary> /// <param name='roleAssignmentId'> /// The ID of the role assignment to create. /// </param> /// <param name='properties'> /// Role assignment properties. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RoleAssignment>> CreateByIdWithHttpMessagesAsync(string roleAssignmentId, RoleAssignmentProperties properties = default(RoleAssignmentProperties), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a role assignment by ID. /// </summary> /// <param name='roleAssignmentId'> /// The ID of the role assignment to get. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RoleAssignment>> GetByIdWithHttpMessagesAsync(string roleAssignmentId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all role assignments for the subscription. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RoleAssignment>>> ListWithHttpMessagesAsync(ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets role assignments for a scope. /// </summary> /// <param name='scope'> /// The scope of the role assignments. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RoleAssignment>>> ListForScopeWithHttpMessagesAsync(string scope, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets role assignments for a resource. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RoleAssignment>>> ListForResourceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets role assignments for a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RoleAssignment>>> ListForResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all role assignments for the subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RoleAssignment>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets role assignments for a scope. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RoleAssignment>>> ListForScopeNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Reflection; using FluentNHibernate.Mapping; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Collections; namespace FluentNHibernate.Conventions.Inspections { #pragma warning disable 612,618 public class CollectionInspector : ICollectionInspector, IArrayInspector, IBagInspector, IListInspector, IMapInspector, ISetInspector #pragma warning restore 612,618 { InspectorModelMapper<ICollectionInspector, CollectionMapping> propertyMappings = new InspectorModelMapper<ICollectionInspector, CollectionMapping>(); CollectionMapping mapping; public CollectionInspector(CollectionMapping mapping) { this.mapping = mapping; propertyMappings.Map(x => x.LazyLoad, x => x.Lazy); } public Type EntityType { get { return mapping.ContainingEntityType; } } public string StringIdentifierForModel { get { return mapping.Name; } } Collection ICollectionInspector.Collection { get { return mapping.Collection; } } /// <summary> /// Represents a string identifier for the model instance, used in conventions for a lazy /// shortcut. /// /// e.g. for a ColumnMapping the StringIdentifierForModel would be the Name attribute, /// this allows the user to find any columns with the matching name. /// </summary> public bool IsSet(Member property) { return mapping.IsSpecified(propertyMappings.Get(property)); } public IKeyInspector Key { get { if (mapping.Key == null) return new KeyInspector(new KeyMapping()); return new KeyInspector(mapping.Key); } } public string TableName { get { return mapping.TableName; } } public bool IsMethodAccess { get { return mapping.Member.IsMethod; } } public MemberInfo Member { get { return mapping.Member.MemberInfo; } } public IRelationshipInspector Relationship { get { if (mapping.Relationship is ManyToManyMapping) return new ManyToManyInspector((ManyToManyMapping)mapping.Relationship); return new OneToManyInspector((OneToManyMapping)mapping.Relationship); } } public Cascade Cascade { get { return Cascade.FromString(mapping.Cascade); } } public Fetch Fetch { get { return Fetch.FromString(mapping.Fetch); } } public bool OptimisticLock { get { return mapping.OptimisticLock; } } public bool Generic { get { return mapping.Generic; } } public bool Inverse { get { return mapping.Inverse; } } public Access Access { get { return Access.FromString(mapping.Access); } } public int BatchSize { get { return mapping.BatchSize; } } public ICacheInspector Cache { get { if (mapping.Cache == null) return new CacheInspector(new CacheMapping()); return new CacheInspector(mapping.Cache); } } public string Check { get { return mapping.Check; } } public Type ChildType { get { return mapping.ChildType; } } public TypeReference CollectionType { get { return mapping.CollectionType; } } public ICompositeElementInspector CompositeElement { get { if (mapping.CompositeElement == null) return new CompositeElementInspector(new CompositeElementMapping()); return new CompositeElementInspector(mapping.CompositeElement); } } public IElementInspector Element { get { if (mapping.Element == null) return new ElementInspector(new ElementMapping()); return new ElementInspector(mapping.Element); } } public Lazy LazyLoad { get { return mapping.Lazy; } } public string Name { get { return mapping.Name; } } public TypeReference Persister { get { return mapping.Persister; } } public string Schema { get { return mapping.Schema; } } public string Where { get { return mapping.Where; } } public string OrderBy { get { return mapping.OrderBy; } } public string Sort { get { return mapping.Sort; } } public IIndexInspectorBase Index { get { if (mapping.Index == null) return new IndexInspector(new IndexMapping()); if (mapping.Index is IndexMapping) return new IndexInspector(mapping.Index as IndexMapping); if (mapping.Index is IndexManyToManyMapping) return new IndexManyToManyInspector(mapping.Index as IndexManyToManyMapping); throw new InvalidOperationException("This IIndexMapping is not a valid type for inspecting"); } } public virtual void ExtraLazyLoad() { // TODO: Fix this... // I'm having trouble understanding the relationship between CollectionInspector, CollectionInstance, // and their derivative types. I'm sure adding this method on here is not the right way to do this, but // I have to fulfill the ICollectionInspector.ExtraLazyLoad() signature or conventions can't use it. throw new NotImplementedException(); } } }
// *********************************************************************** // Copyright (c) 2007-2016 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.IO; using System.Text; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Execution { /// <summary> /// EventListenerTextWriter sends text output to the currently active /// ITestEventListener in the form of a TestOutput object. If no event /// listener is active in the context, or if there is no context, /// the output is forwarded to the supplied default writer. /// </summary> public class EventListenerTextWriter : TextWriter { private TextWriter _defaultWriter; private string _streamName; /// <summary> /// Construct an EventListenerTextWriter /// </summary> /// <param name="streamName">The name of the stream to use for events</param> /// <param name="defaultWriter">The default writer to use if no listener is available</param> public EventListenerTextWriter( string streamName, TextWriter defaultWriter ) { _streamName = streamName; _defaultWriter = defaultWriter; } /// <summary> /// Get the Encoding for this TextWriter /// </summary> override public System.Text.Encoding Encoding { #if NETSTANDARD1_3 || NETSTANDARD1_6 get { return Encoding.UTF8; } #else get { return Encoding.Default; } #endif } private bool TrySendToListener(string text) { var context = TestExecutionContext.CurrentContext; if (context == null || context.Listener == null) return false; string testName = context.CurrentTest != null ? context.CurrentTest.FullName : null; context.Listener.TestOutput(new TestOutput(text, _streamName, testName)); return true; } private bool TrySendLineToListener(string text) { return TrySendToListener(text + Environment.NewLine); } #region Write/WriteLine Methods // NB: We explicitly implement each of the Write and WriteLine methods so that // we are not dependent on the implementation of the TextWriter base class. // // For example, ideally, calling WriteLine(char[]) will send the text once, // however, the base implementation will send one character at a time. /// <summary> /// Write formatted string /// </summary> public override void Write(string format, params object[] arg) { if (!TrySendToListener(String.Format(FormatProvider, format, arg))) _defaultWriter.Write(format, arg); } /// <summary> /// Write formatted string /// </summary> public override void Write(string format, object arg0, object arg1, object arg2) { if (!TrySendToListener(String.Format(FormatProvider, format, arg0, arg1, arg2))) _defaultWriter.Write(format, arg0, arg1, arg2); } /// <summary> /// Write formatted string /// </summary> public override void Write(string format, object arg0) { if (!TrySendToListener(String.Format(FormatProvider, format, arg0))) _defaultWriter.Write(format, arg0); } /// <summary> /// Write an object /// </summary> public override void Write(object value) { if (value != null) { IFormattable f = value as IFormattable; if (f != null) { if (!TrySendToListener(f.ToString(null, FormatProvider))) _defaultWriter.Write(value); } else { if (!TrySendToListener(value.ToString())) _defaultWriter.Write(value); } } else { _defaultWriter.Write(value); } } /// <summary> /// Write a string /// </summary> public override void Write(string value) { if (!TrySendToListener(value)) _defaultWriter.Write(value); } /// <summary> /// Write a decimal /// </summary> public override void Write(decimal value) { if (!TrySendToListener(value.ToString(FormatProvider))) _defaultWriter.Write(value); } /// <summary> /// Write a double /// </summary> public override void Write(double value) { if (!TrySendToListener(value.ToString(FormatProvider))) _defaultWriter.Write(value); } /// <summary> /// Write formatted string /// </summary> public override void Write(string format, object arg0, object arg1) { if (!TrySendToListener(String.Format(FormatProvider, format, arg0, arg1))) _defaultWriter.Write(format, arg0, arg1); } /// <summary> /// Write a ulong /// </summary> [CLSCompliant(false)] public override void Write(ulong value) { if (!TrySendToListener(value.ToString(FormatProvider))) _defaultWriter.Write(value); } /// <summary> /// Write a long /// </summary> public override void Write(long value) { if (!TrySendToListener(value.ToString(FormatProvider))) _defaultWriter.Write(value); } /// <summary> /// Write a uint /// </summary> [CLSCompliant(false)] public override void Write(uint value) { if (!TrySendToListener(value.ToString(FormatProvider))) _defaultWriter.Write(value); } /// <summary> /// Write an int /// </summary> public override void Write(int value) { if (!TrySendToListener(value.ToString(FormatProvider))) _defaultWriter.Write(value); } /// <summary> /// Write a char /// </summary> public override void Write(char value) { if (!TrySendToListener(value.ToString())) _defaultWriter.Write(value); } /// <summary> /// Write a boolean /// </summary> public override void Write(bool value) { if (!TrySendToListener(value ? Boolean.TrueString : Boolean.FalseString)) _defaultWriter.Write(value); } /// <summary> /// Write chars /// </summary> public override void Write(char[] buffer, int index, int count) { if (!TrySendToListener(new string(buffer, index, count))) _defaultWriter.Write(buffer, index, count); } /// <summary> /// Write chars /// </summary> public override void Write(char[] buffer) { if (!TrySendToListener(new string(buffer))) _defaultWriter.Write(buffer); } /// <summary> /// Write a float /// </summary> public override void Write(float value) { if (!TrySendToListener(value.ToString(FormatProvider))) _defaultWriter.Write(value); } /// <summary> /// Write a string with newline /// </summary> public override void WriteLine(string value) { if (!TrySendLineToListener(value)) _defaultWriter.WriteLine(value); } /// <summary> /// Write an object with newline /// </summary> public override void WriteLine(object value) { if (value == null) { if (!TrySendLineToListener(string.Empty)) _defaultWriter.WriteLine(value); } else { IFormattable f = value as IFormattable; if (f != null) { if (!TrySendLineToListener(f.ToString(null, FormatProvider))) _defaultWriter.WriteLine(value); } else { if (!TrySendLineToListener(value.ToString())) _defaultWriter.WriteLine(value); } } } /// <summary> /// Write formatted string with newline /// </summary> public override void WriteLine(string format, params object[] arg) { if (!TrySendLineToListener(String.Format(FormatProvider, format, arg))) _defaultWriter.WriteLine(format, arg); } /// <summary> /// Write formatted string with newline /// </summary> public override void WriteLine(string format, object arg0, object arg1) { if (!TrySendLineToListener(String.Format(FormatProvider, format, arg0, arg1))) _defaultWriter.WriteLine(format, arg0, arg1); } /// <summary> /// Write formatted string with newline /// </summary> public override void WriteLine(string format, object arg0, object arg1, object arg2) { if (!TrySendLineToListener(String.Format(FormatProvider, format, arg0, arg1, arg2))) _defaultWriter.WriteLine(format, arg0, arg1, arg2); } /// <summary> /// Write a decimal with newline /// </summary> public override void WriteLine(decimal value) { if (!TrySendLineToListener(value.ToString(FormatProvider))) _defaultWriter.WriteLine(value); } /// <summary> /// Write a formatted string with newline /// </summary> public override void WriteLine(string format, object arg0) { if (!TrySendLineToListener(String.Format(FormatProvider, format, arg0))) _defaultWriter.WriteLine(format, arg0); } /// <summary> /// Write a double with newline /// </summary> public override void WriteLine(double value) { if (!TrySendLineToListener(value.ToString(FormatProvider))) _defaultWriter.WriteLine(value); } /// <summary> /// Write a uint with newline /// </summary> [CLSCompliant(false)] public override void WriteLine(uint value) { if (!TrySendLineToListener(value.ToString(FormatProvider))) _defaultWriter.WriteLine(value); } /// <summary> /// Write a ulong with newline /// </summary> [CLSCompliant(false)] public override void WriteLine(ulong value) { if (!TrySendLineToListener(value.ToString(FormatProvider))) _defaultWriter.WriteLine(value); } /// <summary> /// Write a long with newline /// </summary> public override void WriteLine(long value) { if (!TrySendLineToListener(value.ToString(FormatProvider))) _defaultWriter.WriteLine(value); } /// <summary> /// Write an int with newline /// </summary> public override void WriteLine(int value) { if (!TrySendLineToListener(value.ToString(FormatProvider))) _defaultWriter.WriteLine(value); } /// <summary> /// Write a bool with newline /// </summary> public override void WriteLine(bool value) { if (!TrySendLineToListener(value ? Boolean.TrueString : Boolean.FalseString)) _defaultWriter.WriteLine(value); } /// <summary> /// Write chars with newline /// </summary> public override void WriteLine(char[] buffer, int index, int count) { if (!TrySendLineToListener(new string(buffer, index, count))) _defaultWriter.WriteLine(buffer, index, count); } /// <summary> /// Write chars with newline /// </summary> public override void WriteLine(char[] buffer) { if (!TrySendLineToListener(new string(buffer))) _defaultWriter.WriteLine(buffer); } /// <summary> /// Write a char with newline /// </summary> public override void WriteLine(char value) { if (!TrySendLineToListener(value.ToString())) _defaultWriter.WriteLine(value); } /// <summary> /// Write a float with newline /// </summary> public override void WriteLine(float value) { if (!TrySendLineToListener(value.ToString(FormatProvider))) _defaultWriter.WriteLine(value); } /// <summary> /// Write newline /// </summary> public override void WriteLine() { if (!TrySendLineToListener(string.Empty)) _defaultWriter.WriteLine(); } #endregion } }