context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** Class: BitConverter ** ** ** Purpose: Allows developers to view the base data types as ** an arbitrary array of bits. ** ** ===========================================================*/ using System; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; using System.Security; namespace System { // The BitConverter class contains methods for // converting an array of bytes to one of the base data // types, as well as for converting a base data type to an // array of bytes. // // Only statics, does not need to be marked with the serializable attribute public static class BitConverter { // This field indicates the "endianess" of the architecture. // The value is set to true if the architecture is // little endian; false if it is big endian. #if BIGENDIAN public static readonly bool IsLittleEndian /* = false */; #else public static readonly bool IsLittleEndian = true; #endif // Converts a byte into an array of bytes with length one. public static byte[] GetBytes(bool value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 1); byte[] r = new byte[1]; r[0] = (value ? (byte)1 : (byte)0); return r; } // Converts a char into an array of bytes with length two. public static byte[] GetBytes(char value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts a short into an array of bytes with length // two. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(short value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); byte[] bytes = new byte[2]; fixed (byte* b = bytes) *((short*)b) = value; return bytes; } // Converts an int into an array of bytes with length // four. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(int value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); byte[] bytes = new byte[4]; fixed (byte* b = bytes) *((int*)b) = value; return bytes; } // Converts a long into an array of bytes with length // eight. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(long value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); byte[] bytes = new byte[8]; fixed (byte* b = bytes) *((long*)b) = value; return bytes; } // Converts an ushort into an array of bytes with // length two. [CLSCompliant(false)] public static byte[] GetBytes(ushort value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts an uint into an array of bytes with // length four. [CLSCompliant(false)] public static byte[] GetBytes(uint value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes((int)value); } // Converts an unsigned long into an array of bytes with // length eight. [CLSCompliant(false)] public static byte[] GetBytes(ulong value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes((long)value); } // Converts a float into an array of bytes with length // four. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(float value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes(*(int*)&value); } // Converts a double into an array of bytes with length // eight. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(double value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes(*(long*)&value); } // Converts an array of bytes into a char. public static char ToChar(byte[] value, int startIndex) { if (value == null) { throw new ArgumentNullException("value"); } if ((uint)startIndex >= value.Length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (startIndex > value.Length - 2) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); return (char)ToInt16(value, startIndex); } // Converts an array of bytes into a short. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe short ToInt16(byte[] value, int startIndex) { if (value == null) { throw new ArgumentNullException("value"); } if ((uint)startIndex >= value.Length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (startIndex > value.Length - 2) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 2 == 0) { // data is aligned return *((short*)pbyte); } else { if (IsLittleEndian) { return (short)((*pbyte) | (*(pbyte + 1) << 8)); } else { return (short)((*pbyte << 8) | (*(pbyte + 1))); } } } } // Converts an array of bytes into an int. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe int ToInt32(byte[] value, int startIndex) { if (value == null) { throw new ArgumentNullException("value"); } if ((uint)startIndex >= value.Length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (startIndex > value.Length - 4) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 4 == 0) { // data is aligned return *((int*)pbyte); } else { if (IsLittleEndian) { return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); } else { return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); } } } } // Converts an array of bytes into a long. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe long ToInt64(byte[] value, int startIndex) { if (value == null) { throw new ArgumentNullException("value"); } if ((uint)startIndex >= value.Length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (startIndex > value.Length - 8) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 8 == 0) { // data is aligned return *((long*)pbyte); } else { if (IsLittleEndian) { int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24); return (uint)i1 | ((long)i2 << 32); } else { int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7)); return (uint)i2 | ((long)i1 << 32); } } } } // Converts an array of bytes into an ushort. // [CLSCompliant(false)] public static ushort ToUInt16(byte[] value, int startIndex) { if (value == null) throw new ArgumentNullException("value"); if ((uint)startIndex >= value.Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); if (startIndex > value.Length - 2) throw new ArgumentOutOfRangeException(SR.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (ushort)ToInt16(value, startIndex); } // Converts an array of bytes into an uint. // [CLSCompliant(false)] public static uint ToUInt32(byte[] value, int startIndex) { if (value == null) throw new ArgumentNullException("value"); if ((uint)startIndex >= value.Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); if (startIndex > value.Length - 4) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (uint)ToInt32(value, startIndex); } // Converts an array of bytes into an unsigned long. // [CLSCompliant(false)] public static ulong ToUInt64(byte[] value, int startIndex) { if (value == null) throw new ArgumentNullException("value"); if ((uint)startIndex >= value.Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); if (startIndex > value.Length - 8) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (ulong)ToInt64(value, startIndex); } // Converts an array of bytes into a float. [System.Security.SecuritySafeCritical] // auto-generated unsafe public static float ToSingle(byte[] value, int startIndex) { if (value == null) throw new ArgumentNullException("value"); if ((uint)startIndex >= value.Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); if (startIndex > value.Length - 4) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); int val = ToInt32(value, startIndex); return *(float*)&val; } // Converts an array of bytes into a double. [System.Security.SecuritySafeCritical] // auto-generated unsafe public static double ToDouble(byte[] value, int startIndex) { if (value == null) throw new ArgumentNullException("value"); if ((uint)startIndex >= value.Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); if (startIndex > value.Length - 8) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); long val = ToInt64(value, startIndex); return *(double*)&val; } private static char GetHexValue(int i) { Contract.Assert(i >= 0 && i < 16, "i is out of range."); if (i < 10) { return (char)(i + '0'); } return (char)(i - 10 + 'A'); } // Converts an array of bytes into a String. public static String ToString(byte[] value, int startIndex, int length) { if (value == null) { throw new ArgumentNullException("byteArray"); } if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) { // Don't throw for a 0 length array. throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_GenericPositive); } if (startIndex > value.Length - length) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); if (length == 0) { return string.Empty; } if (length > (Int32.MaxValue / 3)) { // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB throw new ArgumentOutOfRangeException("length", SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (Int32.MaxValue / 3))); } int chArrayLength = length * 3; char[] chArray = new char[chArrayLength]; int i = 0; int index = startIndex; for (i = 0; i < chArrayLength; i += 3) { byte b = value[index++]; chArray[i] = GetHexValue(b / 16); chArray[i + 1] = GetHexValue(b % 16); chArray[i + 2] = '-'; } // We don't need the last '-' character return new String(chArray, 0, chArray.Length - 1); } // Converts an array of bytes into a String. public static String ToString(byte[] value) { if (value == null) throw new ArgumentNullException("value"); Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); return ToString(value, 0, value.Length); } // Converts an array of bytes into a String. public static String ToString(byte[] value, int startIndex) { if (value == null) throw new ArgumentNullException("value"); Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); return ToString(value, startIndex, value.Length - startIndex); } /*==================================ToBoolean=================================== **Action: Convert an array of bytes to a boolean value. We treat this array ** as if the first 4 bytes were an Int4 an operate on this value. **Returns: True if the Int4 value of the first 4 bytes is non-zero. **Arguments: value -- The byte array ** startIndex -- The position within the array. **Exceptions: See ToInt4. ==============================================================================*/ // Converts an array of bytes into a boolean. public static bool ToBoolean(byte[] value, int startIndex) { if (value == null) throw new ArgumentNullException("value"); if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_NeedNonNegNum); if (startIndex > value.Length - 1) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); return (value[startIndex] == 0) ? false : true; } [SecuritySafeCritical] public static unsafe long DoubleToInt64Bits(double value) { // If we're on a big endian machine, what should this method do? You could argue for // either big endian or little endian, depending on whether you are writing to a file that // should be used by other programs on that processor, or for compatibility across multiple // formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile. // If we ever run on big endian machines, produce two versions where endianness is specified. Contract.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec."); return *((long*)&value); } [SecuritySafeCritical] public static unsafe double Int64BitsToDouble(long value) { // If we're on a big endian machine, what should this method do? You could argue for // either big endian or little endian, depending on whether you are writing to a file that // should be used by other programs on that processor, or for compatibility across multiple // formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile. // If we ever run on big endian machines, produce two versions where endianness is specified. Contract.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec."); return *((double*)&value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace System.Data.SqlClient { public sealed partial class SqlConnection : DbConnection { private static readonly Task s_connectionClosedTask = Task.FromException(ADP.ClosedConnectionError()); private bool _AsyncCommandInProgress; // SQLStatistics support internal SqlStatistics _statistics; private bool _collectstats; private bool _fireInfoMessageEventOnUserErrors; // False by default // root task associated with current async invocation private Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion; private string _connectionString; private int _connectRetryCount; // connection resiliency internal Task _currentReconnectionTask; private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections private Guid _originalConnectionId = Guid.Empty; private CancellationTokenSource _reconnectionCancellationSource; internal SessionData _recoverySessionData; internal bool _supressStateChangeForReconnection; private int _reconnectCount; // diagnostics listener private readonly static DiagnosticListener s_diagnosticListener = new DiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName); // Transient Fault handling flag. This is needed to convey to the downstream mechanism of connection establishment, if Transient Fault handling should be used or not // The downstream handling of Connection open is the same for idle connection resiliency. Currently we want to apply transient fault handling only to the connections opened // using SqlConnection.Open() method. internal bool _applyTransientFaultHandling = false; public SqlConnection(string connectionString) : this() { ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available CacheConnectionStringProperties(); } // This method will be called once connection string is set or changed. private void CacheConnectionStringProperties() { SqlConnectionString connString = ConnectionOptions as SqlConnectionString; if (connString != null) { _connectRetryCount = connString.ConnectRetryCount; } } // // PUBLIC PROPERTIES // // used to start/stop collection of statistics data and do verify the current state // // devnote: start/stop should not performed using a property since it requires execution of code // // start statistics // set the internal flag (_statisticsEnabled) to true. // Create a new SqlStatistics object if not already there. // connect the parser to the object. // if there is no parser at this time we need to connect it after creation. // public bool StatisticsEnabled { get { return (_collectstats); } set { { if (value) { // start if (ConnectionState.Open == State) { if (null == _statistics) { _statistics = new SqlStatistics(); ADP.TimerCurrent(out _statistics._openTimestamp); } // set statistics on the parser // update timestamp; Debug.Assert(Parser != null, "Where's the parser?"); Parser.Statistics = _statistics; } } else { // stop if (null != _statistics) { if (ConnectionState.Open == State) { // remove statistics from parser // update timestamp; TdsParser parser = Parser; Debug.Assert(parser != null, "Where's the parser?"); parser.Statistics = null; ADP.TimerCurrent(out _statistics._closeTimestamp); } } } _collectstats = value; } } } internal bool AsyncCommandInProgress { get { return (_AsyncCommandInProgress); } set { _AsyncCommandInProgress = value; } } internal SqlConnectionString.TypeSystem TypeSystem { get { return ((SqlConnectionString)ConnectionOptions).TypeSystemVersion; } } internal int ConnectRetryInterval { get { return ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval; } } override public string ConnectionString { get { return ConnectionString_Get(); } set { ConnectionString_Set(new DbConnectionPoolKey(value)); _connectionString = value; // Change _connectionString value only after value is validated CacheConnectionStringProperties(); } } override public int ConnectionTimeout { get { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout); } } override public string Database { // if the connection is open, we need to ask the inner connection what it's // current catalog is because it may have gotten changed, otherwise we can // just return what the connection string had. get { SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; if (null != innerConnection) { result = innerConnection.CurrentDatabase; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog); } return result; } } override public string DataSource { get { SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; if (null != innerConnection) { result = innerConnection.CurrentDataSource; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source); } return result; } } public int PacketSize { // if the connection is open, we need to ask the inner connection what it's // current packet size is because it may have gotten changed, otherwise we // can just return what the connection string had. get { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); int result; if (null != innerConnection) { result = innerConnection.PacketSize; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size); } return result; } } public Guid ClientConnectionId { get { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null != innerConnection) { return innerConnection.ClientConnectionId; } else { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return _originalConnectionId; } return Guid.Empty; } } } override public string ServerVersion { get { return GetOpenTdsConnection().ServerVersion; } } override public ConnectionState State { get { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return ConnectionState.Open; } return InnerConnection.State; } } internal SqlStatistics Statistics { get { return _statistics; } } public string WorkstationId { get { // If not supplied by the user, the default value is the MachineName // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; string result = ((null != constr) ? constr.WorkstationId : string.Empty); return result; } } // SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication // // PUBLIC EVENTS // public event SqlInfoMessageEventHandler InfoMessage; public bool FireInfoMessageEventOnUserErrors { get { return _fireInfoMessageEventOnUserErrors; } set { _fireInfoMessageEventOnUserErrors = value; } } // Approx. number of times that the internal connection has been reconnected internal int ReconnectCount { get { return _reconnectCount; } } internal bool ForceNewConnection { get; set; } protected override void OnStateChange(StateChangeEventArgs stateChange) { if (!_supressStateChangeForReconnection) { base.OnStateChange(stateChange); } } // // PUBLIC METHODS // new public SqlTransaction BeginTransaction() { // this is just a delegate. The actual method tracks executiontime return BeginTransaction(IsolationLevel.Unspecified, null); } new public SqlTransaction BeginTransaction(IsolationLevel iso) { // this is just a delegate. The actual method tracks executiontime return BeginTransaction(iso, null); } public SqlTransaction BeginTransaction(string transactionName) { // Use transaction names only on the outermost pair of nested // BEGIN...COMMIT or BEGIN...ROLLBACK statements. Transaction names // are ignored for nested BEGIN's. The only way to rollback a nested // transaction is to have a save point from a SAVE TRANSACTION call. return BeginTransaction(IsolationLevel.Unspecified, transactionName); } override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { DbTransaction transaction = BeginTransaction(isolationLevel); // InnerConnection doesn't maintain a ref on the outer connection (this) and // subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction // is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable // until the completion of BeginTransaction with KeepAlive GC.KeepAlive(this); return transaction; } public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName) { WaitForPendingReconnection(); SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); SqlTransaction transaction; bool isFirstAttempt = true; do { transaction = GetOpenTdsConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt"); isFirstAttempt = false; } while (transaction.InternalTransaction.ConnectionHasBeenRestored); // The GetOpenConnection line above doesn't keep a ref on the outer connection (this), // and it could be collected before the inner connection can hook it to the transaction, resulting in // a transaction with a null connection property. Use GC.KeepAlive to ensure this doesn't happen. GC.KeepAlive(this); return transaction; } finally { SqlStatistics.StopTimer(statistics); } } override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); try { statistics = SqlStatistics.StartTimer(Statistics); InnerConnection.ChangeDatabase(database); } finally { SqlStatistics.StopTimer(statistics); } } static public void ClearAllPools() { SqlConnectionFactory.SingletonInstance.ClearAllPools(); } static public void ClearPool(SqlConnection connection) { ADP.CheckArgumentNull(connection, nameof(connection)); DbConnectionOptions connectionOptions = connection.UserConnectionOptions; if (null != connectionOptions) { SqlConnectionFactory.SingletonInstance.ClearPool(connection); } } private void CloseInnerConnection() { // CloseConnection() now handles the lock // The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and // the command will no longer be cancelable. It might be desirable to be able to cancel the close operation, but this is // outside of the scope of Whidbey RTM. See (SqlCommand::Cancel) for other lock. InnerConnection.CloseConnection(this, ConnectionFactory); } override public void Close() { ConnectionState previousState = State; Guid operationId; Guid clientConnectionId; // during the call to Dispose() there is a redundant call to // Close(). because of this, the second time Close() is invoked the // connection is already in a closed state. this doesn't seem to be a // problem except for logging, as we'll get duplicate Before/After/Error // log entries if (previousState != ConnectionState.Closed) { operationId = s_diagnosticListener.WriteConnectionCloseBefore(this); // we want to cache the ClientConnectionId for After/Error logging, as when the connection // is closed then we will lose this identifier // // note: caching this is only for diagnostics logging purposes clientConnectionId = ClientConnectionId; } SqlStatistics statistics = null; Exception e = null; try { statistics = SqlStatistics.StartTimer(Statistics); Task reconnectTask = Interlocked.Exchange(ref _currentReconnectionTask, s_connectionClosedTask); if (reconnectTask != null && !reconnectTask.IsCompleted) { CancellationTokenSource cts = _reconnectionCancellationSource; if (cts != null) { cts.Cancel(); } AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection if (State != ConnectionState.Open) {// if we cancelled before the connection was opened OnStateChange(DbConnectionInternal.StateChangeClosed); } } CancelOpenAndWait(); CloseInnerConnection(); GC.SuppressFinalize(this); if (null != Statistics) { ADP.TimerCurrent(out _statistics._closeTimestamp); } } catch (Exception ex) { e = ex; throw; } finally { SqlStatistics.StopTimer(statistics); // we only want to log this if the previous state of the // connection is open, as that's the valid use-case if (previousState != ConnectionState.Closed) { if (e != null) { s_diagnosticListener.WriteConnectionCloseError(operationId, clientConnectionId, this, e); } else { s_diagnosticListener.WriteConnectionCloseAfter(operationId, clientConnectionId, this); } } } } new public SqlCommand CreateCommand() { return new SqlCommand(null, this); } private void DisposeMe(bool disposing) { if (!disposing) { // For non-pooled connections we need to make sure that if the SqlConnection was not closed, // then we release the GCHandle on the stateObject to allow it to be GCed // For pooled connections, we will rely on the pool reclaiming the connection var innerConnection = (InnerConnection as SqlInternalConnectionTds); if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling)) { var parser = innerConnection.Parser; if ((parser != null) && (parser._physicalStateObj != null)) { parser._physicalStateObj.DecrementPendingCallbacks(); } } } } override public void Open() { Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this); PrepareStatisticsForNewConnection(); SqlStatistics statistics = null; Exception e = null; try { statistics = SqlStatistics.StartTimer(Statistics); TaskCompletionSource<DbConnectionInternal> completionSource = null; if (!TryOpen(isAsync: false, completionSource: ref completionSource)) { throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending); } } catch (Exception ex) { e = ex; throw; } finally { SqlStatistics.StopTimer(statistics); if (e != null) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, e); } else { s_diagnosticListener.WriteConnectionOpenAfter(operationId, this); } } } internal void RegisterWaitingForReconnect(Task waitingTask) { if (((SqlConnectionString)ConnectionOptions).MARS) { return; } Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null); if (_asyncWaitingForReconnection != waitingTask) { // somebody else managed to register throw SQL.MARSUnspportedOnConnection(); } } private async Task ReconnectAsync(int timeout) { try { long commandTimeoutExpiration = 0; if (timeout > 0) { commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout); } CancellationTokenSource cts = new CancellationTokenSource(); _reconnectionCancellationSource = cts; CancellationToken ctoken = cts.Token; int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string for (int attempt = 0; attempt < retryCount; attempt++) { if (ctoken.IsCancellationRequested) { return; } try { try { ForceNewConnection = true; await OpenAsync(ctoken).ConfigureAwait(false); // On success, increment the reconnect count - we don't really care if it rolls over since it is approx. _reconnectCount = unchecked(_reconnectCount + 1); #if DEBUG Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !"); #endif } finally { ForceNewConnection = false; } return; } catch (SqlException e) { if (attempt == retryCount - 1) { throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) { throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId); } } await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false); } } finally { _recoverySessionData = null; _supressStateChangeForReconnection = false; } Debug.Assert(false, "Should not reach this point"); } internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) { Task runningReconnect = _currentReconnectionTask; // This loop in the end will return not completed reconnect task or null while (runningReconnect != null && runningReconnect.IsCompleted) { // clean current reconnect task (if it is the same one we checked Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect); // make sure nobody started new task (if which case we did not clean it) runningReconnect = _currentReconnectionTask; } if (runningReconnect == null) { if (_connectRetryCount > 0) { SqlInternalConnectionTds tdsConn = GetOpenTdsConnection(); if (tdsConn._sessionRecoveryAcknowledged) { TdsParser tdsParser = tdsConn.Parser; if (!tdsParser._physicalStateObj.ValidateSNIConnection()) { if ((tdsParser._sessionPool != null) && (tdsParser._sessionPool.ActiveSessionsCount > 0)) { // >1 MARS session beforeDisconnect?.Invoke(); OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null); } SessionData cData = tdsConn.CurrentSessionData; cData.AssertUnrecoverableStateCountIsCorrect(); if (cData._unrecoverableStatesCount == 0) { TaskCompletionSource<object> reconnectCompletionSource = new TaskCompletionSource<object>(); runningReconnect = Interlocked.CompareExchange(ref _currentReconnectionTask, reconnectCompletionSource.Task, null); if (runningReconnect == null) { if (cData._unrecoverableStatesCount == 0) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; _recoverySessionData = cData; beforeDisconnect?.Invoke(); try { _supressStateChangeForReconnection = true; tdsConn.DoomThisConnection(); } catch (SqlException) { } Task.Run(() => ReconnectAsync(timeout).ContinueWith(t => { if (t.IsFaulted) { reconnectCompletionSource.SetException(t.Exception); } else if (t.IsCanceled) { reconnectCompletionSource.SetCanceled(); } else { reconnectCompletionSource.SetResult(null); } })); runningReconnect = reconnectCompletionSource.Task; } } else { beforeDisconnect?.Invoke(); } } else { beforeDisconnect?.Invoke(); OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null); } } // ValidateSNIConnection } // sessionRecoverySupported } // connectRetryCount>0 } else { // runningReconnect = null beforeDisconnect?.Invoke(); } return runningReconnect; } // this is straightforward, but expensive method to do connection resiliency - it take locks and all preparations as for TDS request partial void RepairInnerConnection() { WaitForPendingReconnection(); if (_connectRetryCount == 0) { return; } SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds; if (tdsConn != null) { tdsConn.ValidateConnectionForExecute(null); tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this); } } private void WaitForPendingReconnection() { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); } } private void CancelOpenAndWait() { // copy from member to avoid changes by background thread var completion = _currentCompletion; if (completion != null) { completion.Item1.TrySetCanceled(); ((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne(); } } public override Task OpenAsync(CancellationToken cancellationToken) { Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this); PrepareStatisticsForNewConnection(); SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); if (cancellationToken.IsCancellationRequested) { s_diagnosticListener.WriteConnectionOpenAfter(operationId, this); return Task.FromCanceled(cancellationToken); } bool completed; TaskCompletionSource<DbConnectionInternal> completion = null; try { completed = TryOpen(isAsync: true, completionSource: ref completion); } catch (Exception e) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, e); return Task.FromException(e); } if (!completed) { CancellationTokenRegistration registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { registration = cancellationToken.Register(s => ((TaskCompletionSource<DbConnectionInternal>)s).TrySetCanceled(), completion); } OpenAsyncRetry retry = new OpenAsyncRetry(this, registration); var openTask = completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default).Unwrap(); _currentCompletion = Tuple.Create(completion, openTask); if (s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection) || s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlErrorOpenConnection)) { return openTask.ContinueWith((t) => { if (t.Exception != null) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, t.Exception); } else { s_diagnosticListener.WriteConnectionOpenAfter(operationId, this); } }, TaskScheduler.Default); } return openTask; } else { s_diagnosticListener.WriteConnectionOpenAfter(operationId, this); return Task.CompletedTask; } } catch (Exception ex) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, ex); throw; } finally { SqlStatistics.StopTimer(statistics); } } private class OpenAsyncRetry { private SqlConnection _parent; private CancellationTokenRegistration _registration; public OpenAsyncRetry(SqlConnection parent, CancellationTokenRegistration registration) { _parent = parent; _registration = registration; } internal Task Retry(Task<DbConnectionInternal> retryTask) { _registration.Dispose(); if (retryTask.IsFaulted || retryTask.IsCanceled) { _parent.CloseInnerConnection(); } else { s_connectionFactory.SetInnerConnectionEvent(_parent, retryTask.Result); _parent.FinishOpen(); } return retryTask; } } private void PrepareStatisticsForNewConnection() { if (StatisticsEnabled || s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) || s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection)) { if (null == _statistics) { _statistics = new SqlStatistics(); } else { _statistics.ContinueOnNewConnection(); } } } private bool TryOpen(bool isAsync, ref TaskCompletionSource<DbConnectionInternal> completionSource) { if (_currentReconnectionTask == s_connectionClosedTask) { _currentReconnectionTask = null; } if (ForceNewConnection) { if (!InnerConnection.TryReplaceConnection(this, isAsync, ConnectionFactory, UserConnectionOptions, ref completionSource)) { Debug.Assert(completionSource != null, "If didn't completed sync, then should have a completionSource"); return false; } } else { if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, isAsync, UserConnectionOptions, ref completionSource)) { Debug.Assert(completionSource != null, "If didn't completed sync, then should have a completionSource"); return false; } } // does not require GC.KeepAlive(this) because of OnStateChange Debug.Assert(completionSource == null, "If completed sync, then shouldn't have a completionSource"); FinishOpen(); return true; } private void FinishOpen() { var tdsInnerConnection = (InnerConnection as SqlInternalConnectionTds); Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?"); if (!tdsInnerConnection.ConnectionOptions.Pooling) { // For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles GC.ReRegisterForFinalize(this); } if (StatisticsEnabled || s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand)) { ADP.TimerCurrent(out _statistics._openTimestamp); tdsInnerConnection.Parser.Statistics = _statistics; } else { tdsInnerConnection.Parser.Statistics = null; _statistics = null; // in case of previous Open/Close/reset_CollectStats sequence } } // // INTERNAL PROPERTIES // internal bool HasLocalTransaction { get { return GetOpenTdsConnection().HasLocalTransaction; } } internal bool HasLocalTransactionFromAPI { get { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return false; //we will not go into reconnection if we are inside the transaction } return GetOpenTdsConnection().HasLocalTransactionFromAPI; } } internal bool IsKatmaiOrNewer { get { if (_currentReconnectionTask != null) { // holds true even if task is completed return true; // if CR is enabled, connection, if established, will be Katmai+ } return GetOpenTdsConnection().IsKatmaiOrNewer; } } internal TdsParser Parser { get { SqlInternalConnectionTds tdsConnection = GetOpenTdsConnection(); return tdsConnection.Parser; } } /// <summary> /// Gets the TdsParser associated with this connection if there is one, otherwise returns null. /// </summary> internal TdsParser TryGetParser() => (InnerConnection as SqlInternalConnectionTds)?.Parser; // // INTERNAL METHODS // internal void ValidateConnectionForExecute(string method, SqlCommand command) { Task asyncWaitingForReconnection = _asyncWaitingForReconnection; if (asyncWaitingForReconnection != null) { if (!asyncWaitingForReconnection.IsCompleted) { throw SQL.MARSUnspportedOnConnection(); } else { Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection); } } if (_currentReconnectionTask != null) { Task currentReconnectionTask = _currentReconnectionTask; if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted) { return; // execution will wait for this task later } } SqlInternalConnectionTds innerConnection = GetOpenTdsConnection(method); innerConnection.ValidateConnectionForExecute(command); } // Surround name in brackets and then escape any end bracket to protect against SQL Injection. // NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well // as native OleDb and Odbc. static internal string FixupDatabaseTransactionName(string name) { if (!string.IsNullOrEmpty(name)) { return SqlServerEscapeHelper.EscapeIdentifier(name); } else { return name; } } // If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter // The close action also supports being run asynchronously internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction) { Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!"); if (breakConnection && (ConnectionState.Open == State)) { if (wrapCloseInAction != null) { int capturedCloseCount = _closeCount; Action closeAction = () => { if (capturedCloseCount == _closeCount) { Close(); } }; wrapCloseInAction(closeAction); } else { Close(); } } if (exception.Class >= TdsEnums.MIN_ERROR_CLASS) { // It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS or above is an error, // below TdsEnums.MIN_ERROR_CLASS denotes an info message. throw exception; } else { // If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler this.OnInfoMessage(new SqlInfoMessageEventArgs(exception)); } } // // PRIVATE METHODS // internal SqlInternalConnectionTds GetOpenTdsConnection() { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null == innerConnection) { throw ADP.ClosedConnectionError(); } return innerConnection; } internal SqlInternalConnectionTds GetOpenTdsConnection(string method) { DbConnectionInternal innerDbConnection = InnerConnection; SqlInternalConnectionTds innerSqlConnection = (innerDbConnection as SqlInternalConnectionTds); if (null == innerSqlConnection) { throw ADP.OpenConnectionRequired(method, innerDbConnection.State); } return innerSqlConnection; } internal void OnInfoMessage(SqlInfoMessageEventArgs imevent) { bool notified; OnInfoMessage(imevent, out notified); } internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) { SqlInfoMessageEventHandler handler = InfoMessage; if (null != handler) { notified = true; try { handler(this, imevent); } catch (Exception e) { if (!ADP.IsCatchableOrSecurityExceptionType(e)) { throw; } } } else { notified = false; } } // this only happens once per connection // SxS: using named file mapping APIs internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask, object value, int tag) { // Connection exists, schedule removal, will be added to ref collection after calling ValidateAndReconnect outerTask = outerTask.ContinueWith(task => { RemoveWeakReference(value); return task; }, TaskScheduler.Default).Unwrap(); } public void ResetStatistics() { if (null != Statistics) { Statistics.Reset(); if (ConnectionState.Open == State) { // update timestamp; ADP.TimerCurrent(out _statistics._openTimestamp); } } } public IDictionary RetrieveStatistics() { if (null != Statistics) { UpdateStatistics(); return Statistics.GetDictionary(); } else { return new SqlStatistics().GetDictionary(); } } private void UpdateStatistics() { if (ConnectionState.Open == State) { // update timestamp ADP.TimerCurrent(out _statistics._closeTimestamp); } // delegate the rest of the work to the SqlStatistics class Statistics.UpdateStatistics(); } /// <summary> /// TEST ONLY: Kills the underlying connection (without any checks) /// </summary> internal void KillConnection() { GetOpenTdsConnection().Parser._physicalStateObj.Handle.KillConnection(); } } // SqlConnection } // System.Data.SqlClient namespace
using J2N.Text; using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Lucene.Net.Codecs { /* * 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 AtomicReader = Lucene.Net.Index.AtomicReader; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using DataInput = Lucene.Net.Store.DataInput; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using FieldInfo = Lucene.Net.Index.FieldInfo; using FieldInfos = Lucene.Net.Index.FieldInfos; using Fields = Lucene.Net.Index.Fields; using MergeState = Lucene.Net.Index.MergeState; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; /// <summary> /// Codec API for writing term vectors: /// <para/> /// <list type="number"> /// <item><description>For every document, <see cref="StartDocument(int)"/> is called, /// informing the <see cref="Codec"/> how many fields will be written.</description></item> /// <item><description><see cref="StartField(FieldInfo, int, bool, bool, bool)"/> is called for /// each field in the document, informing the codec how many terms /// will be written for that field, and whether or not positions, /// offsets, or payloads are enabled.</description></item> /// <item><description>Within each field, <see cref="StartTerm(BytesRef, int)"/> is called /// for each term.</description></item> /// <item><description>If offsets and/or positions are enabled, then /// <see cref="AddPosition(int, int, int, BytesRef)"/> will be called for each term /// occurrence.</description></item> /// <item><description>After all documents have been written, <see cref="Finish(FieldInfos, int)"/> /// is called for verification/sanity-checks.</description></item> /// <item><description>Finally the writer is disposed (<see cref="Dispose(bool)"/>)</description></item> /// </list> /// <para/> /// @lucene.experimental /// </summary> public abstract class TermVectorsWriter : IDisposable { /// <summary> /// Sole constructor. (For invocation by subclass /// constructors, typically implicit.) /// </summary> protected internal TermVectorsWriter() { } /// <summary> /// Called before writing the term vectors of the document. /// <see cref="StartField(FieldInfo, int, bool, bool, bool)"/> will /// be called <paramref name="numVectorFields"/> times. Note that if term /// vectors are enabled, this is called even if the document /// has no vector fields, in this case <paramref name="numVectorFields"/> /// will be zero. /// </summary> public abstract void StartDocument(int numVectorFields); /// <summary> /// Called after a doc and all its fields have been added. </summary> [MethodImpl(MethodImplOptions.NoInlining)] public virtual void FinishDocument() { } /// <summary> /// Called before writing the terms of the field. /// <see cref="StartTerm(BytesRef, int)"/> will be called <paramref name="numTerms"/> times. /// </summary> public abstract void StartField(FieldInfo info, int numTerms, bool positions, bool offsets, bool payloads); /// <summary> /// Called after a field and all its terms have been added. </summary> public virtual void FinishField() { } /// <summary> /// Adds a <paramref name="term"/> and its term frequency <paramref name="freq"/>. /// If this field has positions and/or offsets enabled, then /// <see cref="AddPosition(int, int, int, BytesRef)"/> will be called /// <paramref name="freq"/> times respectively. /// </summary> public abstract void StartTerm(BytesRef term, int freq); /// <summary> /// Called after a term and all its positions have been added. </summary> public virtual void FinishTerm() { } /// <summary> /// Adds a term <paramref name="position"/> and offsets. </summary> public abstract void AddPosition(int position, int startOffset, int endOffset, BytesRef payload); /// <summary> /// Aborts writing entirely, implementation should remove /// any partially-written files, etc. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public abstract void Abort(); /// <summary> /// Called before <see cref="Dispose(bool)"/>, passing in the number /// of documents that were written. Note that this is /// intentionally redundant (equivalent to the number of /// calls to <see cref="StartDocument(int)"/>, but a <see cref="Codec"/> should /// check that this is the case to detect the bug described /// in LUCENE-1282. /// </summary> public abstract void Finish(FieldInfos fis, int numDocs); /// <summary> /// Called by <see cref="Index.IndexWriter"/> when writing new segments. /// <para/> /// This is an expert API that allows the codec to consume /// positions and offsets directly from the indexer. /// <para/> /// The default implementation calls <see cref="AddPosition(int, int, int, BytesRef)"/>, /// but subclasses can override this if they want to efficiently write /// all the positions, then all the offsets, for example. /// <para/> /// NOTE: this API is extremely expert and subject to change or removal!!! /// <para/> /// @lucene.internal /// </summary> // TODO: we should probably nuke this and make a more efficient 4.x format // PreFlex-RW could then be slow and buffer (its only used in tests...) public virtual void AddProx(int numProx, DataInput positions, DataInput offsets) { int position = 0; int lastOffset = 0; BytesRef payload = null; for (int i = 0; i < numProx; i++) { int startOffset; int endOffset; BytesRef thisPayload; if (positions == null) { position = -1; thisPayload = null; } else { int code = positions.ReadVInt32(); position += (int)((uint)code >> 1); if ((code & 1) != 0) { // this position has a payload int payloadLength = positions.ReadVInt32(); if (payload == null) { payload = new BytesRef(); payload.Bytes = new byte[payloadLength]; } else if (payload.Bytes.Length < payloadLength) { payload.Grow(payloadLength); } positions.ReadBytes(payload.Bytes, 0, payloadLength); payload.Length = payloadLength; thisPayload = payload; } else { thisPayload = null; } } if (offsets == null) { startOffset = endOffset = -1; } else { startOffset = lastOffset + offsets.ReadVInt32(); endOffset = startOffset + offsets.ReadVInt32(); lastOffset = endOffset; } AddPosition(position, startOffset, endOffset, thisPayload); } } /// <summary> /// Merges in the term vectors from the readers in /// <paramref name="mergeState"/>. The default implementation skips /// over deleted documents, and uses <see cref="StartDocument(int)"/>, /// <see cref="StartField(FieldInfo, int, bool, bool, bool)"/>, /// <see cref="StartTerm(BytesRef, int)"/>, <see cref="AddPosition(int, int, int, BytesRef)"/>, /// and <see cref="Finish(FieldInfos, int)"/>, /// returning the number of documents that were written. /// Implementations can override this method for more sophisticated /// merging (bulk-byte copying, etc). /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public virtual int Merge(MergeState mergeState) { int docCount = 0; for (int i = 0; i < mergeState.Readers.Count; i++) { AtomicReader reader = mergeState.Readers[i]; int maxDoc = reader.MaxDoc; IBits liveDocs = reader.LiveDocs; for (int docID = 0; docID < maxDoc; docID++) { if (liveDocs != null && !liveDocs.Get(docID)) { // skip deleted docs continue; } // NOTE: it's very important to first assign to vectors then pass it to // termVectorsWriter.addAllDocVectors; see LUCENE-1282 Fields vectors = reader.GetTermVectors(docID); AddAllDocVectors(vectors, mergeState); docCount++; mergeState.CheckAbort.Work(300); } } Finish(mergeState.FieldInfos, docCount); return docCount; } /// <summary> /// Safe (but, slowish) default method to write every /// vector field in the document. /// </summary> protected void AddAllDocVectors(Fields vectors, MergeState mergeState) { if (vectors == null) { StartDocument(0); FinishDocument(); return; } int numFields = vectors.Count; if (numFields == -1) { // count manually! TODO: Maybe enforce that Fields.size() returns something valid? numFields = 0; //for (IEnumerator<string> it = vectors.Iterator(); it.hasNext();) foreach (string it in vectors) { numFields++; } } StartDocument(numFields); string lastFieldName = null; TermsEnum termsEnum = null; DocsAndPositionsEnum docsAndPositionsEnum = null; int fieldCount = 0; foreach (string fieldName in vectors) { fieldCount++; FieldInfo fieldInfo = mergeState.FieldInfos.FieldInfo(fieldName); if (Debugging.AssertsEnabled) Debugging.Assert(lastFieldName == null || fieldName.CompareToOrdinal(lastFieldName) > 0, () => "lastFieldName=" + lastFieldName + " fieldName=" + fieldName); lastFieldName = fieldName; Terms terms = vectors.GetTerms(fieldName); if (terms == null) { // FieldsEnum shouldn't lie... continue; } bool hasPositions = terms.HasPositions; bool hasOffsets = terms.HasOffsets; bool hasPayloads = terms.HasPayloads; if (Debugging.AssertsEnabled) Debugging.Assert(!hasPayloads || hasPositions); int numTerms = (int)terms.Count; if (numTerms == -1) { // count manually. It is stupid, but needed, as Terms.size() is not a mandatory statistics function numTerms = 0; termsEnum = terms.GetEnumerator(termsEnum); while (termsEnum.MoveNext()) { numTerms++; } } StartField(fieldInfo, numTerms, hasPositions, hasOffsets, hasPayloads); termsEnum = terms.GetEnumerator(termsEnum); int termCount = 0; while (termsEnum.MoveNext()) { termCount++; int freq = (int)termsEnum.TotalTermFreq; StartTerm(termsEnum.Term, freq); if (hasPositions || hasOffsets) { docsAndPositionsEnum = termsEnum.DocsAndPositions(null, docsAndPositionsEnum); if (Debugging.AssertsEnabled) Debugging.Assert(docsAndPositionsEnum != null); int docID = docsAndPositionsEnum.NextDoc(); if (Debugging.AssertsEnabled) { Debugging.Assert(docID != DocIdSetIterator.NO_MORE_DOCS); Debugging.Assert(docsAndPositionsEnum.Freq == freq); } for (int posUpto = 0; posUpto < freq; posUpto++) { int pos = docsAndPositionsEnum.NextPosition(); int startOffset = docsAndPositionsEnum.StartOffset; int endOffset = docsAndPositionsEnum.EndOffset; BytesRef payload = docsAndPositionsEnum.GetPayload(); if (Debugging.AssertsEnabled) Debugging.Assert(!hasPositions || pos >= 0); AddPosition(pos, startOffset, endOffset, payload); } } FinishTerm(); } if (Debugging.AssertsEnabled) Debugging.Assert(termCount == numTerms); FinishField(); } if (Debugging.AssertsEnabled) Debugging.Assert(fieldCount == numFields); FinishDocument(); } /// <summary> /// Return the <see cref="T:IComparer{BytesRef}"/> used to sort terms /// before feeding to this API. /// </summary> public abstract IComparer<BytesRef> Comparer { get; } /// <summary> /// Disposes all resources used by this object. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Implementations must override and should dispose all resources used by this instance. /// </summary> protected abstract void Dispose(bool disposing); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Xml; using System.Xml.Serialization; using System.Xml.Schema; using System.Data.Common; using System.Diagnostics; using System.Text; using System.Reflection; namespace System.Data.SqlTypes { [XmlSchemaProvider("GetXsdType")] public sealed class SqlXml : INullable, IXmlSerializable { private static readonly Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader> s_sqlReaderDelegate = CreateSqlReaderDelegate(); private static readonly XmlReaderSettings s_defaultXmlReaderSettings = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment }; private static readonly XmlReaderSettings s_defaultXmlReaderSettingsCloseInput = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment, CloseInput = true }; #if !uapaot private static MethodInfo s_createSqlReaderMethodInfo; private MethodInfo _createSqlReaderMethodInfo; #endif private bool _fNotNull; // false if null, the default ctor (plain 0) will make it Null private Stream _stream; private bool _firstCreateReader; public SqlXml() { SetNull(); } // constructor // construct a Null private SqlXml(bool fNull) { SetNull(); } public SqlXml(XmlReader value) { // whoever pass in the XmlReader is responsible for closing it if (value == null) { SetNull(); } else { _fNotNull = true; _firstCreateReader = true; _stream = CreateMemoryStreamFromXmlReader(value); } } public SqlXml(Stream value) { // whoever pass in the stream is responsible for closing it // similar to SqlBytes implementation if (value == null) { SetNull(); } else { _firstCreateReader = true; _fNotNull = true; _stream = value; } } public XmlReader CreateReader() { if (IsNull) { throw new SqlNullValueException(); } SqlXmlStreamWrapper stream = new SqlXmlStreamWrapper(_stream); // if it is the first time we create reader and stream does not support CanSeek, no need to reset position if ((!_firstCreateReader || stream.CanSeek) && stream.Position != 0) { stream.Seek(0, SeekOrigin.Begin); } #if !uapaot // NOTE: Maintaining createSqlReaderMethodInfo private field member to preserve the serialization of the class if (_createSqlReaderMethodInfo == null) { _createSqlReaderMethodInfo = CreateSqlReaderMethodInfo; } Debug.Assert(_createSqlReaderMethodInfo != null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null."); #endif XmlReader r = CreateSqlXmlReader(stream); _firstCreateReader = false; return r; } internal static XmlReader CreateSqlXmlReader(Stream stream, bool closeInput = false, bool throwTargetInvocationExceptions = false) { // Call the internal delegate XmlReaderSettings settingsToUse = closeInput ? s_defaultXmlReaderSettingsCloseInput : s_defaultXmlReaderSettings; try { return s_sqlReaderDelegate(stream, settingsToUse, null); } // For particular callers, we need to wrap all exceptions inside a TargetInvocationException to simulate calling CreateSqlReader via MethodInfo.Invoke catch (Exception ex) { if ((!throwTargetInvocationExceptions) || (!ADP.IsCatchableExceptionType(ex))) { throw; } else { throw new TargetInvocationException(ex); } } } #if uapaot private static Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader> CreateSqlReaderDelegate() => System.Xml.XmlReader.CreateSqlReader; #else private static Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader> CreateSqlReaderDelegate() { Debug.Assert(CreateSqlReaderMethodInfo != null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null."); return (Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader>)CreateSqlReaderMethodInfo.CreateDelegate(typeof(Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader>)); } private static MethodInfo CreateSqlReaderMethodInfo { get { if (s_createSqlReaderMethodInfo == null) { s_createSqlReaderMethodInfo = typeof(System.Xml.XmlReader).GetMethod("CreateSqlReader", BindingFlags.Static | BindingFlags.NonPublic); } return s_createSqlReaderMethodInfo; } } #endif // INullable public bool IsNull { get { return !_fNotNull; } } public string Value { get { if (IsNull) throw new SqlNullValueException(); StringWriter sw = new StringWriter((System.IFormatProvider)null); XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = false; // don't close the memory stream writerSettings.ConformanceLevel = ConformanceLevel.Fragment; XmlWriter ww = XmlWriter.Create(sw, writerSettings); XmlReader reader = CreateReader(); if (reader.ReadState == ReadState.Initial) reader.Read(); while (!reader.EOF) { ww.WriteNode(reader, true); } ww.Flush(); return sw.ToString(); } } public static SqlXml Null { get { return new SqlXml(true); } } private void SetNull() { _fNotNull = false; _stream = null; _firstCreateReader = true; } private Stream CreateMemoryStreamFromXmlReader(XmlReader reader) { XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = false; // don't close the memory stream writerSettings.ConformanceLevel = ConformanceLevel.Fragment; writerSettings.Encoding = Encoding.GetEncoding("utf-16"); writerSettings.OmitXmlDeclaration = true; MemoryStream writerStream = new MemoryStream(); XmlWriter ww = XmlWriter.Create(writerStream, writerSettings); if (reader.ReadState == ReadState.Closed) throw new InvalidOperationException(SQLResource.ClosedXmlReaderMessage); if (reader.ReadState == ReadState.Initial) reader.Read(); while (!reader.EOF) { ww.WriteNode(reader, true); } ww.Flush(); // set the stream to the beginning writerStream.Seek(0, SeekOrigin.Begin); return writerStream; } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader r) { string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. r.ReadInnerXml(); SetNull(); } else { _fNotNull = true; _firstCreateReader = true; _stream = new MemoryStream(); StreamWriter sw = new StreamWriter(_stream); sw.Write(r.ReadInnerXml()); sw.Flush(); if (_stream.CanSeek) _stream.Seek(0, SeekOrigin.Begin); } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { // Instead of the WriteRaw use the WriteNode. As Tds sends a binary stream - Create a XmlReader to convert // get the Xml string value from the binary and call WriteNode to pass that out to the XmlWriter. XmlReader reader = CreateReader(); if (reader.ReadState == ReadState.Initial) reader.Read(); while (!reader.EOF) { writer.WriteNode(reader, true); } } writer.Flush(); } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("anyType", XmlSchema.Namespace); } } // SqlXml // two purposes for this class // 1) keep its internal position so one reader positions on the orginial stream // will not interface with the other // 2) when xmlreader calls close, do not close the orginial stream // internal sealed class SqlXmlStreamWrapper : Stream { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- private Stream _stream; private long _lPosition; private bool _isClosed; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- internal SqlXmlStreamWrapper(Stream stream) { _stream = stream; Debug.Assert(_stream != null, "stream can not be null"); _lPosition = 0; _isClosed = false; } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // Always can read/write/seek, unless stream is null, // which means the stream has been closed. public override bool CanRead { get { if (IsStreamClosed()) return false; return _stream.CanRead; } } public override bool CanSeek { get { if (IsStreamClosed()) return false; return _stream.CanSeek; } } public override bool CanWrite { get { if (IsStreamClosed()) return false; return _stream.CanWrite; } } public override long Length { get { ThrowIfStreamClosed("get_Length"); ThrowIfStreamCannotSeek("get_Length"); return _stream.Length; } } public override long Position { get { ThrowIfStreamClosed("get_Position"); ThrowIfStreamCannotSeek("get_Position"); return _lPosition; } set { ThrowIfStreamClosed("set_Position"); ThrowIfStreamCannotSeek("set_Position"); if (value < 0 || value > _stream.Length) throw new ArgumentOutOfRangeException(nameof(value)); else _lPosition = value; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public override long Seek(long offset, SeekOrigin origin) { long lPosition = 0; ThrowIfStreamClosed(nameof(Seek)); ThrowIfStreamCannotSeek(nameof(Seek)); switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _stream.Length) throw new ArgumentOutOfRangeException(nameof(offset)); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _stream.Length) throw new ArgumentOutOfRangeException(nameof(offset)); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _stream.Length + offset; if (lPosition < 0 || lPosition > _stream.Length) throw new ArgumentOutOfRangeException(nameof(offset)); _lPosition = lPosition; break; default: throw ADP.InvalidSeekOrigin(nameof(offset)); } return _lPosition; } public override int Read(byte[] buffer, int offset, int count) { ThrowIfStreamClosed(nameof(Read)); ThrowIfStreamCannotRead(nameof(Read)); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); int iBytesRead = _stream.Read(buffer, offset, count); _lPosition += iBytesRead; return iBytesRead; } public override void Write(byte[] buffer, int offset, int count) { ThrowIfStreamClosed(nameof(Write)); ThrowIfStreamCannotWrite(nameof(Write)); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); _stream.Write(buffer, offset, count); _lPosition += count; } public override int ReadByte() { ThrowIfStreamClosed(nameof(ReadByte)); ThrowIfStreamCannotRead(nameof(ReadByte)); // If at the end of stream, return -1, rather than call ReadByte, // which will throw exception. This is the behavior for Stream. // if (_stream.CanSeek && _lPosition >= _stream.Length) return -1; if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); int ret = _stream.ReadByte(); _lPosition++; return ret; } public override void WriteByte(byte value) { ThrowIfStreamClosed(nameof(WriteByte)); ThrowIfStreamCannotWrite(nameof(WriteByte)); if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); _stream.WriteByte(value); _lPosition++; } public override void SetLength(long value) { ThrowIfStreamClosed(nameof(SetLength)); ThrowIfStreamCannotSeek(nameof(SetLength)); _stream.SetLength(value); if (_lPosition > value) _lPosition = value; } public override void Flush() { if (_stream != null) _stream.Flush(); } protected override void Dispose(bool disposing) { try { // does not close the underline stream but mark itself as closed _isClosed = true; } finally { base.Dispose(disposing); } } private void ThrowIfStreamCannotSeek(string method) { if (!_stream.CanSeek) throw new NotSupportedException(SQLResource.InvalidOpStreamNonSeekable(method)); } private void ThrowIfStreamCannotRead(string method) { if (!_stream.CanRead) throw new NotSupportedException(SQLResource.InvalidOpStreamNonReadable(method)); } private void ThrowIfStreamCannotWrite(string method) { if (!_stream.CanWrite) throw new NotSupportedException(SQLResource.InvalidOpStreamNonWritable(method)); } private void ThrowIfStreamClosed(string method) { if (IsStreamClosed()) throw new ObjectDisposedException(SQLResource.InvalidOpStreamClosed(method)); } private bool IsStreamClosed() { // Check the .CanRead and .CanWrite and .CanSeek properties to make sure stream is really closed if (_isClosed || _stream == null || (!_stream.CanRead && !_stream.CanWrite && !_stream.CanSeek)) return true; else return false; } } // class SqlXmlStreamWrapper }
using NBitcoin; using NBitcoin.Policy; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using WalletWasabi.Blockchain.Analysis.Clustering; using WalletWasabi.Blockchain.Keys; using WalletWasabi.Blockchain.TransactionBuilding; using WalletWasabi.Blockchain.TransactionOutputs; using WalletWasabi.Exceptions; using WalletWasabi.Helpers; using WalletWasabi.Logging; using WalletWasabi.Models; using WalletWasabi.Tor.Socks5.Exceptions; using WalletWasabi.WebClients.PayJoin; namespace WalletWasabi.Blockchain.Transactions { public class TransactionFactory { /// <param name="allowUnconfirmed">Allow to spend unconfirmed transactions, if necessary.</param> public TransactionFactory(Network network, KeyManager keyManager, ICoinsView coins, AllTransactionStore transactionStore, string password = "", bool allowUnconfirmed = false) { Network = Guard.NotNull(nameof(network), network); KeyManager = Guard.NotNull(nameof(keyManager), keyManager); Coins = Guard.NotNull(nameof(coins), coins); TransactionStore = Guard.NotNull(nameof(transactionStore), transactionStore); Password = password; AllowUnconfirmed = allowUnconfirmed; } public Network Network { get; } public KeyManager KeyManager { get; } public ICoinsView Coins { get; } public string Password { get; } public bool AllowUnconfirmed { get; } private AllTransactionStore TransactionStore { get; } /// <exception cref="ArgumentException"></exception> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> public BuildTransactionResult BuildTransaction( PaymentIntent payments, FeeRate feeRate, IEnumerable<OutPoint>? allowedInputs = null, IPayjoinClient? payjoinClient = null) => BuildTransaction(payments, () => feeRate, allowedInputs, () => LockTime.Zero, payjoinClient); /// <exception cref="ArgumentException"></exception> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> public BuildTransactionResult BuildTransaction( PaymentIntent payments, Func<FeeRate> feeRateFetcher, IEnumerable<OutPoint>? allowedInputs = null, Func<LockTime>? lockTimeSelector = null, IPayjoinClient? payjoinClient = null) { payments = Guard.NotNull(nameof(payments), payments); lockTimeSelector ??= () => LockTime.Zero; long totalAmount = payments.TotalAmount.Satoshi; if (totalAmount is < 0 or > Constants.MaximumNumberOfSatoshis) { throw new ArgumentOutOfRangeException($"{nameof(payments)}.{nameof(payments.TotalAmount)} sum cannot be smaller than 0 or greater than {Constants.MaximumNumberOfSatoshis}."); } // Get allowed coins to spend. var availableCoinsView = Coins.Available(); List<SmartCoin> allowedSmartCoinInputs = AllowUnconfirmed // Inputs that can be used to build the transaction. ? availableCoinsView.ToList() : availableCoinsView.Confirmed().ToList(); if (allowedInputs is { }) // If allowedInputs are specified then select the coins from them. { if (!allowedInputs.Any()) { throw new ArgumentException($"{nameof(allowedInputs)} is not null, but empty."); } allowedSmartCoinInputs = allowedSmartCoinInputs .Where(x => allowedInputs.Any(y => y.Hash == x.TransactionId && y.N == x.Index)) .ToList(); // Add those that have the same script, because common ownership is already exposed. // But only if the user didn't click the "max" button. In this case he'd send more money than what he'd think. if (payments.ChangeStrategy != ChangeStrategy.AllRemainingCustom) { var allScripts = allowedSmartCoinInputs.Select(x => x.ScriptPubKey).ToHashSet(); foreach (var coin in availableCoinsView.Where(x => !allowedSmartCoinInputs.Any(y => x.TransactionId == y.TransactionId && x.Index == y.Index))) { if (!(AllowUnconfirmed || coin.Confirmed)) { continue; } if (allScripts.Contains(coin.ScriptPubKey)) { allowedSmartCoinInputs.Add(coin); } } } } // Get and calculate fee Logger.LogInfo("Calculating dynamic transaction fee..."); TransactionBuilder builder = Network.CreateTransactionBuilder(); builder.SetCoinSelector(new SmartCoinSelector(allowedSmartCoinInputs)); builder.AddCoins(allowedSmartCoinInputs.Select(c => c.Coin)); builder.SetLockTime(lockTimeSelector()); foreach (var request in payments.Requests.Where(x => x.Amount.Type == MoneyRequestType.Value)) { var amountRequest = request.Amount; builder.Send(request.Destination, amountRequest.Amount); if (amountRequest.SubtractFee) { builder.SubtractFees(); } } HdPubKey changeHdPubKey = null; if (payments.TryGetCustomRequest(out DestinationRequest? custChange)) { var changeScript = custChange.Destination.ScriptPubKey; changeHdPubKey = KeyManager.GetKeyForScriptPubKey(changeScript); var changeStrategy = payments.ChangeStrategy; if (changeStrategy == ChangeStrategy.Custom) { builder.SetChange(changeScript); } else if (changeStrategy == ChangeStrategy.AllRemainingCustom) { builder.SendAllRemaining(changeScript); } else { throw new NotSupportedException(payments.ChangeStrategy.ToString()); } } else { KeyManager.AssertCleanKeysIndexed(isInternal: true); KeyManager.AssertLockedInternalKeysIndexed(14); changeHdPubKey = KeyManager.GetKeys(KeyState.Clean, true).FirstOrDefault(); builder.SetChange(changeHdPubKey.P2wpkhScript); } builder.OptInRBF = true; FeeRate feeRate = feeRateFetcher(); builder.SendEstimatedFees(feeRate); var psbt = builder.BuildPSBT(false); var spentCoins = psbt.Inputs.Select(txin => allowedSmartCoinInputs.First(y => y.OutPoint == txin.PrevOut)).ToArray(); var realToSend = payments.Requests .Select(t => (label: t.Label, destination: t.Destination, amount: psbt.Outputs.FirstOrDefault(o => o.ScriptPubKey == t.Destination.ScriptPubKey)?.Value)) .Where(i => i.amount is { }); if (!psbt.TryGetFee(out var fee)) { throw new InvalidOperationException("Impossible to get the fees of the PSBT, this should never happen."); } Logger.LogInfo($"Fee: {fee.Satoshi} Satoshi."); var vSize = builder.EstimateSize(psbt.GetOriginalTransaction(), true); Logger.LogInfo($"Estimated tx size: {vSize} vBytes."); // Do some checks Money totalSendAmountNoFee = realToSend.Sum(x => x.amount); if (totalSendAmountNoFee == Money.Zero) { throw new InvalidOperationException("The amount after subtracting the fee is too small to be sent."); } Money totalOutgoingAmountNoFee; if (changeHdPubKey is null) { totalOutgoingAmountNoFee = totalSendAmountNoFee; } else { totalOutgoingAmountNoFee = realToSend.Where(x => !changeHdPubKey.ContainsScript(x.destination.ScriptPubKey)).Sum(x => x.amount); } decimal totalOutgoingAmountNoFeeDecimal = totalOutgoingAmountNoFee.ToDecimal(MoneyUnit.BTC); // Cannot divide by zero, so use the closest number we have to zero. decimal totalOutgoingAmountNoFeeDecimalDivisor = totalOutgoingAmountNoFeeDecimal == 0 ? decimal.MinValue : totalOutgoingAmountNoFeeDecimal; decimal feePc = 100 * fee.ToDecimal(MoneyUnit.BTC) / totalOutgoingAmountNoFeeDecimalDivisor; if (feePc > 1) { Logger.LogInfo($"The transaction fee is {feePc:0.#}% of the sent amount.{Environment.NewLine}" + $"Sending:\t {totalOutgoingAmountNoFee.ToString(fplus: false, trimExcessZero: true)} BTC.{Environment.NewLine}" + $"Fee:\t\t {fee.Satoshi} Satoshi."); } if (feePc > 100) { throw new InvalidOperationException($"The transaction fee is more than twice the sent amount: {feePc:0.#}%."); } if (spentCoins.Any(u => !u.Confirmed)) { Logger.LogInfo("Unconfirmed transaction is spent."); } // Build the transaction Logger.LogInfo("Signing transaction..."); // It must be watch only, too, because if we have the key and also hardware wallet, we do not care we can sign. psbt.AddKeyPaths(KeyManager); psbt.AddPrevTxs(TransactionStore); Transaction tx; if (KeyManager.IsWatchOnly) { tx = psbt.GetGlobalTransaction(); } else { IEnumerable<ExtKey> signingKeys = KeyManager.GetSecrets(Password, spentCoins.Select(x => x.ScriptPubKey).ToArray()); builder = builder.AddKeys(signingKeys.ToArray()); builder.SignPSBT(psbt); var isPayjoin = false; // Try to pay using payjoin if (payjoinClient is { }) { psbt = TryNegotiatePayjoin(payjoinClient, builder, psbt, changeHdPubKey); isPayjoin = true; psbt.AddKeyPaths(KeyManager); psbt.AddPrevTxs(TransactionStore); } psbt.Finalize(); tx = psbt.ExtractTransaction(); var checkResults = builder.Check(tx).ToList(); if (!psbt.TryGetEstimatedFeeRate(out FeeRate actualFeeRate)) { throw new InvalidOperationException("Impossible to get the fee rate of the PSBT, this should never happen."); } if (!isPayjoin) { // Manually check the feerate, because some inaccuracy is possible. var sb1 = feeRate.SatoshiPerByte; var sb2 = actualFeeRate.SatoshiPerByte; if (Math.Abs(sb1 - sb2) > 2) // 2s/b inaccuracy ok. { // So it'll generate a transactionpolicy error thrown below. checkResults.Add(new NotEnoughFundsPolicyError("Fees different than expected")); } } if (checkResults.Count > 0) { throw new InvalidTxException(tx, checkResults); } } var smartTransaction = new SmartTransaction(tx, Height.Unknown, label: SmartLabel.Merge(payments.Requests.Select(x => x.Label))); foreach (var coin in spentCoins) { smartTransaction.WalletInputs.Add(coin); } var label = SmartLabel.Merge(payments.Requests.Select(x => x.Label).Concat(smartTransaction.WalletInputs.Select(x => x.HdPubKey.Label))); for (var i = 0U; i < tx.Outputs.Count; i++) { TxOut output = tx.Outputs[i]; var foundKey = KeyManager.GetKeyForScriptPubKey(output.ScriptPubKey); if (foundKey is { }) { var smartCoin = new SmartCoin(smartTransaction, i, foundKey); label = SmartLabel.Merge(label, smartCoin.HdPubKey.Label); // foundKey's label is already added to the coinlabel. smartTransaction.WalletOutputs.Add(smartCoin); } } foreach (var coin in smartTransaction.WalletOutputs) { var foundPaymentRequest = payments.Requests.FirstOrDefault(x => x.Destination.ScriptPubKey == coin.ScriptPubKey); // If change then we concatenate all the labels. // The foundkeylabel has already been added previously, so no need to concatenate. if (foundPaymentRequest is null) // Then it's autochange. { coin.HdPubKey.SetLabel(label); } else { coin.HdPubKey.SetLabel(SmartLabel.Merge(coin.HdPubKey.Label, foundPaymentRequest.Label)); } } Logger.LogInfo($"Transaction is successfully built: {tx.GetHash()}."); var sign = !KeyManager.IsWatchOnly; return new BuildTransactionResult(smartTransaction, psbt, sign, fee, feePc); } private PSBT TryNegotiatePayjoin(IPayjoinClient payjoinClient, TransactionBuilder builder, PSBT psbt, HdPubKey changeHdPubKey) { try { Logger.LogInfo($"Negotiating payjoin payment with `{payjoinClient.PaymentUrl}`."); psbt = payjoinClient.RequestPayjoin(psbt, KeyManager.ExtPubKey, new RootedKeyPath(KeyManager.MasterFingerprint.Value, KeyManager.DefaultAccountKeyPath), changeHdPubKey, CancellationToken.None).GetAwaiter().GetResult(); // WTF??! builder.SignPSBT(psbt); Logger.LogInfo($"Payjoin payment was negotiated successfully."); } catch (HttpRequestException ex) when (ex.InnerException is TorConnectCommandFailedException innerEx) { if (innerEx.Message.Contains("HostUnreachable")) { Logger.LogWarning($"Payjoin server is not reachable. Ignoring..."); } // ignore } catch (HttpRequestException e) { Logger.LogWarning($"Payjoin server responded with {e.ToTypeMessageString()}. Ignoring..."); } catch (PayjoinException e) { Logger.LogWarning($"Payjoin server responded with {e.Message}. Ignoring..."); } return psbt; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ImplementAbstractClass; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.Options; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementAbstractClass { public partial class ImplementAbstractClassTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpImplementAbstractClassCodeFixProvider()); private IDictionary<OptionKey, object> AllOptionsOff => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithNoneEnforcement)); internal Task TestAllOptionsOffAsync( string initialMarkup, string expectedMarkup, int index = 0, bool ignoreTrivia = true, IDictionary<OptionKey, object> options = null) { options = options ?? new Dictionary<OptionKey, object>(); foreach (var kvp in AllOptionsOff) { options.Add(kvp); } return TestInRegularAndScriptAsync( initialMarkup, expectedMarkup, index: index, ignoreTrivia: ignoreTrivia, options: options); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestSimpleMethods() { await TestAllOptionsOffAsync( @"abstract class Foo { protected abstract string FooMethod(); public abstract void Blah(); } abstract class Bar : Foo { public abstract bool BarMethod(); public override void Blah() { } } class [|Program|] : Foo { static void Main(string[] args) { } }", @"abstract class Foo { protected abstract string FooMethod(); public abstract void Blah(); } abstract class Bar : Foo { public abstract bool BarMethod(); public override void Blah() { } } class Program : Foo { static void Main(string[] args) { } public override void Blah() { throw new System.NotImplementedException(); } protected override string FooMethod() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [WorkItem(16434, "https://github.com/dotnet/roslyn/issues/16434")] public async Task TestMethodWithTupleNames() { await TestAllOptionsOffAsync( @"abstract class Base { protected abstract (int a, int b) Method((string, string d) x); } class [|Program|] : Base { }", @"abstract class Base { protected abstract (int a, int b) Method((string, string d) x); } class Program : Base { protected override (int a, int b) Method((string, string d) x) { throw new System.NotImplementedException(); } }"); } [WorkItem(543234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543234")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNotAvailableForStruct() { await TestMissingInRegularAndScriptAsync( @"abstract class Foo { public abstract void Bar(); } struct [|Program|] : Foo { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalIntParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(int x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(int x = 3); } class b : d { public override void foo(int x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalCharParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(char x = 'a'); } class [|b|] : d { }", @"abstract class d { public abstract void foo(char x = 'a'); } class b : d { public override void foo(char x = 'a') { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalStringParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(string x = ""x""); } class [|b|] : d { }", @"abstract class d { public abstract void foo(string x = ""x""); } class b : d { public override void foo(string x = ""x"") { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalShortParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(short x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(short x = 3); } class b : d { public override void foo(short x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalDecimalParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(decimal x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(decimal x = 3); } class b : d { public override void foo(decimal x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalDoubleParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(double x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(double x = 3); } class b : d { public override void foo(double x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalLongParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(long x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(long x = 3); } class b : d { public override void foo(long x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalFloatParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(float x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(float x = 3); } class b : d { public override void foo(float x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUshortParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(ushort x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(ushort x = 3); } class b : d { public override void foo(ushort x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUintParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(uint x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(uint x = 3); } class b : d { public override void foo(uint x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUlongParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(ulong x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(ulong x = 3); } class b : d { public override void foo(ulong x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalStructParameter() { await TestAllOptionsOffAsync( @"struct b { } abstract class d { public abstract void foo(b x = new b()); } class [|c|] : d { }", @"struct b { } abstract class d { public abstract void foo(b x = new b()); } class c : d { public override void foo(b x = default(b)) { throw new System.NotImplementedException(); } }"); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalNullableStructParameter() { await TestAllOptionsOffAsync( @"struct b { } abstract class d { public abstract void m(b? x = null, b? y = default(b?)); } class [|c|] : d { }", @"struct b { } abstract class d { public abstract void m(b? x = null, b? y = default(b?)); } class c : d { public override void m(b? x = null, b? y = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalNullableIntParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void m(int? x = 5, int? y = default(int?)); } class [|c|] : d { }", @"abstract class d { public abstract void m(int? x = 5, int? y = default(int?)); } class c : d { public override void m(int? x = 5, int? y = null) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalObjectParameter() { await TestAllOptionsOffAsync( @"class b { } abstract class d { public abstract void foo(b x = null); } class [|c|] : d { }", @"class b { } abstract class d { public abstract void foo(b x = null); } class c : d { public override void foo(b x = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(543883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543883")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestDifferentAccessorAccessibility() { await TestAllOptionsOffAsync( @"abstract class c1 { public abstract c1 this[c1 x] { get; internal set; } } class [|c2|] : c1 { }", @"abstract class c1 { public abstract c1 this[c1 x] { get; internal set; } } class c2 : c1 { public override c1 this[c1 x] { get { throw new System.NotImplementedException(); } internal set { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestEvent1() { await TestAllOptionsOffAsync( @"using System; abstract class C { public abstract event Action E; } class [|D|] : C { }", @"using System; abstract class C { public abstract event Action E; } class D : C { public override event Action E; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestIndexer1() { await TestAllOptionsOffAsync( @"using System; abstract class C { public abstract int this[string s] { get { } internal set { } } } class [|D|] : C { }", @"using System; abstract class C { public abstract int this[string s] { get { } internal set { } } } class D : C { public override int this[string s] { get { throw new NotImplementedException(); } internal set { throw new NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestMissingInHiddenType() { await TestMissingInRegularAndScriptAsync( @"using System; abstract class Foo { public abstract void F(); } class [|Program|] : Foo { #line hidden } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestGenerateIntoNonHiddenPart() { await TestAllOptionsOffAsync( @"using System; abstract class Foo { public abstract void F(); } partial class [|Program|] : Foo { #line hidden } #line default partial class Program ", @"using System; abstract class Foo { public abstract void F(); } partial class Program : Foo { #line hidden } #line default partial class Program { public override void F() { throw new NotImplementedException(); } } ", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestGenerateIfLocationAvailable() { await TestAllOptionsOffAsync( @"#line default using System; abstract class Foo { public abstract void F(); } partial class [|Program|] : Foo { void Bar() { } #line hidden } #line default", @"#line default using System; abstract class Foo { public abstract void F(); } partial class Program : Foo { public override void F() { throw new NotImplementedException(); } void Bar() { } #line hidden } #line default", ignoreTrivia: false); } [WorkItem(545585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545585")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOnlyGenerateUnimplementedAccessors() { await TestAllOptionsOffAsync( @"using System; abstract class A { public abstract int X { get; set; } } abstract class B : A { public override int X { get { throw new NotImplementedException(); } } } class [|C|] : B { }", @"using System; abstract class A { public abstract int X { get; set; } } abstract class B : A { public override int X { get { throw new NotImplementedException(); } } } class C : B { public override int X { set { throw new NotImplementedException(); } } }"); } [WorkItem(545615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545615")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestParamsArray() { await TestAllOptionsOffAsync( @"class A { public virtual void Foo(int x, params int[] y) { } } abstract class B : A { public abstract override void Foo(int x, int[] y = null); } class [|C|] : B { }", @"class A { public virtual void Foo(int x, params int[] y) { } } abstract class B : A { public abstract override void Foo(int x, int[] y = null); } class C : B { public override void Foo(int x, params int[] y) { throw new System.NotImplementedException(); } }"); } [WorkItem(545636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545636")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullPointerType() { await TestAllOptionsOffAsync( @"abstract class C { unsafe public abstract void Foo(int* x = null); } class [|D|] : C { }", @"abstract class C { unsafe public abstract void Foo(int* x = null); } class D : C { public override unsafe void Foo(int* x = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(545637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545637")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestErrorTypeCalledVar() { await TestAllOptionsOffAsync( @"extern alias var; abstract class C { public abstract void Foo(var::X x); } class [|D|] : C { }", @"extern alias var; abstract class C { public abstract void Foo(var::X x); } class D : C { public override void Foo(X x) { throw new System.NotImplementedException(); } }"); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task Bugfix_581500() { await TestAllOptionsOffAsync( @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class [|T|] : A<T> { } } }", @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class T : A<T> { public override void M(B.T x) { throw new System.NotImplementedException(); } } } }"); } [WorkItem(625442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625442")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task Bugfix_625442() { await TestAllOptionsOffAsync( @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class [|T|] : A<B.T> { } } } ", @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class T : A<B.T> { public override void M(A<A<T>.B>.B.T x) { throw new System.NotImplementedException(); } } } } ", ignoreTrivia: false); } [WorkItem(2407, "https://github.com/dotnet/roslyn/issues/2407")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task ImplementClassWithInaccessibleMembers() { await TestAllOptionsOffAsync( @"using System; using System.Globalization; public class [|x|] : EastAsianLunisolarCalendar { }", @"using System; using System.Globalization; public class x : EastAsianLunisolarCalendar { public override int[] Eras { get { throw new NotImplementedException(); } } internal override int MinCalendarYear { get { throw new NotImplementedException(); } } internal override int MaxCalendarYear { get { throw new NotImplementedException(); } } internal override EraInfo[] CalEraInfo { get { throw new NotImplementedException(); } } internal override DateTime MinDate { get { throw new NotImplementedException(); } } internal override DateTime MaxDate { get { throw new NotImplementedException(); } } public override int GetEra(DateTime time) { throw new NotImplementedException(); } internal override int GetGregorianYear(int year, int era) { throw new NotImplementedException(); } internal override int GetYear(int year, DateTime time) { throw new NotImplementedException(); } internal override int GetYearInfo(int LunarYear, int Index) { throw new NotImplementedException(); } }"); } [WorkItem(13149, "https://github.com/dotnet/roslyn/issues/13149")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestPartialClass1() { await TestAllOptionsOffAsync( @"using System; public abstract class Base { public abstract void Dispose(); } partial class [|A|] : Base { } partial class A { }", @"using System; public abstract class Base { public abstract void Dispose(); } partial class A : Base { public override void Dispose() { throw new NotImplementedException(); } } partial class A { }"); } [WorkItem(13149, "https://github.com/dotnet/roslyn/issues/13149")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestPartialClass2() { await TestAllOptionsOffAsync( @"using System; public abstract class Base { public abstract void Dispose(); } partial class [|A|] { } partial class A : Base { }", @"using System; public abstract class Base { public abstract void Dispose(); } partial class A { public override void Dispose() { throw new NotImplementedException(); } } partial class A : Base { }"); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Method1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract void M(int x); } class [|T|] : A { }", @"abstract class A { public abstract void M(int x); } class T : A { public override void M(int x) => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; } } class T : A { public override int M => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { set; } } class T : A { public override int M { set { throw new System.NotImplementedException(); } } }", options: OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption.None), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.None))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; set; } } class T : A { public override int M { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", options: OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption.None), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.None))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexers1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { get; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { get; } } class T : A { public override int this[int i] => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexer3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { set; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { set; } } class T : A { public override int this[int i] { set { throw new System.NotImplementedException(); } } }", options: OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption.None), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.None))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexer4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { get; set; } } class T : A { public override int this[int i] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", options: OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption.None), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.None))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; } } class T : A { public override int M { get => throw new System.NotImplementedException(); } }", options: OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never, NotificationOption.None), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible, NotificationOption.None))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { set; } } class T : A { public override int M { set => throw new System.NotImplementedException(); } }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; set; } } class T : A { public override int M { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement)); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestWithGroupingOff1() { await TestInRegularAndScriptAsync( @"abstract class Base { public abstract int Prop { get; } } class [|Derived|] : Base { void Foo() { } }", @"abstract class Base { public abstract int Prop { get; } } class Derived : Base { void Foo() { } public override int Prop => throw new System.NotImplementedException(); }", options: Option(ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd)); } [WorkItem(17274, "https://github.com/dotnet/roslyn/issues/17274")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestAddedUsingWithBanner1() { await TestInRegularAndScriptAsync( @"// Copyright ... using Microsoft.Win32; namespace My { public abstract class Foo { public abstract void Bar(System.Collections.Generic.List<object> values); } public class [|Foo2|] : Foo // Implement Abstract Class { } }", @"// Copyright ... using System.Collections.Generic; using Microsoft.Win32; namespace My { public abstract class Foo { public abstract void Bar(System.Collections.Generic.List<object> values); } public class Foo2 : Foo // Implement Abstract Class { public override void Bar(List<object> values) { throw new System.NotImplementedException(); } } }", ignoreTrivia: false); } [WorkItem(17562, "https://github.com/dotnet/roslyn/issues/17562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullableOptionalParameters() { await TestInRegularAndScriptAsync( @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class [|D|] : B { }", @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class D : B { public override void M1(int i = 0, string s = null, int? j = null, V v = default(V)) { throw new System.NotImplementedException(); } public override void M2<T>(T? i = null) { throw new System.NotImplementedException(); } }"); } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public sealed class GoTween : AbstractGoTween { // Tween specific properties public object target { get; private set; } // the target of the tweens public float delay { get; private set; } // delay before starting the actual animations private float _elapsedDelay; // total time delayed private bool _delayComplete; // once we complete the delay this gets set so we can reverse and play properly for the future public bool isFrom { get; private set; } // a value of true will make this a "from" tween private List<AbstractTweenProperty> _tweenPropertyList = new List<AbstractTweenProperty>( 2 ); private Type targetType; /// <summary> /// sets the ease type for all Tweens. this will overwrite the ease types for each Tween! /// </summary> private GoEaseType _easeType; public GoEaseType easeType { get { return _easeType; } set { _easeType = value; // change ease type of all existing tweens. for ( int k = 0; k < _tweenPropertyList.Count; ++k ) { AbstractTweenProperty tween = _tweenPropertyList[k]; tween.setEaseType (value); } } } /// <summary> /// sets the ease curve for all Tweens /// </summary> public AnimationCurve easeCurve { get; set; } /// <summary> /// initializes a new instance and sets up the details according to the config parameter /// </summary> public GoTween( object target, float duration, GoTweenConfig config, Action<AbstractGoTween> onComplete = null ) { // all tweens must be intialized to have a duration greater than zero. keep in mind that this will ensure // the tween occurs over two frames: the initialized value, and the final value. if you are looking for a // tween to reach the end of it's tween immediately, be sure to call complete() on it after creation. if( duration <= 0 ) { duration = float.Epsilon; Debug.LogError( "tween duration must be greater than 0. coerced to float.Epsilon." ); } // default to removing on complete autoRemoveOnComplete = true; // allow events by default allowEvents = true; // setup callback bools _didInit = false; _didBegin = false; // flag the onIterationStart event to fire. // as long as goTo is not called on this tween, the onIterationStart event will fire // as soon as the delay, if any, is completed. _fireIterationStart = true; this.target = target; this.targetType = target.GetType(); this.duration = duration; // copy the TweenConfig info over id = config.id; delay = config.delay; loopType = config.loopType; iterations = config.iterations; _easeType = config.easeType; easeCurve = config.easeCurve; updateType = config.propertyUpdateType; isFrom = config.isFrom; timeScale = config.timeScale; _onInit = config.onInitHandler; _onBegin = config.onBeginHandler; _onIterationStart = config.onIterationStartHandler; _onUpdate = config.onUpdateHandler; _onIterationEnd = config.onIterationEndHandler; _onComplete = config.onCompleteHandler; if( config.isPaused ) state = GoTweenState.Paused; // if onComplete is passed to the constructor it wins. it is left as the final param to allow an inline Action to be // set and maintain clean code (Actions always try to be the last param of a method) if( onComplete != null ) _onComplete = onComplete; // add all our properties for( var i = 0; i < config.tweenProperties.Count; ++i ) { var tweenProp = config.tweenProperties[i]; // if the tween property is initialized already it means it is being reused so we need to clone it if( tweenProp.isInitialized ) tweenProp = tweenProp.clone(); addTweenProperty( tweenProp ); } // calculate total duration if( iterations < 0 ) totalDuration = float.PositiveInfinity; else totalDuration = iterations * duration; } /// <summary> /// tick method. if it returns true it indicates the tween is complete /// </summary> public override bool update( float deltaTime ) { // properties are prepared only once on the first update of the tween. if ( !_didInit ) onInit(); // should we validate the target? if( Go.validateTargetObjectsEachTick ) { // This might seem to be overkill, but on the case of Transforms that // have been destroyed, target == null will return false, whereas // target.Equals(null) will return true. Otherwise we don't really // get the benefits of the nanny. if( target == null || target.Equals(null) ) { // if the target doesn't pass validation Debug.LogWarning( "target validation failed. destroying the tween to avoid errors. Target type: " + this.targetType ); autoRemoveOnComplete = true; return true; } } // we only fire the begin callback once per run. if ( !_didBegin ) onBegin(); // handle delay and return if we are still delaying if( !_delayComplete && _elapsedDelay < delay ) { // if we have a timeScale set we need to remove its influence so that delays are always in seconds if( timeScale != 0 ) _elapsedDelay += deltaTime / timeScale; // are we done delaying? if( _elapsedDelay >= delay ) _delayComplete = true; return false; } // loops only start once the delay has completed. if ( _fireIterationStart ) onIterationStart(); // base will calculate the proper elapsedTime, iterations, etc. base.update( deltaTime ); // if we are looping back on a PingPong loop var convertedElapsedTime = _isLoopingBackOnPingPong ? duration - _elapsedTime : _elapsedTime; //Debug.Log(string.Format("{0} : {1} -- {2}", _elapsedTime, convertedElapsedTime, _isLoopingBackOnPingPong ? "Y" : "N")); // update all properties for( var i = 0; i < _tweenPropertyList.Count; ++i ) _tweenPropertyList[i].tick( convertedElapsedTime ); onUpdate(); if ( _fireIterationEnd ) onIterationEnd(); if( state == GoTweenState.Complete ) { onComplete(); return true; // true if complete } return false; // false if not complete } /// <summary> /// we are valid if we have a target and at least one TweenProperty /// </summary> public override bool isValid() { return target != null; } /// <summary> /// adds the tween property if it passes validation and initializes the property /// </summary> public void addTweenProperty( AbstractTweenProperty tweenProp ) { // make sure the target is valid for this tween before adding if( tweenProp.validateTarget( target ) ) { // ensure we dont add two tweens of the same property so they dont fight if( _tweenPropertyList.Contains( tweenProp ) ) { Debug.Log( "not adding tween property because one already exists: " + tweenProp ); return; } _tweenPropertyList.Add( tweenProp ); tweenProp.init( this ); } else { Debug.Log( "tween failed to validate target: " + tweenProp ); } } public override bool removeTweenProperty( AbstractTweenProperty property ) { if( _tweenPropertyList.Contains( property ) ) { _tweenPropertyList.Remove( property ); return true; } return false; } public override bool containsTweenProperty( AbstractTweenProperty property ) { return _tweenPropertyList.Contains( property ); } public void clearTweenProperties() { _tweenPropertyList.Clear(); } public override List<AbstractTweenProperty> allTweenProperties() { return _tweenPropertyList; } #region AbstractTween overrides /// <summary> /// called only once the first update of a tween. /// </summary> protected override void onInit() { base.onInit(); for ( var i = 0; i < _tweenPropertyList.Count; ++i ) _tweenPropertyList[i].prepareForUse(); } /// <summary> /// removes the tween and cleans up its state /// </summary> public override void destroy() { base.destroy(); _tweenPropertyList.Clear(); target = null; } /// <summary> /// goes to the specified time clamping it from 0 to the total duration of the tween. if the tween is /// not playing it will be force updated to the time specified. /// </summary> public override void goTo( float time , bool skipDelay) { // handle delay, which is specific to Tweens if( skipDelay ) { _elapsedDelay = delay; } else { _elapsedDelay = Mathf.Min( time, delay ); time -= _elapsedDelay; } _delayComplete = _elapsedDelay >= delay; time = Mathf.Clamp( time, 0f, totalDuration ); // provide an early out for calling goto on the same time multiple times. if ( time == _totalElapsedTime ) return; // if we are doing a goTo at the "start" of the timeline, based on the isReversed variable, // allow the onBegin and onIterationStart callback to fire again. // we only allow the onIterationStart event callback to fire at the start of the timeline, // as doing a goTo(x) where x % duration == 0 will trigger the onIterationEnd before we // go to the start. if ( ( isReversed && time == totalDuration ) || ( !isReversed && time == 0f ) ) { _didBegin = false; _fireIterationStart = true; } else { _didBegin = true; _fireIterationStart = false; } // since we're doing a goTo, we want to stop this tween from remembering that it iterated. // this could cause issues if you caused the tween to complete an iteration and then goTo somewhere // else while still paused. _didIterateThisFrame = false; // force a time and completedIterations before we update _totalElapsedTime = time; _completedIterations = isReversed ? Mathf.CeilToInt( _totalElapsedTime / duration ) : Mathf.FloorToInt( _totalElapsedTime / duration ); update( 0 ); } /// <summary> /// completes the tween. sets the object to it's final position as if the tween completed normally. /// takes into effect if the tween was playing forward or reversed. /// </summary> public override void complete() { if( iterations < 0 ) return; // set delayComplete so we get one last update in before we die (base will set the elapsed time for us) _delayComplete = true; base.complete(); } #endregion }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Internal; namespace Orleans.Runtime.Messaging { internal sealed class ConnectionManager { [ThreadStatic] private static uint nextConnection; private readonly ConcurrentDictionary<SiloAddress, ConnectionEntry> connections = new(); private readonly ConnectionOptions connectionOptions; private readonly ConnectionFactory connectionFactory; private readonly NetworkingTrace trace; private readonly CancellationTokenSource shutdownCancellation = new(); private readonly object lockObj = new object(); private readonly TaskCompletionSource<int> closedTaskCompletionSource = new(TaskCreationOptions.RunContinuationsAsynchronously); public ConnectionManager( IOptions<ConnectionOptions> connectionOptions, ConnectionFactory connectionFactory, NetworkingTrace trace) { this.connectionOptions = connectionOptions.Value; this.connectionFactory = connectionFactory; this.trace = trace; } public int ConnectionCount => connections.Sum(e => e.Value.Connections.Length); public Task Closed => this.closedTaskCompletionSource.Task; public List<SiloAddress> GetConnectedAddresses() => connections.Select(i => i.Key).ToList(); public ValueTask<Connection> GetConnection(SiloAddress endpoint) { if (this.connections.TryGetValue(endpoint, out var entry) && entry.NextConnection() is { } connection) { if (!entry.HasSufficientConnections(connectionOptions) && entry.PendingConnection is null) { this.GetConnectionAsync(endpoint).Ignore(); } // Return the existing connection. return new(connection); } // Start a new connection attempt since there are no suitable connections. return new(this.GetConnectionAsync(endpoint)); } public bool TryGetConnection(SiloAddress endpoint, out Connection connection) { if (this.connections.TryGetValue(endpoint, out var entry) && entry.NextConnection() is { } c) { connection = c; return true; } connection = null; return false; } private async Task<Connection> GetConnectionAsync(SiloAddress endpoint) { await Task.Yield(); while (true) { if (this.shutdownCancellation.IsCancellationRequested) { throw new OperationCanceledException("Shutting down"); } Task pendingAttempt; lock (this.lockObj) { var entry = this.GetOrCreateEntry(endpoint); entry.RemoveDefunct(); // If there are sufficient connections available then return an existing connection. if (entry.HasSufficientConnections(connectionOptions) && entry.NextConnection() is { } connection) { return connection; } var remainingDelay = entry.GetRemainingRetryDelay(connectionOptions); if (remainingDelay.Ticks > 0) { throw new ConnectionFailedException($"Unable to connect to {endpoint}, will retry after {remainingDelay.TotalMilliseconds}ms"); } // If there is no pending attempt then start one, otherwise the pending attempt will be awaited before reevaluating. pendingAttempt = entry.PendingConnection ??= ConnectAsync(endpoint, entry); } await pendingAttempt; } } private void OnConnectionFailed(ConnectionEntry entry) { var lastFailure = DateTime.UtcNow; lock (this.lockObj) { if (entry.LastFailure < lastFailure) entry.LastFailure = lastFailure; entry.PendingConnection = null; entry.RemoveDefunct(); } } public void OnConnected(SiloAddress address, Connection connection) => OnConnected(address, connection, null); private void OnConnected(SiloAddress address, Connection connection, ConnectionEntry entry) { lock (this.lockObj) { entry ??= GetOrCreateEntry(address); entry.Connections = entry.Connections.Contains(connection) ? entry.Connections : entry.Connections.Add(connection); entry.LastFailure = default; entry.PendingConnection = null; } this.trace.LogInformation("Connection {Connection} established with {Silo}", connection, address); } public void OnConnectionTerminated(SiloAddress address, Connection connection, Exception exception) { if (connection is null) return; lock (this.lockObj) { if (this.connections.TryGetValue(address, out var entry)) { entry.Connections = entry.Connections.Remove(connection); if (entry.Connections.Length == 0 && entry.PendingConnection is null) { // Remove the entire entry. this.connections.TryRemove(address, out _); } else { entry.RemoveDefunct(); } } } if (exception != null && !this.shutdownCancellation.IsCancellationRequested) { this.trace.LogWarning( exception, "Connection {Connection} terminated", connection); } else { this.trace.LogDebug( "Connection {Connection} closed", connection); } } private ConnectionEntry GetOrCreateEntry(SiloAddress address) => connections.GetOrAdd(address, _ => new()); private async Task<Connection> ConnectAsync(SiloAddress address, ConnectionEntry entry) { await Task.Yield(); CancellationTokenSource openConnectionCancellation = default; try { if (this.trace.IsEnabled(LogLevel.Information)) { this.trace.LogInformation( "Establishing connection to endpoint {EndPoint}", address); } // Cancel pending connection attempts either when the host terminates or after the configured time limit. openConnectionCancellation = CancellationTokenSource.CreateLinkedTokenSource(this.shutdownCancellation.Token, default); openConnectionCancellation.CancelAfter(this.connectionOptions.OpenConnectionTimeout); var connection = await this.connectionFactory.ConnectAsync(address, openConnectionCancellation.Token); if (this.trace.IsEnabled(LogLevel.Information)) { this.trace.LogInformation( "Connected to endpoint {EndPoint}", address); } this.StartConnection(address, connection); await connection.Initialized.WithCancellation(openConnectionCancellation.Token); this.OnConnected(address, connection, entry); return connection; } catch (Exception exception) { this.OnConnectionFailed(entry); this.trace.LogWarning( exception, "Connection attempt to endpoint {EndPoint} failed", address); if (exception is OperationCanceledException && openConnectionCancellation?.IsCancellationRequested == true && !shutdownCancellation.IsCancellationRequested) throw new ConnectionFailedException($"Connection attempt to endpoint {address} timed out after {connectionOptions.OpenConnectionTimeout}"); throw new ConnectionFailedException( $"Unable to connect to endpoint {address}. See {nameof(exception.InnerException)}", exception); } finally { openConnectionCancellation?.Dispose(); } } public async Task CloseAsync(SiloAddress endpoint) { ImmutableArray<Connection> connections; lock (this.lockObj) { if (!this.connections.TryGetValue(endpoint, out var entry)) { return; } connections = entry.Connections; if (entry.PendingConnection is null) { this.connections.TryRemove(endpoint, out _); } } if (connections.Length == 1) { await connections[0].CloseAsync(exception: null); } else if (!connections.IsEmpty) { var closeTasks = new List<Task>(); foreach (var connection in connections) { try { closeTasks.Add(connection.CloseAsync(exception: null)); } catch { } } await Task.WhenAll(closeTasks); } } public async Task Close(CancellationToken ct) { try { if (this.trace.IsEnabled(LogLevel.Information)) { this.trace.LogInformation("Shutting down connections"); } this.shutdownCancellation.Cancel(throwOnFirstException: false); var cycles = 0; for (var closeTasks = new List<Task>(); ; closeTasks.Clear()) { var pendingConnections = false; foreach (var kv in connections) { pendingConnections |= kv.Value.PendingConnection != null; foreach (var connection in kv.Value.Connections) { try { closeTasks.Add(connection.CloseAsync(exception: null)); } catch { } } } if (closeTasks.Count > 0) { await Task.WhenAny(Task.WhenAll(closeTasks), ct.WhenCancelled()); if (ct.IsCancellationRequested) break; } else if (!pendingConnections) break; await Task.Delay(10); if (++cycles > 100 && cycles % 500 == 0 && this.ConnectionCount is var remaining and > 0) { this.trace?.LogWarning("Waiting for {NumRemaining} connections to terminate", remaining); } } } catch (Exception exception) { this.trace?.LogWarning(exception, "Exception during shutdown"); } finally { this.closedTaskCompletionSource.TrySetResult(0); } } private void StartConnection(SiloAddress address, Connection connection) { ThreadPool.UnsafeQueueUserWorkItem(state => { var (t, address, connection) = ((ConnectionManager, SiloAddress, Connection))state; _ = t.RunConnectionAsync(address, connection); }, (this, address, connection)); } private async Task RunConnectionAsync(SiloAddress address, Connection connection) { Exception error = default; try { using (this.BeginConnectionScope(connection)) { await connection.Run(); } } catch (Exception exception) { error = exception; } finally { this.OnConnectionTerminated(address, connection, error); } } private IDisposable BeginConnectionScope(Connection connection) { if (this.trace.IsEnabled(LogLevel.Critical)) { return this.trace.BeginScope(new ConnectionLogScope(connection)); } return null; } private sealed class ConnectionEntry { public Task PendingConnection { get; set; } public DateTime LastFailure { get; set; } public ImmutableArray<Connection> Connections { get; set; } = ImmutableArray<Connection>.Empty; public TimeSpan GetRemainingRetryDelay(ConnectionOptions options) { var lastFailure = this.LastFailure; if (lastFailure.Ticks > 0) { var retryAfter = lastFailure + options.ConnectionRetryDelay; var remainingDelay = retryAfter - DateTime.UtcNow; if (remainingDelay.Ticks > 0) { return remainingDelay; } } return default; } public bool HasSufficientConnections(ConnectionOptions options) => Connections.Length >= options.ConnectionsPerEndpoint; public Connection NextConnection() { var connections = this.Connections; if (connections.IsEmpty) { return null; } var result = connections.Length == 1 ? connections[0] : connections[(int)(++nextConnection % (uint)connections.Length)]; return result.IsValid ? result : null; } public void RemoveDefunct() => Connections = Connections.RemoveAll(c => !c.IsValid); } } }
using System.Collections; using UnityEngine; namespace System.Threading.Tasks { public static class Extensions { public static Task RunTask(this MonoBehaviour behaviour, IEnumerator coroutine, float delay = 0) { var scheduler = TaskScheduler.FromMonoBehaviour(behaviour); var cr = delay <= 0? coroutine : RunCoroutineDelayed(coroutine, delay); return Task.Factory.StartNew(cr, scheduler); } static IEnumerator RunCoroutineDelayed(IEnumerator coroutine, float delay) { yield return new WaitForSeconds(delay); yield return coroutine; } public static Task RunTask(this MonoBehaviour behaviour, Func<TaskCompletionSource, IEnumerator> coroutine) { var scheduler = TaskScheduler.FromMonoBehaviour(behaviour); return Task.Factory.StartNew(coroutine, scheduler); } public static Task<T> RunTask<T>(this MonoBehaviour behaviour, Func<TaskCompletionSource<T>, IEnumerator> coroutine) { var scheduler = TaskScheduler.FromMonoBehaviour(behaviour); return Task.Factory.StartNew<T>(coroutine, scheduler); } #if !UNITY_5_2 public static TaskYieldInstruction ToYieldInstruction(this Task task) { return new TaskYieldInstruction(task); } public static TaskYieldInstruction<T> ToYieldInstruction<T>(this Task<T> task) { return new TaskYieldInstruction<T>(task); } #endif public static IEnumerator ToIEnumerator(this Task task) { while (!task.IsCompleted) yield return null; } public static Task ThenComplete(this Task task, TaskCompletionSource tcs) { return task.ContinueWith(t => { if (t.Status == TaskStatus.RanToCompletion) { tcs.TrySetCompleted(); } else if (t.Status == TaskStatus.Canceled) { tcs.TrySetCanceled((OperationCanceledException)t.Error); } else if (t.Status == TaskStatus.Faulted) { tcs.TrySetException(t.Error); } else { throw new NotImplementedException(); } t.AssertCompletion(); }); } public static Task<T> ThenComplete<T>(this Task<T> task, TaskCompletionSource<T> tcs) { return task.ContinueWith<T>((Task<T> t) => { if (t.Status == TaskStatus.RanToCompletion) { tcs.TrySetCompleted(t.Result); } else if (t.Status == TaskStatus.Canceled) { tcs.TrySetCanceled((OperationCanceledException)t.Error); } else if (t.Status == TaskStatus.Faulted) { tcs.TrySetException(t.Error); } else { throw new NotImplementedException(); } return t.Result; }); } public static bool SetFailure(this Task task, TaskCompletionSource tcs) { if (task.Status == TaskStatus.Canceled) { tcs.TrySetCanceled(task.Error as System.OperationCanceledException); return true; } if (task.Status == TaskStatus.Faulted) { tcs.TrySetException(task.Error); return true; } return false; } public static Task ContinueWithCR(this Task task, Func<Task, IEnumerator> sequence, TaskScheduler scheduler = null) { var t = new TaskCompletionSource(); t.Task.autoComplete = true; t.Task.scheduler = scheduler ?? task.scheduler ?? TaskScheduler.Current; ((ITaskCompletionSourceController)task.source).ContinueWith(tcs => { t.Task.userCoroutine = sequence(tcs.Task); t.Task.scheduler.QueueTask(t.Task); }); return t.Task; } public static Task ContinueWithCR(this Task task, Func<TaskCompletionSource, Task, IEnumerator> sequence, TaskScheduler scheduler = null) { var t = new TaskCompletionSource(); t.Task.scheduler = scheduler ?? task.scheduler ?? TaskScheduler.Current; ((ITaskCompletionSourceController)task.source).ContinueWith(tcs => { t.Task.userCoroutine = sequence(t, tcs.Task); t.Task.scheduler.QueueTask(t.Task); }); return t.Task; } public static Task<T> ContinueWithCR<T>(this Task task, Func<TaskCompletionSource<T>, Task, IEnumerator> sequence, TaskScheduler scheduler = null) { var t = new TaskCompletionSource<T>(); t.Task.scheduler = scheduler ?? task.scheduler ?? TaskScheduler.Current; ((ITaskCompletionSourceController)task.source).ContinueWith(tcs => { t.Task.userCoroutine = sequence(t, tcs.Task); t.Task.scheduler.QueueTask(t.Task); }); return t.Task; } public static Task ContinueWithCR<T>(this Task<T> task, Func<Task<T>, IEnumerator> sequence, TaskScheduler scheduler = null) { return ((Task)task).ContinueWithCR(s => sequence((Task<T>)s), scheduler); } public static Task ContinueWithCR<T>(this Task<T> task, Func<TaskCompletionSource, Task<T>, IEnumerator> sequence, TaskScheduler scheduler = null) { return ((Task)task).ContinueWithCR((s, t) => sequence(s, (Task<T>)t), scheduler); } public static Task<TR> ContinueWithCR<T, TR>(this Task<T> task, Func<TaskCompletionSource<TR>, Task<T>, IEnumerator> sequence, TaskScheduler scheduler = null) { return ((Task)task).ContinueWithCR<TR>((s, t) => sequence(s, (Task<T>)t), scheduler); } public static IEnumerator Wait(this Task task, string log = null, float timeOut = -1, bool ignoreErrors = false) { var toWait = timeOut < 0? task : task.TimeOut(TimeSpan.FromSeconds(timeOut), log + " Timed out"); if (log != null) { toWait = toWait.Log(log); } yield return toWait; if (!ignoreErrors) { toWait.AssertCompletion(); } } public static Task Log(this Task task, string name) { Debug.Log(name + " Started"); return LogResult(task, name, false); } public static Task<T> Log<T>(this Task<T> task, string name) { Debug.Log(name + " Started"); return LogResult(task, name, false); } public static Task LogResult(this Task task, string name, bool errorsOnly = false) { return task.ContinueWith(t => { if (!errorsOnly || t.Status != TaskStatus.RanToCompletion) { LogTaskResult(t, name); } t.AssertCompletion(); }); } public static Task<T> LogResult<T>(this Task<T> task, string name, bool errorsOnly = false) { return task.ContinueWith<T>(t => { if (!errorsOnly || t.Status != TaskStatus.RanToCompletion) { LogTaskResult(task, name); } return t.Result; }); } static void LogTaskResult<T>(Task<T> task, string name) { if (task.IsFaulted) { Debug.LogError(name + " Completed - " + task.Status + " - " + task.Error); } else { Debug.Log(name + " Completed - " + task.Status + " - " + (task.Error != null? task.Error.ToString() : Convert.ToString(task.Result))); } } static void LogTaskResult(Task task, string name) { if (task.IsFaulted) { Debug.LogError(name + " Completed - " + task.Status + " - " + task.Error); } else { Debug.Log(name + " Completed - " + task.Status + (task.Error != null? " - " + task.Error : "")); } } public static Task TimeOut(this Task t, float seconds, string message = null) { return Task.Factory.StartNew(TimeOutCR(t, TimeSpan.FromSeconds(seconds), message)); } public static Task TimeOut(this Task t, TimeSpan duration, string message = null) { return Task.Factory.StartNew(TimeOutCR(t, duration, message)); } static IEnumerator TimeOutCR(Task t, TimeSpan duration, string message) { var cancellation = new CancellationTokenSource(); var normalizedDuration = duration < TimeSpan.Zero? TimeSpan.FromMilliseconds(-1) : duration; var timeout = Task.Delay(normalizedDuration, cancellation.Token); var any = Task.WhenAny(t, timeout); yield return any; cancellation.Cancel(); if (any.Result == timeout) { throw new TimeoutException(message ?? "Task timed out"); } t.AssertCompletion(); } } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.3.10.1 Abstract superclass for PDUs relating to minefields. COMPLETE /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(EntityID))] [XmlInclude(typeof(EntityType))] [XmlInclude(typeof(Vector3Double))] [XmlInclude(typeof(Orientation))] [XmlInclude(typeof(Point))] [XmlInclude(typeof(EntityType))] public partial class MinefieldStatePdu : MinefieldFamilyPdu, IEquatable<MinefieldStatePdu> { /// <summary> /// Minefield ID /// </summary> private EntityID _minefieldID = new EntityID(); /// <summary> /// Minefield sequence /// </summary> private ushort _minefieldSequence; /// <summary> /// force ID /// </summary> private byte _forceID; /// <summary> /// Number of permieter points /// </summary> private byte _numberOfPerimeterPoints; /// <summary> /// type of minefield /// </summary> private EntityType _minefieldType = new EntityType(); /// <summary> /// how many mine types /// </summary> private ushort _numberOfMineTypes; /// <summary> /// location of minefield in world coords /// </summary> private Vector3Double _minefieldLocation = new Vector3Double(); /// <summary> /// orientation of minefield /// </summary> private Orientation _minefieldOrientation = new Orientation(); /// <summary> /// appearance bitflags /// </summary> private ushort _appearance; /// <summary> /// protocolMode /// </summary> private ushort _protocolMode; /// <summary> /// perimeter points for the minefield /// </summary> private List<Point> _perimeterPoints = new List<Point>(); /// <summary> /// Type of mines /// </summary> private List<EntityType> _mineType = new List<EntityType>(); /// <summary> /// Initializes a new instance of the <see cref="MinefieldStatePdu"/> class. /// </summary> public MinefieldStatePdu() { PduType = (byte)37; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(MinefieldStatePdu left, MinefieldStatePdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(MinefieldStatePdu left, MinefieldStatePdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += this._minefieldID.GetMarshalledSize(); // this._minefieldID marshalSize += 2; // this._minefieldSequence marshalSize += 1; // this._forceID marshalSize += 1; // this._numberOfPerimeterPoints marshalSize += this._minefieldType.GetMarshalledSize(); // this._minefieldType marshalSize += 2; // this._numberOfMineTypes marshalSize += this._minefieldLocation.GetMarshalledSize(); // this._minefieldLocation marshalSize += this._minefieldOrientation.GetMarshalledSize(); // this._minefieldOrientation marshalSize += 2; // this._appearance marshalSize += 2; // this._protocolMode for (int idx = 0; idx < this._perimeterPoints.Count; idx++) { Point listElement = (Point)this._perimeterPoints[idx]; marshalSize += listElement.GetMarshalledSize(); } for (int idx = 0; idx < this._mineType.Count; idx++) { EntityType listElement = (EntityType)this._mineType[idx]; marshalSize += listElement.GetMarshalledSize(); } return marshalSize; } /// <summary> /// Gets or sets the Minefield ID /// </summary> [XmlElement(Type = typeof(EntityID), ElementName = "minefieldID")] public EntityID MinefieldID { get { return this._minefieldID; } set { this._minefieldID = value; } } /// <summary> /// Gets or sets the Minefield sequence /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "minefieldSequence")] public ushort MinefieldSequence { get { return this._minefieldSequence; } set { this._minefieldSequence = value; } } /// <summary> /// Gets or sets the force ID /// </summary> [XmlElement(Type = typeof(byte), ElementName = "forceID")] public byte ForceID { get { return this._forceID; } set { this._forceID = value; } } /// <summary> /// Gets or sets the Number of permieter points /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfPerimeterPoints method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(byte), ElementName = "numberOfPerimeterPoints")] public byte NumberOfPerimeterPoints { get { return this._numberOfPerimeterPoints; } set { this._numberOfPerimeterPoints = value; } } /// <summary> /// Gets or sets the type of minefield /// </summary> [XmlElement(Type = typeof(EntityType), ElementName = "minefieldType")] public EntityType MinefieldType { get { return this._minefieldType; } set { this._minefieldType = value; } } /// <summary> /// Gets or sets the how many mine types /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfMineTypes method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(ushort), ElementName = "numberOfMineTypes")] public ushort NumberOfMineTypes { get { return this._numberOfMineTypes; } set { this._numberOfMineTypes = value; } } /// <summary> /// Gets or sets the location of minefield in world coords /// </summary> [XmlElement(Type = typeof(Vector3Double), ElementName = "minefieldLocation")] public Vector3Double MinefieldLocation { get { return this._minefieldLocation; } set { this._minefieldLocation = value; } } /// <summary> /// Gets or sets the orientation of minefield /// </summary> [XmlElement(Type = typeof(Orientation), ElementName = "minefieldOrientation")] public Orientation MinefieldOrientation { get { return this._minefieldOrientation; } set { this._minefieldOrientation = value; } } /// <summary> /// Gets or sets the appearance bitflags /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "appearance")] public ushort Appearance { get { return this._appearance; } set { this._appearance = value; } } /// <summary> /// Gets or sets the protocolMode /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "protocolMode")] public ushort ProtocolMode { get { return this._protocolMode; } set { this._protocolMode = value; } } /// <summary> /// Gets the perimeter points for the minefield /// </summary> [XmlElement(ElementName = "perimeterPointsList", Type = typeof(List<Point>))] public List<Point> PerimeterPoints { get { return this._perimeterPoints; } } /// <summary> /// Gets the Type of mines /// </summary> [XmlElement(ElementName = "mineTypeList", Type = typeof(List<EntityType>))] public List<EntityType> MineType { get { return this._mineType; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { this._minefieldID.Marshal(dos); dos.WriteUnsignedShort((ushort)this._minefieldSequence); dos.WriteUnsignedByte((byte)this._forceID); dos.WriteUnsignedByte((byte)this._perimeterPoints.Count); this._minefieldType.Marshal(dos); dos.WriteUnsignedShort((ushort)this._mineType.Count); this._minefieldLocation.Marshal(dos); this._minefieldOrientation.Marshal(dos); dos.WriteUnsignedShort((ushort)this._appearance); dos.WriteUnsignedShort((ushort)this._protocolMode); for (int idx = 0; idx < this._perimeterPoints.Count; idx++) { Point aPoint = (Point)this._perimeterPoints[idx]; aPoint.Marshal(dos); } for (int idx = 0; idx < this._mineType.Count; idx++) { EntityType aEntityType = (EntityType)this._mineType[idx]; aEntityType.Marshal(dos); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._minefieldID.Unmarshal(dis); this._minefieldSequence = dis.ReadUnsignedShort(); this._forceID = dis.ReadUnsignedByte(); this._numberOfPerimeterPoints = dis.ReadUnsignedByte(); this._minefieldType.Unmarshal(dis); this._numberOfMineTypes = dis.ReadUnsignedShort(); this._minefieldLocation.Unmarshal(dis); this._minefieldOrientation.Unmarshal(dis); this._appearance = dis.ReadUnsignedShort(); this._protocolMode = dis.ReadUnsignedShort(); for (int idx = 0; idx < this.NumberOfPerimeterPoints; idx++) { Point anX = new Point(); anX.Unmarshal(dis); this._perimeterPoints.Add(anX); } for (int idx = 0; idx < this.NumberOfMineTypes; idx++) { EntityType anX = new EntityType(); anX.Unmarshal(dis); this._mineType.Add(anX); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<MinefieldStatePdu>"); base.Reflection(sb); try { sb.AppendLine("<minefieldID>"); this._minefieldID.Reflection(sb); sb.AppendLine("</minefieldID>"); sb.AppendLine("<minefieldSequence type=\"ushort\">" + this._minefieldSequence.ToString(CultureInfo.InvariantCulture) + "</minefieldSequence>"); sb.AppendLine("<forceID type=\"byte\">" + this._forceID.ToString(CultureInfo.InvariantCulture) + "</forceID>"); sb.AppendLine("<perimeterPoints type=\"byte\">" + this._perimeterPoints.Count.ToString(CultureInfo.InvariantCulture) + "</perimeterPoints>"); sb.AppendLine("<minefieldType>"); this._minefieldType.Reflection(sb); sb.AppendLine("</minefieldType>"); sb.AppendLine("<mineType type=\"ushort\">" + this._mineType.Count.ToString(CultureInfo.InvariantCulture) + "</mineType>"); sb.AppendLine("<minefieldLocation>"); this._minefieldLocation.Reflection(sb); sb.AppendLine("</minefieldLocation>"); sb.AppendLine("<minefieldOrientation>"); this._minefieldOrientation.Reflection(sb); sb.AppendLine("</minefieldOrientation>"); sb.AppendLine("<appearance type=\"ushort\">" + this._appearance.ToString(CultureInfo.InvariantCulture) + "</appearance>"); sb.AppendLine("<protocolMode type=\"ushort\">" + this._protocolMode.ToString(CultureInfo.InvariantCulture) + "</protocolMode>"); for (int idx = 0; idx < this._perimeterPoints.Count; idx++) { sb.AppendLine("<perimeterPoints" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"Point\">"); Point aPoint = (Point)this._perimeterPoints[idx]; aPoint.Reflection(sb); sb.AppendLine("</perimeterPoints" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } for (int idx = 0; idx < this._mineType.Count; idx++) { sb.AppendLine("<mineType" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"EntityType\">"); EntityType aEntityType = (EntityType)this._mineType[idx]; aEntityType.Reflection(sb); sb.AppendLine("</mineType" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</MinefieldStatePdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as MinefieldStatePdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(MinefieldStatePdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (!this._minefieldID.Equals(obj._minefieldID)) { ivarsEqual = false; } if (this._minefieldSequence != obj._minefieldSequence) { ivarsEqual = false; } if (this._forceID != obj._forceID) { ivarsEqual = false; } if (this._numberOfPerimeterPoints != obj._numberOfPerimeterPoints) { ivarsEqual = false; } if (!this._minefieldType.Equals(obj._minefieldType)) { ivarsEqual = false; } if (this._numberOfMineTypes != obj._numberOfMineTypes) { ivarsEqual = false; } if (!this._minefieldLocation.Equals(obj._minefieldLocation)) { ivarsEqual = false; } if (!this._minefieldOrientation.Equals(obj._minefieldOrientation)) { ivarsEqual = false; } if (this._appearance != obj._appearance) { ivarsEqual = false; } if (this._protocolMode != obj._protocolMode) { ivarsEqual = false; } if (this._perimeterPoints.Count != obj._perimeterPoints.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._perimeterPoints.Count; idx++) { if (!this._perimeterPoints[idx].Equals(obj._perimeterPoints[idx])) { ivarsEqual = false; } } } if (this._mineType.Count != obj._mineType.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._mineType.Count; idx++) { if (!this._mineType[idx].Equals(obj._mineType[idx])) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._minefieldID.GetHashCode(); result = GenerateHash(result) ^ this._minefieldSequence.GetHashCode(); result = GenerateHash(result) ^ this._forceID.GetHashCode(); result = GenerateHash(result) ^ this._numberOfPerimeterPoints.GetHashCode(); result = GenerateHash(result) ^ this._minefieldType.GetHashCode(); result = GenerateHash(result) ^ this._numberOfMineTypes.GetHashCode(); result = GenerateHash(result) ^ this._minefieldLocation.GetHashCode(); result = GenerateHash(result) ^ this._minefieldOrientation.GetHashCode(); result = GenerateHash(result) ^ this._appearance.GetHashCode(); result = GenerateHash(result) ^ this._protocolMode.GetHashCode(); if (this._perimeterPoints.Count > 0) { for (int idx = 0; idx < this._perimeterPoints.Count; idx++) { result = GenerateHash(result) ^ this._perimeterPoints[idx].GetHashCode(); } } if (this._mineType.Count > 0) { for (int idx = 0; idx < this._mineType.Count; idx++) { result = GenerateHash(result) ^ this._mineType[idx].GetHashCode(); } } return result; } } }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; //#define ConfigTrace using Microsoft.VisualStudio.Shell.Interop; using MSBuildConstruction = Microsoft.Build.Construction; using MSBuildExecution = Microsoft.Build.Execution; namespace Microsoft.VisualStudioTools.Project { [ComVisible(true)] internal abstract class ProjectConfig : IVsCfg, IVsProjectCfg, IVsProjectCfg2, IVsProjectFlavorCfg, IVsDebuggableProjectCfg, ISpecifyPropertyPages, IVsSpecifyProjectDesignerPages, IVsCfgBrowseObject { internal const string Debug = "Debug"; internal const string AnyCPU = "AnyCPU"; private ProjectNode project; private string configName; private MSBuildExecution.ProjectInstance currentConfig; private IVsProjectFlavorCfg flavoredCfg; private List<OutputGroup> outputGroups; private BuildableProjectConfig buildableCfg; #region properties internal ProjectNode ProjectMgr { get { return this.project; } } public string ConfigName { get { return this.configName; } set { this.configName = value; } } internal IList<OutputGroup> OutputGroups { get { if (null == this.outputGroups) { // Initialize output groups this.outputGroups = new List<OutputGroup>(); // If the project is not buildable (no CoreCompile target) // then don't bother getting the output groups. if (this.project.BuildProject != null && this.project.BuildProject.Targets.ContainsKey("CoreCompile")) { // Get the list of group names from the project. // The main reason we get it from the project is to make it easier for someone to modify // it by simply overriding that method and providing the correct MSBuild target(s). IList<KeyValuePair<string, string>> groupNames = project.GetOutputGroupNames(); if (groupNames != null) { // Populate the output array foreach (KeyValuePair<string, string> group in groupNames) { OutputGroup outputGroup = CreateOutputGroup(project, group); this.outputGroups.Add(outputGroup); } } } } return this.outputGroups; } } #endregion #region ctors internal ProjectConfig(ProjectNode project, string configuration) { this.project = project; this.configName = configuration; var flavoredCfgProvider = ProjectMgr.GetOuterInterface<IVsProjectFlavorCfgProvider>(); Utilities.ArgumentNotNull("flavoredCfgProvider", flavoredCfgProvider); ErrorHandler.ThrowOnFailure(flavoredCfgProvider.CreateProjectFlavorCfg(this, out flavoredCfg)); Utilities.ArgumentNotNull("flavoredCfg", flavoredCfg); // if the flavored object support XML fragment, initialize it IPersistXMLFragment persistXML = flavoredCfg as IPersistXMLFragment; if (null != persistXML) { this.project.LoadXmlFragment(persistXML, configName); } } #endregion #region methods internal virtual OutputGroup CreateOutputGroup(ProjectNode project, KeyValuePair<string, string> group) { OutputGroup outputGroup = new OutputGroup(group.Key, group.Value, project, this); return outputGroup; } public void PrepareBuild(bool clean) { project.PrepareBuild(this.configName, clean); } public virtual string GetConfigurationProperty(string propertyName, bool resetCache) { MSBuildExecution.ProjectPropertyInstance property = GetMsBuildProperty(propertyName, resetCache); if (property == null) return null; return property.EvaluatedValue; } public virtual void SetConfigurationProperty(string propertyName, string propertyValue) { if (!this.project.QueryEditProjectFile(false)) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } string condition = String.Format(CultureInfo.InvariantCulture, ConfigProvider.configString, this.ConfigName, this.PlatformName); SetPropertyUnderCondition(propertyName, propertyValue, condition); // property cache will need to be updated this.currentConfig = null; return; } /// <summary> /// Emulates the behavior of SetProperty(name, value, condition) on the old MSBuild object model. /// This finds a property group with the specified condition (or creates one if necessary) then sets the property in there. /// </summary> private void SetPropertyUnderCondition(string propertyName, string propertyValue, string condition) { string conditionTrimmed = (condition == null) ? String.Empty : condition.Trim(); if (conditionTrimmed.Length == 0) { this.project.BuildProject.SetProperty(propertyName, propertyValue); return; } // New OM doesn't have a convenient equivalent for setting a property with a particular property group condition. // So do it ourselves. MSBuildConstruction.ProjectPropertyGroupElement newGroup = null; foreach (MSBuildConstruction.ProjectPropertyGroupElement group in this.project.BuildProject.Xml.PropertyGroups) { if (String.Equals(group.Condition.Trim(), conditionTrimmed, StringComparison.OrdinalIgnoreCase)) { newGroup = group; break; } } if (newGroup == null) { newGroup = this.project.BuildProject.Xml.AddPropertyGroup(); // Adds after last existing PG, else at start of project newGroup.Condition = condition; } foreach (MSBuildConstruction.ProjectPropertyElement property in newGroup.PropertiesReversed) // If there's dupes, pick the last one so we win { if (String.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase) && property.Condition.Length == 0) { property.Value = propertyValue; return; } } newGroup.AddProperty(propertyName, propertyValue); } /// <summary> /// If flavored, and if the flavor config can be dirty, ask it if it is dirty /// </summary> /// <param name="storageType">Project file or user file</param> /// <returns>0 = not dirty</returns> internal int IsFlavorDirty(_PersistStorageType storageType) { int isDirty = 0; if (this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment) { ErrorHandler.ThrowOnFailure(((IPersistXMLFragment)this.flavoredCfg).IsFragmentDirty((uint)storageType, out isDirty)); } return isDirty; } /// <summary> /// If flavored, ask the flavor if it wants to provide an XML fragment /// </summary> /// <param name="flavor">Guid of the flavor</param> /// <param name="storageType">Project file or user file</param> /// <param name="fragment">Fragment that the flavor wants to save</param> /// <returns>HRESULT</returns> internal int GetXmlFragment(Guid flavor, _PersistStorageType storageType, out string fragment) { fragment = null; int hr = VSConstants.S_OK; if (this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment) { Guid flavorGuid = flavor; hr = ((IPersistXMLFragment)this.flavoredCfg).Save(ref flavorGuid, (uint)storageType, out fragment, 1); } return hr; } #endregion #region IVsSpecifyPropertyPages public void GetPages(CAUUID[] pages) { this.GetCfgPropertyPages(pages); } #endregion #region IVsSpecifyProjectDesignerPages /// <summary> /// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration dependent. /// </summary> /// <param name="pages">The pages to return.</param> /// <returns>VSConstants.S_OK</returns> public virtual int GetProjectDesignerPages(CAUUID[] pages) { this.GetCfgPropertyPages(pages); return VSConstants.S_OK; } #endregion #region IVsCfg methods /// <summary> /// The display name is a two part item /// first part is the config name, 2nd part is the platform name /// </summary> public virtual int get_DisplayName(out string name) { name = DisplayName; return VSConstants.S_OK; } private string PlatformName { get { string[] platform = new string[1]; uint[] actual = new uint[1]; IVsCfgProvider provider; ErrorHandler.ThrowOnFailure(project.GetCfgProvider(out provider)); ErrorHandler.ThrowOnFailure(((IVsCfgProvider2)provider).GetPlatformNames(1, platform, actual)); return platform[0]; } } private string DisplayName { get { string name; string[] platform = new string[1]; uint[] actual = new uint[1]; name = this.configName; // currently, we only support one platform, so just add it.. IVsCfgProvider provider; ErrorHandler.ThrowOnFailure(project.GetCfgProvider(out provider)); ErrorHandler.ThrowOnFailure(((IVsCfgProvider2)provider).GetPlatformNames(1, platform, actual)); if (!string.IsNullOrEmpty(platform[0])) { name += "|" + platform[0]; } return name; } } public virtual int get_IsDebugOnly(out int fDebug) { fDebug = 0; if (this.configName == "Debug") { fDebug = 1; } return VSConstants.S_OK; } public virtual int get_IsReleaseOnly(out int fRelease) { fRelease = 0; if (this.configName == "Release") { fRelease = 1; } return VSConstants.S_OK; } #endregion #region IVsProjectCfg methods public virtual int EnumOutputs(out IVsEnumOutputs eo) { eo = null; return VSConstants.E_NOTIMPL; } public virtual int get_BuildableProjectCfg(out IVsBuildableProjectCfg pb) { if (project.BuildProject == null || !project.BuildProject.Targets.ContainsKey("CoreCompile")) { // The project is not buildable, so don't return a config. This // will hide the 'Build' commands from the VS UI. pb = null; return VSConstants.E_NOTIMPL; } if (buildableCfg == null) { buildableCfg = new BuildableProjectConfig(this); } pb = buildableCfg; return VSConstants.S_OK; } public virtual int get_CanonicalName(out string name) { name = configName; return VSConstants.S_OK; } public virtual int get_IsPackaged(out int pkgd) { pkgd = 0; return VSConstants.S_OK; } public virtual int get_IsSpecifyingOutputSupported(out int f) { f = 1; return VSConstants.S_OK; } public virtual int get_Platform(out Guid platform) { platform = Guid.Empty; return VSConstants.E_NOTIMPL; } public virtual int get_ProjectCfgProvider(out IVsProjectCfgProvider p) { p = null; IVsCfgProvider cfgProvider = null; this.project.GetCfgProvider(out cfgProvider); if (cfgProvider != null) { p = cfgProvider as IVsProjectCfgProvider; } return (null == p) ? VSConstants.E_NOTIMPL : VSConstants.S_OK; } public virtual int get_RootURL(out string root) { root = null; return VSConstants.S_OK; } public virtual int get_TargetCodePage(out uint target) { target = (uint)System.Text.Encoding.Default.CodePage; return VSConstants.S_OK; } public virtual int get_UpdateSequenceNumber(ULARGE_INTEGER[] li) { Utilities.ArgumentNotNull("li", li); li[0] = new ULARGE_INTEGER(); li[0].QuadPart = 0; return VSConstants.S_OK; } public virtual int OpenOutput(string name, out IVsOutput output) { output = null; return VSConstants.E_NOTIMPL; } #endregion #region IVsProjectCfg2 Members public virtual int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup) { ppIVsOutputGroup = null; // Search through our list of groups to find the one they are looking forgroupName foreach (OutputGroup group in OutputGroups) { string groupName; group.get_CanonicalName(out groupName); if (String.Compare(groupName, szCanonicalName, StringComparison.OrdinalIgnoreCase) == 0) { ppIVsOutputGroup = group; break; } } return (ppIVsOutputGroup != null) ? VSConstants.S_OK : VSConstants.E_FAIL; } public virtual int OutputsRequireAppRoot(out int pfRequiresAppRoot) { pfRequiresAppRoot = 0; return VSConstants.E_NOTIMPL; } public virtual int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg) { // Delegate to the flavored configuration (to enable a flavor to take control) // Since we can be asked for Configuration we don't support, avoid throwing and return the HRESULT directly int hr = flavoredCfg.get_CfgType(ref iidCfg, out ppCfg); return hr; } public virtual int get_IsPrivate(out int pfPrivate) { pfPrivate = 0; return VSConstants.S_OK; } public virtual int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual) { // Are they only asking for the number of groups? if (celt == 0) { if ((null == pcActual) || (0 == pcActual.Length)) { throw new ArgumentNullException("pcActual"); } pcActual[0] = (uint)OutputGroups.Count; return VSConstants.S_OK; } // Check that the array of output groups is not null if ((null == rgpcfg) || (rgpcfg.Length == 0)) { throw new ArgumentNullException("rgpcfg"); } // Fill the array with our output groups uint count = 0; foreach (OutputGroup group in OutputGroups) { if (rgpcfg.Length > count && celt > count && group != null) { rgpcfg[count] = group; ++count; } } if (pcActual != null && pcActual.Length > 0) pcActual[0] = count; // If the number asked for does not match the number returned, return S_FALSE return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE; } public virtual int get_VirtualRoot(out string pbstrVRoot) { pbstrVRoot = null; return VSConstants.E_NOTIMPL; } #endregion #region IVsDebuggableProjectCfg methods /// <summary> /// Called by the vs shell to start debugging (managed or unmanaged). /// Override this method to support other debug engines. /// </summary> /// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns> public abstract int DebugLaunch(uint grfLaunch); /// <summary> /// Determines whether the debugger can be launched, given the state of the launch flags. /// </summary> /// <param name="flags">Flags that determine the conditions under which to launch the debugger. /// For valid grfLaunch values, see __VSDBGLAUNCHFLAGS or __VSDBGLAUNCHFLAGS2.</param> /// <param name="fCanLaunch">true if the debugger can be launched, otherwise false</param> /// <returns>S_OK if the method succeeds, otherwise an error code</returns> public virtual int QueryDebugLaunch(uint flags, out int fCanLaunch) { string assembly = this.project.GetAssemblyName(this.ConfigName); fCanLaunch = (assembly != null && assembly.ToUpperInvariant().EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) ? 1 : 0; if (fCanLaunch == 0) { string property = GetConfigurationProperty("StartProgram", true); fCanLaunch = (property != null && property.Length > 0) ? 1 : 0; } return VSConstants.S_OK; } #endregion #region IVsCfgBrowseObject /// <summary> /// Maps back to the configuration corresponding to the browse object. /// </summary> /// <param name="cfg">The IVsCfg object represented by the browse object</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int GetCfg(out IVsCfg cfg) { cfg = this; return VSConstants.S_OK; } /// <summary> /// Maps back to the hierarchy or project item object corresponding to the browse object. /// </summary> /// <param name="hier">Reference to the hierarchy object.</param> /// <param name="itemid">Reference to the project item.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid) { Utilities.CheckNotNull(this.project); Utilities.CheckNotNull(this.project.NodeProperties); return this.project.NodeProperties.GetProjectItem(out hier, out itemid); } #endregion #region helper methods private MSBuildExecution.ProjectInstance GetCurrentConfig(bool resetCache = false) { if (resetCache || currentConfig == null) { // Get properties for current configuration from project file and cache it project.SetConfiguration(ConfigName); project.SetPlatformName(PlatformName); project.BuildProject.ReevaluateIfNecessary(); // Create a snapshot of the evaluated project in its current state currentConfig = project.BuildProject.CreateProjectInstance(); // Restore configuration project.SetCurrentConfiguration(); } return currentConfig; } private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache) { var current = GetCurrentConfig(resetCache); if (current == null) throw new Exception("Failed to retrieve properties"); // return property asked for return current.GetProperty(propertyName); } /// <summary> /// Retrieves the configuration dependent property pages. /// </summary> /// <param name="pages">The pages to return.</param> private void GetCfgPropertyPages(CAUUID[] pages) { // We do not check whether the supportsProjectDesigner is set to true on the ProjectNode. // We rely that the caller knows what to call on us. Utilities.ArgumentNotNull("pages", pages); if (pages.Length == 0) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), "pages"); } // Retrive the list of guids from hierarchy properties. // Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy string guidsList = String.Empty; IVsHierarchy hierarchy = project.GetOuterInterface<IVsHierarchy>(); object variant = null; ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList, out variant), new int[] { VSConstants.DISP_E_MEMBERNOTFOUND, VSConstants.E_NOTIMPL }); guidsList = (string)variant; Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList); if (guids == null || guids.Length == 0) { pages[0] = new CAUUID(); pages[0].cElems = 0; } else { pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids); } } internal virtual bool IsInputGroup(string groupName) { return groupName == "SourceFiles"; } private static DateTime? TryGetLastWriteTimeUtc(string path, Redirector output = null) { try { return File.GetLastWriteTimeUtc(path); } catch (UnauthorizedAccessException ex) { if (output != null) { output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message)); #if DEBUG output.WriteErrorLine(ex.ToString()); #endif } } catch (ArgumentException ex) { if (output != null) { output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message)); #if DEBUG output.WriteErrorLine(ex.ToString()); #endif } } catch (PathTooLongException ex) { if (output != null) { output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message)); #if DEBUG output.WriteErrorLine(ex.ToString()); #endif } } catch (NotSupportedException ex) { if (output != null) { output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message)); #if DEBUG output.WriteErrorLine(ex.ToString()); #endif } } return null; } internal virtual bool IsUpToDate() { var outputWindow = OutputWindowRedirector.GetGeneral(ProjectMgr.Site); #if DEBUG outputWindow.WriteLine(string.Format("Checking whether {0} needs to be rebuilt:", ProjectMgr.Caption)); #endif var latestInput = DateTime.MinValue; var earliestOutput = DateTime.MaxValue; bool mustRebuild = false; var allInputs = new HashSet<string>(OutputGroups .Where(g => IsInputGroup(g.Name)) .SelectMany(x => x.EnumerateOutputs()) .Select(input => input.CanonicalName), StringComparer.OrdinalIgnoreCase ); foreach (var group in OutputGroups.Where(g => !IsInputGroup(g.Name))) { foreach (var output in group.EnumerateOutputs()) { var path = output.CanonicalName; #if DEBUG var dt = TryGetLastWriteTimeUtc(path); outputWindow.WriteLine(string.Format( " Out: {0}: {1} [{2}]", group.Name, path, dt.HasValue ? dt.Value.ToString("s") : "err" )); #endif DateTime? modifiedTime; if (!File.Exists(path) || !(modifiedTime = TryGetLastWriteTimeUtc(path, outputWindow)).HasValue) { mustRebuild = true; break; } string inputPath; if (File.Exists(inputPath = output.GetMetadata("SourceFile"))) { var inputModifiedTime = TryGetLastWriteTimeUtc(inputPath, outputWindow); if (inputModifiedTime.HasValue && inputModifiedTime.Value > modifiedTime.Value) { mustRebuild = true; break; } else { continue; } } // output is an input, ignore it... if (allInputs.Contains(path)) { continue; } if (modifiedTime.Value < earliestOutput) { earliestOutput = modifiedTime.Value; } } if (mustRebuild) { // Early exit if we know we're going to have to rebuild break; } } if (mustRebuild) { #if DEBUG outputWindow.WriteLine(string.Format( "Rebuilding {0} because mustRebuild is true", ProjectMgr.Caption )); #endif return false; } foreach (var group in OutputGroups.Where(g => IsInputGroup(g.Name))) { foreach (var input in group.EnumerateOutputs()) { var path = input.CanonicalName; #if DEBUG var dt = TryGetLastWriteTimeUtc(path); outputWindow.WriteLine(string.Format( " In: {0}: {1} [{2}]", group.Name, path, dt.HasValue ? dt.Value.ToString("s") : "err" )); #endif if (!File.Exists(path)) { continue; } var modifiedTime = TryGetLastWriteTimeUtc(path, outputWindow); if (modifiedTime.HasValue && modifiedTime.Value > latestInput) { latestInput = modifiedTime.Value; if (earliestOutput < latestInput) { break; } } } if (earliestOutput < latestInput) { // Early exit if we know we're going to have to rebuild break; } } if (earliestOutput < latestInput) { #if DEBUG outputWindow.WriteLine(string.Format( "Rebuilding {0} because {1:s} < {2:s}", ProjectMgr.Caption, earliestOutput, latestInput )); #endif return false; } else { #if DEBUG outputWindow.WriteLine(string.Format( "Not rebuilding {0} because {1:s} >= {2:s}", ProjectMgr.Caption, earliestOutput, latestInput )); #endif return true; } } #endregion #region IVsProjectFlavorCfg Members /// <summary> /// This is called to let the flavored config let go /// of any reference it may still be holding to the base config /// </summary> /// <returns></returns> int IVsProjectFlavorCfg.Close() { // This is used to release the reference the flavored config is holding // on the base config, but in our scenario these 2 are the same object // so we have nothing to do here. return VSConstants.S_OK; } /// <summary> /// Actual implementation of get_CfgType. /// When not flavored or when the flavor delegate to use /// we end up creating the requested config if we support it. /// </summary> /// <param name="iidCfg">IID representing the type of config object we should create</param> /// <param name="ppCfg">Config object that the method created</param> /// <returns>HRESULT</returns> int IVsProjectFlavorCfg.get_CfgType(ref Guid iidCfg, out IntPtr ppCfg) { ppCfg = IntPtr.Zero; // See if this is an interface we support if (iidCfg == typeof(IVsDebuggableProjectCfg).GUID) { ppCfg = Marshal.GetComInterfaceForObject(this, typeof(IVsDebuggableProjectCfg)); } else if (iidCfg == typeof(IVsBuildableProjectCfg).GUID) { IVsBuildableProjectCfg buildableConfig; this.get_BuildableProjectCfg(out buildableConfig); // //In some cases we've intentionally shutdown the build options // If buildableConfig is null then don't try to get the BuildableProjectCfg interface // if (null != buildableConfig) { ppCfg = Marshal.GetComInterfaceForObject(buildableConfig, typeof(IVsBuildableProjectCfg)); } } // If not supported if (ppCfg == IntPtr.Zero) return VSConstants.E_NOINTERFACE; return VSConstants.S_OK; } #endregion } [ComVisible(true)] internal class BuildableProjectConfig : IVsBuildableProjectCfg { #region fields ProjectConfig config = null; EventSinkCollection callbacks = new EventSinkCollection(); #endregion #region ctors public BuildableProjectConfig(ProjectConfig config) { this.config = config; } #endregion #region IVsBuildableProjectCfg methods public virtual int AdviseBuildStatusCallback(IVsBuildStatusCallback callback, out uint cookie) { cookie = callbacks.Add(callback); return VSConstants.S_OK; } public virtual int get_ProjectCfg(out IVsProjectCfg p) { p = config; return VSConstants.S_OK; } public virtual int QueryStartBuild(uint options, int[] supported, int[] ready) { if (supported != null && supported.Length > 0) supported[0] = 1; if (ready != null && ready.Length > 0) ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1; return VSConstants.S_OK; } public virtual int QueryStartClean(uint options, int[] supported, int[] ready) { if (supported != null && supported.Length > 0) supported[0] = 1; if (ready != null && ready.Length > 0) ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1; return VSConstants.S_OK; } public virtual int QueryStartUpToDateCheck(uint options, int[] supported, int[] ready) { if (supported != null && supported.Length > 0) supported[0] = 1; if (ready != null && ready.Length > 0) ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1; return VSConstants.S_OK; } public virtual int QueryStatus(out int done) { done = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1; return VSConstants.S_OK; } public virtual int StartBuild(IVsOutputWindowPane pane, uint options) { config.PrepareBuild(false); // Current version of MSBuild wish to be called in an STA uint flags = VSConstants.VS_BUILDABLEPROJECTCFGOPTS_REBUILD; // If we are not asked for a rebuild, then we build the default target (by passing null) this.Build(options, pane, ((options & flags) != 0) ? MsBuildTarget.Rebuild : null); return VSConstants.S_OK; } public virtual int StartClean(IVsOutputWindowPane pane, uint options) { config.PrepareBuild(true); // Current version of MSBuild wish to be called in an STA this.Build(options, pane, MsBuildTarget.Clean); return VSConstants.S_OK; } public virtual int StartUpToDateCheck(IVsOutputWindowPane pane, uint options) { return config.IsUpToDate() ? VSConstants.S_OK : VSConstants.E_FAIL; } public virtual int Stop(int fsync) { return VSConstants.S_OK; } public virtual int UnadviseBuildStatusCallback(uint cookie) { callbacks.RemoveAt(cookie); return VSConstants.S_OK; } public virtual int Wait(uint ms, int fTickWhenMessageQNotEmpty) { return VSConstants.E_NOTIMPL; } #endregion #region helpers [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private bool NotifyBuildBegin() { int shouldContinue = 1; foreach (IVsBuildStatusCallback cb in callbacks) { try { ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue)); if (shouldContinue == 0) { return false; } } catch (Exception e) { // If those who ask for status have bugs in their code it should not prevent the build/notification from happening Debug.Fail(SR.GetString(SR.BuildEventError, e.Message)); } } return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void NotifyBuildEnd(MSBuildResult result, string buildTarget) { int success = ((result == MSBuildResult.Successful) ? 1 : 0); foreach (IVsBuildStatusCallback cb in callbacks) { try { ErrorHandler.ThrowOnFailure(cb.BuildEnd(success)); } catch (Exception e) { // If those who ask for status have bugs in their code it should not prevent the build/notification from happening Debug.Fail(SR.GetString(SR.BuildEventError, e.Message)); } finally { // We want to refresh the references if we are building with the Build or Rebuild target or if the project was opened for browsing only. bool shouldRepaintReferences = (buildTarget == null || buildTarget == MsBuildTarget.Build || buildTarget == MsBuildTarget.Rebuild); // Now repaint references if that is needed. // We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build. // One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable, // but msbuild can actually resolve it. // Another one if the project was opened only for browsing and now the user chooses to build or rebuild. if (shouldRepaintReferences && (result == MSBuildResult.Successful)) { this.RefreshReferences(); } } } } private void Build(uint options, IVsOutputWindowPane output, string target) { if (!this.NotifyBuildBegin()) { return; } try { config.ProjectMgr.BuildAsync(options, this.config.ConfigName, output, target, (result, buildTarget) => this.NotifyBuildEnd(result, buildTarget)); } catch (Exception e) { if (e.IsCriticalException()) { throw; } Trace.WriteLine("Exception : " + e.Message); ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n")); this.NotifyBuildEnd(MSBuildResult.Failed, target); throw; } finally { ErrorHandler.ThrowOnFailure(output.FlushToTaskList()); } } /// <summary> /// Refreshes references and redraws them correctly. /// </summary> private void RefreshReferences() { // Refresh the reference container node for assemblies that could be resolved. IReferenceContainer referenceContainer = this.config.ProjectMgr.GetReferenceContainer(); if (referenceContainer != null) { foreach (ReferenceNode referenceNode in referenceContainer.EnumReferences()) { referenceNode.RefreshReference(); } } } #endregion } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.ComponentModel; /// <summary> /// Represents a generic dictionary that can be sent to or retrieved from EWS. /// </summary> /// <typeparam name="TKey">The type of key.</typeparam> /// <typeparam name="TEntry">The type of entry.</typeparam> [EditorBrowsable(EditorBrowsableState.Never)] public abstract class DictionaryProperty<TKey, TEntry> : ComplexProperty, ICustomUpdateSerializer where TEntry : DictionaryEntryProperty<TKey> { private Dictionary<TKey, TEntry> entries = new Dictionary<TKey, TEntry>(); private Dictionary<TKey, TEntry> removedEntries = new Dictionary<TKey, TEntry>(); private List<TKey> addedEntries = new List<TKey>(); private List<TKey> modifiedEntries = new List<TKey>(); /// <summary> /// Entry was changed. /// </summary> /// <param name="complexProperty">The complex property.</param> private void EntryChanged(ComplexProperty complexProperty) { TKey key = (complexProperty as TEntry).Key; if (!this.addedEntries.Contains(key) && !this.modifiedEntries.Contains(key)) { this.modifiedEntries.Add(key); this.Changed(); } } /// <summary> /// Writes the URI to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="key">The key.</param> private void WriteUriToXml(EwsServiceXmlWriter writer, TKey key) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.IndexedFieldURI); writer.WriteAttributeValue(XmlAttributeNames.FieldURI, this.GetFieldURI()); writer.WriteAttributeValue(XmlAttributeNames.FieldIndex, this.GetFieldIndex(key)); writer.WriteEndElement(); } /// <summary> /// Gets the index of the field. /// </summary> /// <param name="key">The key.</param> /// <returns>Key index.</returns> internal virtual string GetFieldIndex(TKey key) { return key.ToString(); } /// <summary> /// Gets the field URI. /// </summary> /// <returns>Field URI.</returns> internal virtual string GetFieldURI() { return null; } /// <summary> /// Creates the entry. /// </summary> /// <param name="reader">The reader.</param> /// <returns>Dictionary entry.</returns> internal virtual TEntry CreateEntry(EwsServiceXmlReader reader) { if (reader.LocalName == XmlElementNames.Entry) { return this.CreateEntryInstance(); } else { return null; } } /// <summary> /// Creates instance of dictionary entry. /// </summary> /// <returns>New instance.</returns> internal abstract TEntry CreateEntryInstance(); /// <summary> /// Gets the name of the entry XML element. /// </summary> /// <param name="entry">The entry.</param> /// <returns>XML element name.</returns> internal virtual string GetEntryXmlElementName(TEntry entry) { return XmlElementNames.Entry; } /// <summary> /// Clears the change log. /// </summary> internal override void ClearChangeLog() { this.addedEntries.Clear(); this.removedEntries.Clear(); this.modifiedEntries.Clear(); foreach (TEntry entry in this.entries.Values) { entry.ClearChangeLog(); } } /// <summary> /// Add entry. /// </summary> /// <param name="entry">The entry.</param> internal void InternalAdd(TEntry entry) { entry.OnChange += this.EntryChanged; this.entries.Add(entry.Key, entry); this.addedEntries.Add(entry.Key); this.removedEntries.Remove(entry.Key); this.Changed(); } /// <summary> /// Add or replace entry. /// </summary> /// <param name="entry">The entry.</param> internal void InternalAddOrReplace(TEntry entry) { TEntry oldEntry; if (this.entries.TryGetValue(entry.Key, out oldEntry)) { oldEntry.OnChange -= this.EntryChanged; entry.OnChange += this.EntryChanged; if (!this.addedEntries.Contains(entry.Key)) { if (!this.modifiedEntries.Contains(entry.Key)) { this.modifiedEntries.Add(entry.Key); } } this.Changed(); } else { this.InternalAdd(entry); } } /// <summary> /// Remove entry based on key. /// </summary> /// <param name="key">The key.</param> internal void InternalRemove(TKey key) { TEntry entry; if (this.entries.TryGetValue(key, out entry)) { entry.OnChange -= this.EntryChanged; this.entries.Remove(key); this.removedEntries.Add(key, entry); this.Changed(); } this.addedEntries.Remove(key); this.modifiedEntries.Remove(key); } /// <summary> /// Loads from XML. /// </summary> /// <param name="reader">The reader.</param> /// <param name="localElementName">Name of the local element.</param> internal override void LoadFromXml(EwsServiceXmlReader reader, string localElementName) { reader.EnsureCurrentNodeIsStartElement(XmlNamespace.Types, localElementName); if (!reader.IsEmptyElement) { do { reader.Read(); if (reader.IsStartElement()) { TEntry entry = this.CreateEntry(reader); if (entry != null) { entry.LoadFromXml(reader, reader.LocalName); this.InternalAdd(entry); } else { reader.SkipCurrentElement(); } } } while (!reader.IsEndElement(XmlNamespace.Types, localElementName)); } } /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="xmlNamespace">The XML namespace.</param> /// <param name="xmlElementName">Name of the XML element.</param> internal override void WriteToXml( EwsServiceXmlWriter writer, XmlNamespace xmlNamespace, string xmlElementName) { // Only write collection if it has at least one element. if (this.entries.Count > 0) { base.WriteToXml( writer, xmlNamespace, xmlElementName); } } /// <summary> /// Writes elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { foreach (KeyValuePair<TKey, TEntry> keyValuePair in this.entries) { keyValuePair.Value.WriteToXml(writer, this.GetEntryXmlElementName(keyValuePair.Value)); } } /// <summary> /// Gets the entries. /// </summary> /// <value>The entries.</value> internal Dictionary<TKey, TEntry> Entries { get { return this.entries; } } /// <summary> /// Determines whether this instance contains the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if this instance contains the specified key; otherwise, <c>false</c>. /// </returns> public bool Contains(TKey key) { return this.Entries.ContainsKey(key); } #region ICustomXmlUpdateSerializer Members /// <summary> /// Writes updates to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="ewsObject">The ews object.</param> /// <param name="propertyDefinition">Property definition.</param> /// <returns> /// True if property generated serialization. /// </returns> bool ICustomUpdateSerializer.WriteSetUpdateToXml( EwsServiceXmlWriter writer, ServiceObject ewsObject, PropertyDefinition propertyDefinition) { List<TEntry> tempEntries = new List<TEntry>(); foreach (TKey key in this.addedEntries) { tempEntries.Add(this.entries[key]); } foreach (TKey key in this.modifiedEntries) { tempEntries.Add(this.entries[key]); } foreach (TEntry entry in tempEntries) { if (!entry.WriteSetUpdateToXml( writer, ewsObject, propertyDefinition.XmlElementName)) { writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetSetFieldXmlElementName()); this.WriteUriToXml(writer, entry.Key); writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetXmlElementName()); writer.WriteStartElement(XmlNamespace.Types, propertyDefinition.XmlElementName); entry.WriteToXml(writer, this.GetEntryXmlElementName(entry)); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); } } foreach (TEntry entry in this.removedEntries.Values) { if (!entry.WriteDeleteUpdateToXml(writer, ewsObject)) { writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetDeleteFieldXmlElementName()); this.WriteUriToXml(writer, entry.Key); writer.WriteEndElement(); } } return true; } /// <summary> /// Writes deletion update to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="ewsObject">The ews object.</param> /// <returns> /// True if property generated serialization. /// </returns> bool ICustomUpdateSerializer.WriteDeleteUpdateToXml(EwsServiceXmlWriter writer, ServiceObject ewsObject) { return false; } #endregion } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Registrasi_HemoList : System.Web.UI.Page { public int NoKe = 0; //protected string dsReportSessionName = "dsListRegistrasiKUBT"; protected string dsReportSessionName = "dsListRegistrasiHemo"; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; //if (Session["RegistrasiKUBT"] == null) if (Session["RegistrasiHemo"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } else { btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + "Pasien Baru"; btnAddRJ.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + "Pasien Rawat Jalan"; btnAddRI.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + "Pasien Rawat Inap"; } btnSearch.Text = Resources.GetString("", "Search"); ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif"; ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif"; ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif"; ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif"; txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy"); UpdateDataView(true); } } #region .Update View Data ////////////////////////////////////////////////////////////////////// // PhysicalDataRead // ------------------------------------------------------------------ /// <summary> /// This function is responsible for loading data from database. /// </summary> /// <returns>DataSet</returns> public DataSet PhysicalDataRead() { // Local variables DataSet oDS = new DataSet(); // Get Data DataTable myData = new DataTable(); SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); if (txtTanggalRegistrasi.Text != "") { myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); } //myObj.PoliklinikId = 26 ;//KUBT myObj.PoliklinikId = 39; //Hemodialisa myData = myObj.SelectAllFilter(); oDS.Tables.Add(myData); return oDS; } /// <summary> /// This function is responsible for binding data to Datagrid. /// </summary> /// <param name="dv"></param> private void BindData(DataView dv) { // Sets the sorting order dv.Sort = DataGridList.Attributes["SortField"]; if (DataGridList.Attributes["SortAscending"] == "no") dv.Sort += " DESC"; if (dv.Count > 0) { DataGridList.ShowFooter = false; int intRowCount = dv.Count; int intPageSaze = DataGridList.PageSize; int intPageCount = intRowCount / intPageSaze; if (intRowCount - (intPageCount * intPageSaze) > 0) intPageCount = intPageCount + 1; if (DataGridList.CurrentPageIndex >= intPageCount) DataGridList.CurrentPageIndex = intPageCount - 1; } else { DataGridList.ShowFooter = true; DataGridList.CurrentPageIndex = 0; } // Re-binds the grid NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex; DataGridList.DataSource = dv; DataGridList.DataBind(); int CurrentPage = DataGridList.CurrentPageIndex + 1; lblCurrentPage.Text = CurrentPage.ToString(); lblTotalPage.Text = DataGridList.PageCount.ToString(); lblTotalRecord.Text = dv.Count.ToString(); } /// <summary> /// This function is responsible for loading data from database and store to Session. /// </summary> /// <param name="strDataSessionName"></param> public void DataFromSourceToMemory(String strDataSessionName) { // Gets rows from the data source DataSet oDS = PhysicalDataRead(); // Stores it in the session cache Session[strDataSessionName] = oDS; } /// <summary> /// This function is responsible for update data view from datagrid. /// </summary> /// <param name="requery">true = get data from database, false= get data from session</param> public void UpdateDataView(bool requery) { // Retrieves the data if ((Session[dsReportSessionName] == null) || (requery)) { if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString()); DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } public void UpdateDataView() { // Retrieves the data if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } #endregion #region .Event DataGridList ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // HANDLERs // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageChanged(Object sender, DataGridPageChangedEventArgs e) { DataGridList.CurrentPageIndex = e.NewPageIndex; DataGridList.SelectedIndex = -1; UpdateDataView(); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="nPageIndex"></param> public void GoToPage(Object sender, int nPageIndex) { DataGridPageChangedEventArgs evPage; evPage = new DataGridPageChangedEventArgs(sender, nPageIndex); PageChanged(sender, evPage); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a first page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToFirst(Object sender, ImageClickEventArgs e) { GoToPage(sender, 0); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a previous page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToPrev(Object sender, ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex > 0) { GoToPage(sender, DataGridList.CurrentPageIndex - 1); } else { GoToPage(sender, 0); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a next page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1)) { GoToPage(sender, DataGridList.CurrentPageIndex + 1); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a last page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToLast(Object sender, ImageClickEventArgs e) { GoToPage(sender, DataGridList.PageCount - 1); } /// <summary> /// This function is invoked when you click on a column's header to /// sort by that. It just saves the current sort field name and /// refreshes the grid. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void SortByColumn(Object sender, DataGridSortCommandEventArgs e) { String strSortBy = DataGridList.Attributes["SortField"]; String strSortAscending = DataGridList.Attributes["SortAscending"]; // Sets the new sorting field DataGridList.Attributes["SortField"] = e.SortExpression; // Sets the order (defaults to ascending). If you click on the // sorted column, the order reverts. DataGridList.Attributes["SortAscending"] = "yes"; if (e.SortExpression == strSortBy) DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes"); // Refreshes the view OnClearSelection(null, null); UpdateDataView(); } /// <summary> /// The function gets invoked when a new item is being created in /// the datagrid. This applies to pager, header, footer, regular /// and alternating items. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageItemCreated(Object sender, DataGridItemEventArgs e) { // Get the newly created item ListItemType itemType = e.Item.ItemType; ////////////////////////////////////////////////////////// // Is it the HEADER? if (itemType == ListItemType.Header) { for (int i = 0; i < DataGridList.Columns.Count; i++) { // draw to reflect sorting if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression) { ////////////////////////////////////////////// // Should be much easier this way: // ------------------------------------------ // TableCell cell = e.Item.Cells[i]; // Label lblSorted = new Label(); // lblSorted.Font = "webdings"; // lblSorted.Text = strOrder; // cell.Controls.Add(lblSorted); // // but it seems it doesn't work <g> ////////////////////////////////////////////// // Add a non-clickable triangle to mean desc or asc. // The </a> ensures that what follows is non-clickable TableCell cell = e.Item.Cells[i]; LinkButton lb = (LinkButton)cell.Controls[0]; //lb.Text += "</a>&nbsp;<span style=font-family:webdings;>" + GetOrderSymbol() + "</span>"; lb.Text += "</a>&nbsp;<img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >"; } } } ////////////////////////////////////////////////////////// // Is it the PAGER? if (itemType == ListItemType.Pager) { // There's just one control in the list... TableCell pager = (TableCell)e.Item.Controls[0]; // Enumerates all the items in the pager... for (int i = 0; i < pager.Controls.Count; i += 2) { // It can be either a Label or a Link button try { Label l = (Label)pager.Controls[i]; l.Text = "Hal " + l.Text; l.CssClass = "CurrentPage"; } catch { LinkButton h = (LinkButton)pager.Controls[i]; h.Text = "[ " + h.Text + " ]"; h.CssClass = "HotLink"; } } } } /// <summary> /// Verifies whether the current sort is ascending or descending and /// returns an appropriate display text (i.e., a webding) /// </summary> /// <returns></returns> private String GetOrderSymbol() { bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no"); //return (bDescending ? " 6" : " 5"); return (bDescending ? "downbr.gif" : "upbr.gif"); } /// <summary> /// When clicked clears the current selection if any /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnClearSelection(Object sender, EventArgs e) { DataGridList.SelectedIndex = -1; } #endregion #region .Event Button /// <summary> /// When clicked, redirect to form add for inserts a new record to the database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnNewRecord(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); //Response.Redirect("KUBTAddBaru.aspx?CurrentPage=" + CurrentPage); Response.Redirect("HemoAddBaru.aspx?CurrentPage=" + CurrentPage); } public void OnAddRJ(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); //Response.Redirect("KUBTAddRJ.aspx?CurrentPage=" + CurrentPage); Response.Redirect("HemoAddRJ.aspx?CurrentPage=" + CurrentPage); } public void OnAddRI(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); //Response.Redirect("KUBTAddRI.aspx?CurrentPage=" + CurrentPage); Response.Redirect("HemoAddRI.aspx?CurrentPage=" + CurrentPage); } /// <summary> /// When clicked, filter data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnSearch(Object sender, System.EventArgs e) { if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; DataView dv = ds.Tables[0].DefaultView; if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Nama") dv.RowFilter = " Nama LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NoRegistrasi") dv.RowFilter = " NoRegistrasi LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NoRM") dv.RowFilter = " NoRM LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NRP") dv.RowFilter = " NRP LIKE '%" + txtSearch.Text + "%'"; else dv.RowFilter = ""; BindData(dv); } #endregion #region .Update Link Item Butom /// <summary> /// The function is responsible for get link button form. /// </summary> /// <param name="szId"></param> /// <param name="CurrentPage"></param> /// <returns></returns> public string GetLinkButton(string RawatJalanId, string StatusRawatJalan, string Nama, string CurrentPage) { string szResult = ""; //if (Session["RegistrasiKUBT"] != null) if (Session["RegistrasiHemo"] != null) { //szResult += "<a class=\"toolbar\" href=\"KUBTView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + RawatJalanId + "\" "; szResult += "<a class=\"toolbar\" href=\"HemoView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + RawatJalanId + "\" "; szResult += ">Detil</a>"; } return szResult; } public bool GetLinkDelete(string StatusRawatJalan) { bool szResult = false; //if (Session["RegistrasiKUBT"] != null && StatusRawatJalan == "0") if (Session["RegistrasiHemo"] != null && StatusRawatJalan == "0") { szResult = true; } return szResult; } #endregion protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e) { UpdateDataView(true); } protected void DataGridList_DeleteCommand(object source, DataGridCommandEventArgs e) { string RawatJalanId = DataGridList.DataKeys[e.Item.ItemIndex].ToString(); SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.RawatJalanId = int.Parse(RawatJalanId); myObj.Delete(); DataGridList.SelectedIndex = -1; UpdateDataView(true); } }
using System; using System.Data.Linq; using System.Data.SqlTypes; using System.IO; using System.Linq.Expressions; using System.Text; using System.Xml; namespace LinqToDB.DataProvider.SqlServer { using Common; using Expressions; using Mapping; using SqlQuery; public class SqlServerMappingSchema : MappingSchema { public SqlServerMappingSchema() : base(ProviderName.SqlServer) { SetConvertExpression<SqlXml,XmlReader>( s => s.IsNull ? DefaultValue<XmlReader>.Value : s.CreateReader(), s => s.CreateReader()); SetConvertExpression<string,SqlXml>(s => new SqlXml(new MemoryStream(Encoding.UTF8.GetBytes(s)))); AddScalarType(typeof(SqlBinary), SqlBinary. Null, true, DataType.VarBinary); AddScalarType(typeof(SqlBoolean), SqlBoolean. Null, true, DataType.Boolean); AddScalarType(typeof(SqlByte), SqlByte. Null, true, DataType.Byte); AddScalarType(typeof(SqlDateTime), SqlDateTime.Null, true, DataType.DateTime); AddScalarType(typeof(SqlDecimal), SqlDecimal. Null, true, DataType.Decimal); AddScalarType(typeof(SqlDouble), SqlDouble. Null, true, DataType.Double); AddScalarType(typeof(SqlGuid), SqlGuid. Null, true, DataType.Guid); AddScalarType(typeof(SqlInt16), SqlInt16. Null, true, DataType.Int16); AddScalarType(typeof(SqlInt32), SqlInt32. Null, true, DataType.Int32); AddScalarType(typeof(SqlInt64), SqlInt64. Null, true, DataType.Int64); AddScalarType(typeof(SqlMoney), SqlMoney. Null, true, DataType.Money); AddScalarType(typeof(SqlSingle), SqlSingle. Null, true, DataType.Single); AddScalarType(typeof(SqlString), SqlString. Null, true, DataType.NVarChar); AddScalarType(typeof(SqlXml), SqlXml. Null, true, DataType.Xml); try { foreach (var typeInfo in new[] { new { Type = SqlServerTools.SqlHierarchyIdType, Name = "SqlHierarchyId" }, new { Type = SqlServerTools.SqlGeographyType, Name = "SqlGeography" }, new { Type = SqlServerTools.SqlGeometryType, Name = "SqlGeometry" }, }) { var type = typeInfo.Type ?? Type.GetType("Microsoft.SqlServer.Types.{0}, Microsoft.SqlServer.Types".Args(typeInfo.Name)) ?? Type.GetType("Microsoft.SqlServer.Types.{0}, SqlServerSpatial110".Args(typeInfo.Name)); if (type == null) continue; var p = type.GetProperty("Null"); var l = Expression.Lambda<Func<object>>( Expression.Convert(Expression.Property(null, p), typeof(object))); var nullValue = l.Compile()(); AddScalarType(type, nullValue, true, DataType.Udt); SqlServerDataProvider.SetUdtType(type, typeInfo.Name.Substring(3).ToLower()); } } catch { } SetValueToSqlConverter(typeof(String), (sb,dt,v) => ConvertStringToSql (sb, dt, v.ToString())); SetValueToSqlConverter(typeof(Char), (sb,dt,v) => ConvertCharToSql (sb, dt, (char)v)); SetValueToSqlConverter(typeof(DateTime), (sb,dt,v) => ConvertDateTimeToSql (sb, (DateTime)v)); SetValueToSqlConverter(typeof(TimeSpan), (sb,dt,v) => ConvertTimeSpanToSql (sb, dt, (TimeSpan)v)); SetValueToSqlConverter(typeof(DateTimeOffset), (sb,dt,v) => ConvertDateTimeOffsetToSql(sb, dt, (DateTimeOffset)v)); SetValueToSqlConverter(typeof(byte[]), (sb,dt,v) => ConvertBinaryToSql (sb, (byte[])v)); SetValueToSqlConverter(typeof(Binary), (sb,dt,v) => ConvertBinaryToSql (sb, ((Binary)v).ToArray())); SetDataType(typeof(string), new SqlDataType(DataType.NVarChar, typeof(string), int.MaxValue)); } internal static SqlServerMappingSchema Instance = new SqlServerMappingSchema(); public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { if (@from != to && @from.FullName == to.FullName && @from.Namespace == "Microsoft.SqlServer.Types") { var p = Expression.Parameter(@from); return Expression.Lambda( Expression.Call(to, "Parse", new Type[0], Expression.New( MemberHelper.ConstructorOf(() => new SqlString("")), Expression.Call( Expression.Convert(p, typeof(object)), "ToString", new Type[0]))), p); } return base.TryGetConvertExpression(@from, to); } static void AppendConversion(StringBuilder stringBuilder, int value) { stringBuilder .Append("char(") .Append(value) .Append(')') ; } static void ConvertStringToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, string value) { string start; switch (sqlDataType.DataType) { case DataType.Char : case DataType.VarChar : case DataType.Text : start = "'"; break; default : start = "N'"; break; } DataTools.ConvertStringToSql(stringBuilder, "+", start, AppendConversion, value); } static void ConvertCharToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, char value) { string start; switch (sqlDataType.DataType) { case DataType.Char : case DataType.VarChar : case DataType.Text : start = "'"; break; default : start = "N'"; break; } DataTools.ConvertCharToSql(stringBuilder, start, AppendConversion, value); } static void ConvertDateTimeToSql(StringBuilder stringBuilder, DateTime value) { var format = value.Millisecond == 0 ? value.Hour == 0 && value.Minute == 0 && value.Second == 0 ? "yyyy-MM-dd" : "yyyy-MM-ddTHH:mm:ss" : "yyyy-MM-ddTHH:mm:ss.fff"; stringBuilder .Append('\'') .Append(value.ToString(format)) .Append('\'') ; } static void ConvertTimeSpanToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, TimeSpan value) { if (sqlDataType.DataType == DataType.Int64) { stringBuilder.Append(value.Ticks); } else { var format = value.Days > 0 ? value.Milliseconds > 0 ? "d\\.hh\\:mm\\:ss\\.fff" : "d\\.hh\\:mm\\:ss" : value.Milliseconds > 0 ? "hh\\:mm\\:ss\\.fff" : "hh\\:mm\\:ss"; stringBuilder .Append('\'') .Append(value.ToString(format)) .Append('\'') ; } } static void ConvertDateTimeOffsetToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, DateTimeOffset value) { var format = "'{0:yyyy-MM-dd HH:mm:ss.fffffff zzz}'"; switch (sqlDataType.Precision ?? sqlDataType.Scale) { case 0 : format = "'{0:yyyy-MM-dd HH:mm:ss zzz}'"; break; case 1 : format = "'{0:yyyy-MM-dd HH:mm:ss.f zzz}'"; break; case 2 : format = "'{0:yyyy-MM-dd HH:mm:ss.ff zzz}'"; break; case 3 : format = "'{0:yyyy-MM-dd HH:mm:ss.fff zzz}'"; break; case 4 : format = "'{0:yyyy-MM-dd HH:mm:ss.ffff zzz}'"; break; case 5 : format = "'{0:yyyy-MM-dd HH:mm:ss.fffff zzz}'"; break; case 6 : format = "'{0:yyyy-MM-dd HH:mm:ss.ffffff zzz}'"; break; case 7 : format = "'{0:yyyy-MM-dd HH:mm:ss.fffffff zzz}'"; break; } stringBuilder.AppendFormat(format, value); } static void ConvertBinaryToSql(StringBuilder stringBuilder, byte[] value) { stringBuilder.Append("0x"); foreach (var b in value) stringBuilder.Append(b.ToString("X2")); } } public class SqlServer2000MappingSchema : MappingSchema { public SqlServer2000MappingSchema() : base(ProviderName.SqlServer2000, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2005MappingSchema : MappingSchema { public SqlServer2005MappingSchema() : base(ProviderName.SqlServer2005, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2008MappingSchema : MappingSchema { public SqlServer2008MappingSchema() : base(ProviderName.SqlServer2008, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2012MappingSchema : MappingSchema { public SqlServer2012MappingSchema() : base(ProviderName.SqlServer2012, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } }
// 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 OLEDB.Test.ModuleCore; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Xml; using System.Xml.XmlDiff; namespace XmlCoreTest.Common { /************************************************* author alexkr date 12/14/2005 This class contains common static methods used to verify the results of an XSLT data-driven test. It contains the following methods: CompareXml - used to compare two XML outputs, captured as files, using XmlDiff. CompareChecksum - used to compare two non-XML outputs, captured as files, using a Checksum calculation. CompareException - used to compare two Exceptions, or the meta-data of two Exceptions, using an Exception wrapper class. ************************************************/ public class XsltVerificationLibrary { public static string winSDKPath = string.Empty; /************************************************* XMLDiff compare for XSLTV2 data driven tests. It supports custom data-driven xmldiff options passed from the command line, It might support an optional helperObject that can perform delayed logging, but does not yet. ************************************************/ public static bool CompareXml(string baselineFile, string actualFile, string xmldiffoptionvalue) { return CompareXml(baselineFile, actualFile, xmldiffoptionvalue, null); } public static bool CompareXml(string baselineFile, string actualFile, string xmldiffoptionvalue, DelayedWriteLogger logger) { using (var fsActual = new FileStream(actualFile, FileMode.Open, FileAccess.Read)) using (var fsExpected = new FileStream(baselineFile, FileMode.Open, FileAccess.Read)) { return CompareXml(fsActual, fsExpected, xmldiffoptionvalue, logger); } } public static bool CompareXml(string baselineFile, Stream actualStream) { actualStream.Seek(0, SeekOrigin.Begin); using (var expectedStream = new FileStream(baselineFile, FileMode.Open, FileAccess.Read)) return CompareXml(expectedStream, actualStream, string.Empty, null); } public static bool CompareXml(Stream expectedStream, Stream actualStream, string xmldiffoptionvalue, DelayedWriteLogger logger) { bool bResult = false; // Default Diff options used by XSLT V2 driver. int defaultXmlDiffOptions = (int)(XmlDiffOption.InfosetComparison | XmlDiffOption.IgnoreEmptyElement | XmlDiffOption.IgnoreAttributeOrder); XmlDiff diff = new XmlDiff(); if (xmldiffoptionvalue == null || xmldiffoptionvalue.Equals(string.Empty)) diff.Option = (XmlDiffOption)defaultXmlDiffOptions; else { if (logger != null) logger.LogMessage("Custom XmlDiffOptions used. Value passed is " + xmldiffoptionvalue); diff.Option = (XmlDiffOption)int.Parse(xmldiffoptionvalue); } XmlParserContext context = new XmlParserContext(new NameTable(), null, "", XmlSpace.None); try { bResult = diff.Compare(new XmlTextReader(actualStream, XmlNodeType.Element, context), new XmlTextReader(expectedStream, XmlNodeType.Element, context)); } catch (Exception e) { bResult = false; if (logger != null) { logger.LogMessage("Exception thrown in XmlDiff compare!"); logger.LogXml(e.ToString()); throw; } } if (bResult) return true; if (logger != null) { logger.LogMessage("Mismatch in XmlDiff"); logger.LogMessage("Actual result: "); } return false; } /************************************************* Checksum calculation. Legacy. ************************************************/ public static bool CompareChecksum(string Baseline, string OutFile, int driverVersion) { return CompareChecksum(Baseline, OutFile, driverVersion, null); } public static bool CompareChecksum(string Baseline, string OutFile, int driverVersion, DelayedWriteLogger logger) { return CompareChecksum( Baseline, 1, //start from the first line in the baseline file OutFile, 1, //start from the first line in the output file driverVersion, logger); } /// <summary> /// /// </summary> /// <param name="Baseline"></param> /// <param name="baselineStartLine">The line to start comparison in the baseline file</param> /// <param name="OutFile"></param> /// <param name="outFileStartLine">The line to start comparison in the output file</param> /// <param name="driverVersion"></param> /// <param name="logger"></param> /// <returns></returns> public static bool CompareChecksum(string Baseline, int baselineStartLine, string OutFile, int outFileStartLine, int driverVersion, DelayedWriteLogger logger) { // Keep people honest. if (driverVersion == 2) { if (logger != null) logger.LogMessage("Calculating checksum for baseline output {0}...", Baseline); string expectedCheckSum = CalcChecksum(Baseline, baselineStartLine, logger); string actualChecksum = CalcChecksum(OutFile, outFileStartLine, logger); if (expectedCheckSum.Equals(actualChecksum)) return true; else { if (logger != null) { logger.LogMessage("Actual checksum: {0}, Expected checksum: {1}", actualChecksum, expectedCheckSum); logger.LogMessage("Actual result: "); logger.WriteOutputFileToLog(OutFile); } return false; } } else throw new NotSupportedException("Not a supported driver version"); } private static string CalcChecksum(string fileName, DelayedWriteLogger logger) { return CalcChecksum(fileName, 1, logger); } /// <summary> /// /// </summary> /// <param name="fileName"></param> /// <param name="startFromLine">The line to start calculating the checksum. Any text before this line is ignored. First line is 1.</param> /// <param name="logger"></param> /// <returns></returns> private static string CalcChecksum(string fileName, int startFromLine, DelayedWriteLogger logger) { const int BUFFERSIZE = 4096; decimal dResult = 0; // Numerical value of the checksum int i = 0; // Generic counter int cBytesRead = 1; // # of bytes read at one time int cTotalRead = 0; // Total # of bytes read so far decimal dEndBuffer = 0; // Buffer to remove from the end (This is necessary because // notepad adds CR/LF onto the end of every file) char[] rgBuffer = new char[BUFFERSIZE]; string xml = ""; StreamReader fs = null; try { fs = new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read)); //switch to the line to start from, lines start from 1 for (int j = 1; j < startFromLine; j++) { fs.ReadLine(); } cBytesRead = fs.Read(rgBuffer, 0, BUFFERSIZE); while (cBytesRead > 0) { // Keep XML property up to date xml = string.Concat(xml, new string(rgBuffer, 0, cBytesRead)); // Calculate the checksum for (i = 0; i < cBytesRead; i++) { dResult += Math.Round((decimal)(rgBuffer[i] / (cTotalRead + i + 1.0)), 10); } cTotalRead += cBytesRead; dEndBuffer = 0; // Keep reading (in case file is bigger than 4K) cBytesRead = fs.Read(rgBuffer, 0, BUFFERSIZE); } } catch (Exception ex) { if (logger != null) logger.LogXml(ex.ToString()); return ""; } finally { if (fs != null) fs.Dispose(); } return Convert.ToString(dResult - dEndBuffer, NumberFormatInfo.InvariantInfo); } // Is this really all there is to it? public static bool DetectEmittedPDB(string fileName) { if (File.Exists(fileName)) return true; else return File.Exists(fileName + ".pdb"); } // Call PEVerify on the Assembly name, parse the output, // and return true if the output is PASS and false if the output is FAIL. public static bool VerifyAssemblyUsingPEVerify(string asmName, bool isValidCase, DelayedWriteLogger logger, ref string output) { Debug.Assert(asmName != null); Debug.Assert(asmName != string.Empty); if (!asmName.Contains(".dll") || !asmName.Contains(".DLL")) asmName = asmName + ".dll"; if (File.Exists(asmName)) { return VerifyAssemblyUsingPEVerify(asmName, logger, ref output); } else { if (isValidCase) { string message = "PEVerify could not be run, no assembly present: " + asmName; if (logger != null) logger.LogMessage(message); output = message; return false; } else return true; } } public static bool VerifySingleAssemblyUsingPEVerify(string asmName, DelayedWriteLogger logger, ref string output) { Debug.Assert(asmName != null); Debug.Assert(asmName != string.Empty); bool result = false; if (File.Exists(asmName)) { //add double quotes for names with whitespace in them string processArguments = " /quiet " + "\"" + asmName + "\""; // Call PEVerify to verify persistant assembly. Process peVerifyProcess = new Process(); peVerifyProcess.StartInfo.FileName = SearchPath("peverify.exe"); peVerifyProcess.StartInfo.Arguments = " " + processArguments; //peVerifyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; peVerifyProcess.StartInfo.CreateNoWindow = true; peVerifyProcess.StartInfo.UseShellExecute = false; peVerifyProcess.StartInfo.RedirectStandardOutput = true; peVerifyProcess.Start(); output = peVerifyProcess.StandardOutput.ReadToEnd(); peVerifyProcess.WaitForExit(); // Check the output for the Assembly name, and the word "PASS" // For example: // C:>peverify /quiet 4AC8BD29F3CB888FAD76F7C08FD57AD3.dll // 4AC8BD29F3CB888FAD76F7C08FD57AD3.dll PASS if (peVerifyProcess.ExitCode == 0 && output.Contains(asmName) && output.Contains("PASS")) result = true; else { if (logger != null) logger.LogMessage("PEVerify could not be run or FAILED : {0}", asmName + " " + output); result = false; } } else { if (logger != null) logger.LogMessage("Assembly file could not be found : {0}", asmName); result = false; } return result; } public static bool VerifyAssemblyUsingPEVerify(string asmName, DelayedWriteLogger logger, ref string output) { string scriptAsmNameFormat = Path.ChangeExtension(asmName, null) + "_Script{0}.dll"; int scriptCounter = 0; string testAsm = asmName; bool result = false; do { result = VerifySingleAssemblyUsingPEVerify(testAsm, logger, ref output); testAsm = string.Format(scriptAsmNameFormat, ++scriptCounter); } while (result && File.Exists(testAsm)); return result; } public static string SearchPath(string fileName) { var locations = new HashSet<string>(StringComparer.OrdinalIgnoreCase); // 32 bit if on 64 bit Windows locations.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Microsoft SDKs\Windows")); // 32 bit if on 32 bit Windows, otherwise 64 bit locations.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Microsoft SDKs\Windows")); // 64 bit if in 32 bit process on 64 bit Windows locations.Add(Path.Combine(Environment.GetEnvironmentVariable("ProgramW6432"), @"Microsoft SDKs\Windows")); var files = new List<string>(); foreach (var location in locations) { if (Directory.Exists(location)) files.AddRange(Directory.GetFiles(location, fileName, SearchOption.AllDirectories)); } if (files.Count == 0) throw new FileNotFoundException(fileName); // Prefer newer versions, for stability files.Sort((left, right) => { int comparison = Comparer<float>.Default.Compare(GetVersionFromSDKPath(left), GetVersionFromSDKPath(right)); if (comparison == 0) comparison = string.Compare(left, right, StringComparison.OrdinalIgnoreCase); return comparison; }); return files[files.Count - 1]; } // Pull the version out of a path like "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\xsltc.exe" private static float GetVersionFromSDKPath(string s) { Match match = Regex.Match(s, @"\\v(\d+\.\d+)\w?\\", RegexOptions.IgnoreCase); float val = 0; if (match.Success) float.TryParse(match.Groups[1].Value, out val); return val; } } /************************************************* This class is a delayed-write message logger, similar to CError.WriteLine etc. It is instantiated by your XsltDriver and used to record messages that you would normally write with CError.WriteLine, CError.WriteLineIgnore, or CError.WriteXml, in a buffered manner. The messages can be written to the final log file using WriteOutputFileToLog() by your driver code if there is a variation failure, or just discarded when a test passes to keep results.log files within a managable size on disk. As an example, using this method reduced the size of the XSLT V2 log file from 3MB per run to around 300k. ************************************************/ public class DelayedWriteLogger { private ArrayList _messageLog; public DelayedWriteLogger() { _messageLog = new ArrayList(); } // Writes the buffer of messages to the results.log file. public void WriteOutputFileToLog(string fileName) { StreamReader fs = null; try { char[] rgBuffer = new char[4096]; fs = new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read)); int cBytesRead = fs.Read(rgBuffer, 0, 4096); while (cBytesRead > 0) { this.Log(new string(rgBuffer, 0, cBytesRead)); cBytesRead = fs.Read(rgBuffer, 0, 4096); } } finally { if (fs != null) fs.Dispose(); this.LogMessage(string.Empty); } } public void Log(string msg) { LogMessage(MessageType.Write, msg, null); } public void LogMessage(string msg) { LogMessage(MessageType.WriteLine, msg, null); } public void LogMessage(string msg, params object[] args) { LogMessage(MessageType.WriteLineParams, msg, args); } public void LogMessageIgnore(string msg) { LogMessage(MessageType.WriteLineIgnore, msg, null); } public void LogXml(string msg) { LogMessage(MessageType.Xml, msg, null); } private void LogMessage(MessageType msgtype, string msg, params object[] args) { LogMessage message = new LogMessage(msgtype, msg, args); _messageLog.Add(message); } public void WriteLoggedMessages() { foreach (LogMessage mg in _messageLog) { switch (mg.type) { case MessageType.Write: CError.Write(mg.msg); break; case MessageType.WriteLine: CError.WriteLine(mg.msg); break; case MessageType.WriteLineIgnore: CError.WriteLineIgnore(mg.msg); break; case MessageType.WriteLineParams: CError.WriteLine(mg.msg, mg.args); break; case MessageType.Xml: CError.WriteXml(mg.msg); break; } } } } // used by DelayedWriteLogger internal enum MessageType { Write, WriteLine, WriteLineParams, WriteLineIgnore, Xml } // used by DelayedWriteLogger internal class LogMessage { public LogMessage(MessageType t, string m, object[] o) { type = t; msg = m; args = o; } internal MessageType type; public string msg; public object[] args; } /************************************************* author alexkr date 12/12/2005 This class is used to compare expected exceptions with actual exceptions in the CompareException method, used by the XSLT V2 data driven driver. Its use is somewhat subtle, so please read all comments, understand the Equals method, and ask for introduction before you use it in any new code, or modify existing code. Why? There are many assumptions made when using this class. Here are some... Non-Xml Exceptions are always compared by type, and must never have ExceptionResourceId or ExceptionMessage attributes in a control file. Xml Exceptions can be either ExceptionId only, ExceptionId and ExceptionMessage for all Xml_UserException exceptions, or ExceptionId and ExceptionResourceId for all non-Xml_UserExceptions Never have both ExceptionResourceId AND ExceptionMessage attributes set for the same Exception meta-data. The behavior is undefined. Xml Exceptions that are Xml_UserExceptions and include a MessageFragment will only be compared in ENU runs. Globalized runs resort to Type comparison (ExceptionId) only. Xml Exceptions that are non-Xml_UserExceptions and include an ExceptionResourceId will be compared for all runs. **************************************************/ public class XsltRuntimeException { public static string XMLUSEREX = "Xml_UserException"; private XsltRuntimeException() { } // no op, do not call public XsltRuntimeException(string a, bool d) : this(a, XMLUSEREX, string.Empty, d) { } public XsltRuntimeException(string a, string b, string c, bool d) { ExceptionId = a; ResourceId = b; MessageFragment = c; _examineMessages = d; } public string ExceptionId; public string ResourceId; public string MessageFragment; private bool _examineMessages; public override string ToString() { return ExceptionId + "\n" + ResourceId + "\n" + MessageFragment; } public override int GetHashCode() { return base.GetHashCode(); } // The Equals method must always be used this way // ExpectedException.Equals( ActualException )? // Please note that if ExamineMessages is true, we are in a non-localized build and we can safely examine exception messages. If false, we fall back to type comparison exclusively. public override bool Equals(object o) { XsltRuntimeException objectToCompareTo = o as XsltRuntimeException; Debug.Assert(objectToCompareTo != null); Debug.Assert(objectToCompareTo.ExceptionId != null, "ExceptionId must be initialized to a valid fully qualified type name"); Debug.Assert(objectToCompareTo.ResourceId != null, "ResourceId must be initialized to String.Empty, in which case MessageFragment is used, or a legal resource Id"); Debug.Assert(objectToCompareTo.MessageFragment != null, "MessageFragment must be initialized to String.Empty, in which case ResourceId is used, or a string that represents a specific exception message."); Debug.Assert(this.ExceptionId != null, "ExceptionId must be initialized to a valid fully qualified type name"); Debug.Assert(this.ResourceId != null, "ResourceId must be initialized to String.Empty, in which case MessageFragment is used, or a legal resource Id"); Debug.Assert(this.MessageFragment != null, "MessageFragment must be initialized to String.Empty, in which case ResourceId is used, or a string that represents a specific exception message."); // Inside this block, we have two properly initialized XsltRuntimeExceptions to compare. ///// // There are several basic comparisons, each with its own degree of certainty. // // The first comparison is the original used by the driver, which we no longer use: if there is any // exception at all for an expected "Invalid" case, we match. // // The second comparison is the initial revision to the driver: an Exception type comparison. This is the least certain. // type matches should no longer exist once this exception work is complete. These will be flagged by failing the test. // // The third comparison is for Xml_UserExceptions. In this case we try to compare the Exception Type and Exception Message. // If the Exception type does not match, but the message does, we count that as a match. Note that this match is NOT // immue to the effects of globalized resource strings, and hence is less certain. // // The fourth comparison is for NON Xml_UserExceptions. In this case we try to compare the Exception Type and ResourceId. // If the Exception type does not match, but the resource id does, we count that a match. Note that this match is // immune to the effects of globalized resource strings. It is the most certain match we can make. // ///// if (!IsXmlException(this.ExceptionId)) { // Aye, here's the dillema. If its not an XML exception we can't look up its resource ID. // So in these cases (very rare anyway) we revert to the old simple days of comparing type to type. return objectToCompareTo.ExceptionId.Equals(this.ExceptionId); } else { if (!objectToCompareTo.ResourceId.Equals(string.Empty) && !objectToCompareTo.ResourceId.Equals(XMLUSEREX) && objectToCompareTo.ResourceId.Equals(this.ResourceId)) { //**** The highest degree of certainty we have. ****// if (objectToCompareTo.ExceptionId.Equals(this.ExceptionId)) return true; // ResourceIds match, but Exception types dont. else { CError.WriteLine("match?\n {0} \ncompare to \n {1} \n pls investigate why this resource id is being thrown in 2 differet exceptions", objectToCompareTo.ToString(), this.ToString()); return true; } } // ResourceId is Empty or Xml_UserException, or they dont match else if (!this.MessageFragment.Equals(string.Empty) && _examineMessages) { if (objectToCompareTo.ResourceId.Equals(this.ResourceId) && objectToCompareTo.MessageFragment.Contains(this.MessageFragment)) { //**** Very high certainty equivalence ****// if (objectToCompareTo.ExceptionId.Equals(this.ExceptionId)) return true; // Messages match, but Exception types dont. else { CError.WriteLine("match?(message matches but exact typename doesn't)\n {0} \ncompare to \n {1} ", objectToCompareTo.ToString(), this.ToString()); return false; // for now. } } } // ResourceId is Empty or Xml_UserException or they dont match, Message is Empty or they dont match else { //**** Lower degree of certainty ****// // This is an exception that has not yet been updated in the control file with complete information. // Use the older, less flexible comparison logic. CError.WriteLine("old comparison:{0} \ncompare to \n {1} ", objectToCompareTo.ToString(), this.ToString()); return objectToCompareTo.ExceptionId.Equals(this.ExceptionId); } } return false; } public static ArrayList XmlExceptionList = new ArrayList(5); private static void setXmlExceptionList() { XmlExceptionList.Add("System.Xml.Xsl.XPath.XPathCompileException"); XmlExceptionList.Add("System.Xml.Xsl.XslLoadException"); XmlExceptionList.Add("System.Xml.Xsl.XslTransformException"); XmlExceptionList.Add("System.Xml.Xsl.XsltException"); XmlExceptionList.Add("System.Xml.XmlException"); } public static bool IsXmlException(string typeName) { setXmlExceptionList(); return XmlExceptionList.Contains(typeName); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using bv.common.db.Core; using EIDSS.GISControl.Common.Layers; using EIDSS.GISControl.Common.Data.Providers; using SharpMap.Data; using SharpMap.Geometries; namespace EIDSS.Tests.GIS { public class GISControlTestInfo { public static DataTable GetCaseEvents_Old() { VectorLayer vectorLayer = new VectorLayer("stt_case"); string connection = ConnectionManager.DefaultInstance.ConnectionString; vectorLayer.DataSource = new MsSql(connection, "gisWKBSettlement", "blbWKBGeometry", "idfsGeoObject"); FeatureDataSet fds = new FeatureDataSet(); BoundingBox bbox = vectorLayer.Envelope; ((SharpMap.Data.Providers.MsSql)vectorLayer.DataSource).ExecuteIntersectionQuery(bbox, fds); DataTable events = new DataTable(); events.Columns.AddRange(new DataColumn[] { new DataColumn("x", typeof (double)), new DataColumn("y", typeof (double)), new DataColumn("caption", typeof(string)), new DataColumn("value", typeof (double)) }); Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); for (int i = 0; i < fds.Tables[0].Count; i++) { DataRow newRow = events.NewRow(); newRow["x"] = fds.Tables[0][i].Geometry.GetBoundingBox().Left; newRow["y"] = fds.Tables[0][i].Geometry.GetBoundingBox().Bottom; newRow["caption"] = "info"; newRow["value"] = rnd.Next(0, 5); events.Rows.Add(newRow); } return events; } public static DataTable GetCaseEvents() { VectorLayer vectorLayer = new VectorLayer("stt_case"); string connection = ConnectionManager.DefaultInstance.ConnectionString; vectorLayer.DataSource = new MsSql(connection, "gisWKBSettlement", "blbWKBGeometry", "idfsGeoObject"); FeatureDataSet fds = new FeatureDataSet(); BoundingBox bbox = vectorLayer.Envelope; ((SharpMap.Data.Providers.MsSql) vectorLayer.DataSource).ExecuteIntersectionQuery(bbox, fds); DataTable events = new DataTable(); events.Columns.AddRange(new DataColumn[] { new DataColumn("id", typeof (long)), new DataColumn("value", typeof (double)), new DataColumn("x", typeof (double)), new DataColumn("y", typeof (double)), new DataColumn("info1", typeof(string)), new DataColumn("info2",typeof(string)) }); Random rnd = new Random(unchecked((int) DateTime.Now.Ticks)); Random rnd1 = new Random(~unchecked((int)DateTime.Now.Ticks)); int k; for (int i = 0; i < fds.Tables[0].Count; i++) { DataRow newRow = events.NewRow(); newRow["id"] = rnd1.Next(); k = rnd.Next(0, 10); if (k < 5) { newRow["x"] = fds.Tables[0][i].Geometry.GetBoundingBox().Left; newRow["y"] = fds.Tables[0][i].Geometry.GetBoundingBox().Bottom; } newRow["value"] = rnd.Next(0, 5); newRow["info1"] = "info1"; newRow["info2"] = "info2"; if ((double)newRow["value"] != 0) events.Rows.Add(newRow); } return events; } public static DataTable GetRegionalEvents_Old(string connection, double minValue, double maxValue) { SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT idfsGeoObject FROM gisWKBRegion", connection); DataTable dataTable = new DataTable(); sqlDataAdapter.Fill(dataTable); DataTable events = new DataTable(); events.Columns.AddRange(new DataColumn[] { new DataColumn("id", typeof (long)), new DataColumn("caption", typeof (string)), new DataColumn("value", typeof (double)) }); Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); Random rnd1 = new Random(~unchecked((int)DateTime.Now.Ticks)); foreach (DataRow row in dataTable.Rows) { DataRow newRow = events.NewRow(); newRow["id"] = (long)row[0]; double dblValue = rnd.Next((int)minValue, (int)maxValue); int flag = rnd1.Next(0, 5); if (flag == 3) { dblValue = 0; } newRow["value"] = dblValue; newRow["caption"] = "region"; events.Rows.Add(newRow); } return events; } public static DataTable GetRegionalEvents(string connection, double minValue, double maxValue) { SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT idfsGeoObject FROM gisWKBRegion", connection); DataTable dataTable = new DataTable(); sqlDataAdapter.Fill(dataTable); DataTable events = new DataTable(); events.Columns.AddRange(new DataColumn[] { new DataColumn("id", typeof (long)), new DataColumn("value", typeof (double)), new DataColumn("x", typeof (double)), new DataColumn("y", typeof (double)), new DataColumn("population", typeof (long)), new DataColumn("info", typeof (string)) }); Random rnd = new Random(unchecked((int) DateTime.Now.Ticks)); Random rnd1 = new Random(~unchecked((int)DateTime.Now.Ticks)); foreach (DataRow row in dataTable.Rows) { DataRow newRow = events.NewRow(); newRow["id"] = (long) row[0]; double dblValue = rnd.Next((int) minValue, (int) maxValue); int flag = rnd1.Next(0, 5); if (flag == 3) { dblValue = 0; } newRow["value"] = dblValue; newRow["population"] = rnd.Next(0, 1000000); newRow["info"] = "region"; if (dblValue != 0) events.Rows.Add(newRow); } return events; } public static DataTable GetDistrictEvents_Old(string connection, double minValue, double maxValue) { SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT idfsGeoObject FROM gisWKBRayon", connection); DataTable dataTable = new DataTable(); sqlDataAdapter.Fill(dataTable); DataTable events = new DataTable(); events.Columns.AddRange(new DataColumn[] { new DataColumn("id", typeof (long)), new DataColumn("caption", typeof (string)), new DataColumn("value", typeof (double)) }); Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); Random rnd1 = new Random(~unchecked((int)DateTime.Now.Ticks)); foreach (DataRow row in dataTable.Rows) { DataRow newRow = events.NewRow(); newRow["id"] = (long)row[0]; double dblValue = rnd.Next((int)minValue, (int)maxValue); int flag = rnd1.Next(0, 15); if (flag == 3) { dblValue = 0; } newRow["value"] = dblValue; newRow["caption"] = "district"; events.Rows.Add(newRow); } return events; } public static DataTable GetDistrictEvents(string connection, double minValue, double maxValue) { SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT idfsGeoObject FROM gisWKBRayon", connection); DataTable dataTable = new DataTable(); sqlDataAdapter.Fill(dataTable); DataTable events = new DataTable(); events.Columns.AddRange(new DataColumn[] { new DataColumn("id", typeof (long)), new DataColumn("value", typeof (double)), new DataColumn("x", typeof (double)), new DataColumn("y", typeof (double)), new DataColumn("population", typeof (long)), new DataColumn("info", typeof (string)) }); Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); Random rnd1 = new Random(~unchecked((int)DateTime.Now.Ticks)); foreach (DataRow row in dataTable.Rows) { DataRow newRow = events.NewRow(); newRow["id"] = (long)row[0]; double dblValue = rnd.Next((int)minValue, (int)maxValue); int flag = rnd1.Next(0, 15); if (flag == 3) { dblValue = 0; } newRow["value"] = dblValue; newRow["population"] = rnd.Next(0, 1000000); newRow["info"] = "district"; if (dblValue != 0) events.Rows.Add(newRow); } return events; } public static DataTable GetSttEvents_Old(string connection, double minValue, double maxValue) { SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT idfsGeoObject FROM gisWKBSettlement", connection); DataTable dataTable = new DataTable(); sqlDataAdapter.Fill(dataTable); DataTable events = new DataTable(); events.Columns.AddRange(new DataColumn[] { new DataColumn("id", typeof (long)), new DataColumn("caption", typeof (string)), new DataColumn("value", typeof (double)) }); Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); Random rnd1 = new Random(~unchecked((int)DateTime.Now.Ticks)); foreach (DataRow row in dataTable.Rows) { DataRow newRow = events.NewRow(); newRow["id"] = (long)row[0]; double dblValue = rnd.Next((int)minValue, (int)maxValue); int flag = (int)rnd1.Next(0, 15); if (flag != 5) { dblValue = 0; } newRow["value"] = dblValue; newRow["caption"] = "settlement"; events.Rows.Add(newRow); } return events; } public static DataTable GetSttEvents(string connection, double minValue, double maxValue) { SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT idfsGeoObject FROM gisWKBSettlement", connection); DataTable dataTable = new DataTable(); sqlDataAdapter.Fill(dataTable); DataTable events = new DataTable(); events.Columns.AddRange(new DataColumn[] { new DataColumn("id", typeof (long)), new DataColumn("value", typeof (double)), new DataColumn("x", typeof (double)), new DataColumn("y", typeof (double)), new DataColumn("population", typeof (long)), new DataColumn("info", typeof (string)) }); Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); Random rnd1 = new Random(~unchecked((int) DateTime.Now.Ticks)); foreach (DataRow row in dataTable.Rows) { DataRow newRow = events.NewRow(); newRow["id"] = (long)row[0]; double dblValue = rnd.Next((int)minValue, (int)maxValue); int flag = (int) rnd1.Next(0, 15); if (flag!=5) { dblValue = 0; } newRow["value"] = dblValue; newRow["population"] = rnd.Next(0, 1000000); newRow["info"] = "settlement"; if (dblValue != 0) events.Rows.Add(newRow); } return events; } } }
using System; using System.Collections; using System.Data; using System.Data.OleDb; using System.Text; using PCSComUtils.Common; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; namespace PCSComProduction.DCP.DS { /// <summary> /// Summary description for ImportPlanDataDS. /// </summary> public class ImportPlanDataDS { private const string THIS = "PCSComProduction.DCP.DS.ImportPlanDataDS"; public ImportPlanDataDS() { // // TODO: Add constructor logic here // } /// <summary> /// Clear A1 data /// </summary> public void Delete() { const string METHOD_NAME = THIS + ".Delete()"; OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("DELETE A1", oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Update A1 Table /// </summary> /// <param name="pData"></param> public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT ProductID, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11," + " F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24," + " F25, F26, F27, F28, F29, F30, F31 FROM A1"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; int intCon = odadPCS.Update(pData, "A1"); int a = intCon; } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataSet List() { // TODO: Add ImportPlanDataDS.List implementation return null; } public void Update(object pobjObjecVO) { // TODO: Add ImportPlanDataDS.Update implementation } public void Delete(int pintID) { // TODO: Add ImportPlanDataDS.Delete implementation } public void Add(object pobjObjectVO) { // TODO: Add ImportPlanDataDS.Add implementation } public object GetObjectVO(int pintID) { // TODO: Add ImportPlanDataDS.GetObjectVO implementation return null; } public void ExecuteCommand(string pstrSql) { const string METHOD_NAME = THIS + ".ExecuteCommand()"; OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(pstrSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using Microsoft.Ccr.Core; using Microsoft.Dss.Core; using Microsoft.Dss.Core.DsspHttp; using Microsoft.Dss.Core.DsspHttpUtilities; using Microsoft.Dss.Core.Attributes; using Microsoft.Dss.ServiceModel.Dssp; using Microsoft.Dss.ServiceModel.DsspServiceBase; using W3C.Soap; using submgr = Microsoft.Dss.Services.SubscriptionManager; using System.Net; using System.Net.Mime; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using TrackRoamer.Robotics.Utility.LibPicSensors; using TrackRoamer.Robotics.Utility.LibSystem; namespace TrackRoamer.Robotics.Services.TrackRoamerBrickProximityBoard { // The ActivationSettings attribute with Sharing == false makes the runtime dedicate a dispatcher thread pool just for this service. // ExecutionUnitsPerDispatcher - Indicates the number of execution units allocated to the dispatcher // ShareDispatcher - Inidicates whether multiple service instances can be pooled or not [ActivationSettings(ShareDispatcher = false, ExecutionUnitsPerDispatcher = 8)] [Contract(Contract.Identifier)] [DisplayName("(User) TrackRoamer Proximity Brick")] [Description("TrackRoamer Proximity Brick represents a PIC4550 based Proximity Board with sonars and IR sensors")] class TrackRoamerBrickProximityBoardService : DsspServiceBase { // USB Device ID for Proximity Module. Must match definitions in Microchip PIC microcontroller code (USB Device - HID - Proximity Module\Generic HID - Firmware\usb_descriptors.c lines 178, 179) private const Int32 vendorId = 0x0925; private const Int32 productId = 0x7001; private const int openDelayMs = 5000; /// <summary> /// Declare the service state and also the XSLT Transform for displaying it /// </summary> [ServiceState(StateTransform = "TrackRoamer.Robotics.Services.TrackRoamerBrickProximityBoard.TrackRoamerBrickProximityBoard.xslt")] TrackRoamerBrickProximityBoardState _state = new TrackRoamerBrickProximityBoardState() { ProductId = productId, VendorId = vendorId, AngularRange = 180, AngularResolution = ((double)180) / 26.0d, Description = "TrackRoamer Brick Proximity Board Service" }; /// <summary> /// Main service port /// </summary> [ServicePort("/trproxboard", AllowMultipleInstances = false)] TrackRoamerBrickProximityBoardOperations _mainPort = new TrackRoamerBrickProximityBoardOperations(); ProximityBoardCcrServiceCommander _pbCommander; DispatcherQueue _pbCommanderTaskQueue = null; PBCommandPort _pbCommanderDataEventsPort = new PBCommandPort(); // data (Sonar, Direction, Accelerometer, Proximity) is posted to this port by ProximityBoardCcrServiceCommander DsspHttpUtilitiesPort _httpUtilities; /* * others can subscribe for the following types: * UpdateSonarData, UpdateDirectionData, UpdateAccelerometerData, UpdateProximityData, ResetType and whole TrackRoamerBrickProximityBoardState * * example: * * Arbiter.Receive<trpb.UpdateSonarData>(true, _trpbNotify, trpbUpdateNotification) <- put this in interleave * * Type[] notifyMeOf = new Type[] { typeof(trpb.UpdateSonarData) }; * _trpbPort.Subscribe(_trpbNotify, notifyMeOf); * */ [SubscriptionManagerPartner] submgr.SubscriptionManagerPort _submgrPort = new submgr.SubscriptionManagerPort(); /// <summary> /// Service constructor /// </summary> public TrackRoamerBrickProximityBoardService(DsspServiceCreationPort creationPort) : base(creationPort) { Tracer.Trace("TrackRoamerBrickProximityBoardService::TrackRoamerBrickProximityBoardService()"); } /// <summary> /// Service start /// </summary> /// <summary> /// Send phase of construction. /// </summary> protected override void Start() { //if (_state == null) //{ // _state = new TrackRoamerBrickProximityBoardState(); //} Tracer.Trace("TrackRoamerBrickProximityBoardService::Start()"); LogInfo("TrackRoamerBrickProximityBoardService::Start"); _httpUtilities = DsspHttpUtilitiesService.Create(Environment); // // Kick off the connection to the Proximity Board device. // SpawnIterator(0, StartProximityBoard); // This service does not use base.Start() because of the way that // the handlers are hooked up. Also, because of this, there are // explicit Get and HttpGet handlers instead of using the default ones. // Handlers that need write or Exclusive access to state go under // the Exclusive group. Handlers that need read or shared access, and can be // Concurrent to other readers, go to the Concurrent group. // Other internal ports can be included in interleave so you can coordinate // intermediate computation with top level handlers. Activate( Arbiter.Interleave( new TeardownReceiverGroup( Arbiter.Receive<DsspDefaultDrop>(false, _mainPort, DropHandler)), new ExclusiveReceiverGroup( Arbiter.Receive<Replace>(true, _mainPort, ReplaceHandler), Arbiter.Receive<SonarData>(true, _pbCommanderDataEventsPort, SonarMeasurementHandler), Arbiter.Receive<DirectionData>(true, _pbCommanderDataEventsPort, DirectionMeasurementHandler), Arbiter.Receive<AccelerometerData>(true, _pbCommanderDataEventsPort, AccelerometerMeasurementHandler), Arbiter.Receive<ProximityData>(true, _pbCommanderDataEventsPort, ProximityMeasurementHandler), Arbiter.Receive<ParkingSensorData>(true, _pbCommanderDataEventsPort, ParkingSensorMeasurementHandler), Arbiter.Receive<AnalogData>(true, _pbCommanderDataEventsPort, AnalogMeasurementHandler), Arbiter.ReceiveWithIterator<ProximityBoardUsbDeviceAttached>(true, _pbCommanderDataEventsPort, UsbDeviceAttached), Arbiter.ReceiveWithIterator<ProximityBoardUsbDeviceDetached>(true, _pbCommanderDataEventsPort, UsbDeviceDetached), Arbiter.ReceiveWithIterator<Exception>(true, _pbCommanderDataEventsPort, ExceptionHandler)), new ConcurrentReceiverGroup( Arbiter.Receive<DsspDefaultLookup>(true, _mainPort, DefaultLookupHandler), Arbiter.ReceiveWithIterator<Subscribe>(true, _mainPort, SubscribeHandler), Arbiter.Receive<Get>(true, _mainPort, GetHandler), Arbiter.Receive<HttpGet>(true, _mainPort, HttpGetHandler), Arbiter.Receive<Reset>(true, _mainPort, ResetHandler)) ) ); DirectoryInsert(); //base.Start(); } /// <summary> /// Handles Subscribe messages /// </summary> /// <param name="subscribe">the subscribe request</param> [ServiceHandler(ServiceHandlerBehavior.Concurrent)] public IEnumerator<ITask> SubscribeHandler(Subscribe subscribe) { Tracer.Trace("TrackRoamerBrickProximityBoardService::SubscribeHandler() - subscribe request from '" + subscribe.Body.Subscriber + "' for " + subscribe.Body.TypeFilter.Length + " types."); foreach (string tf in subscribe.Body.TypeFilter) { Tracer.Trace(" =========== subscribe requested for type: " + tf); } SubscribeHelper(_submgrPort, subscribe.Body, subscribe.ResponsePort); yield break; } #region Proximity Board initialization and board maintenance /// <summary> /// Start conversation with the TrackRoamer Proximity Board device. /// </summary> IEnumerator<ITask> StartProximityBoard(int timeout) { Tracer.Trace(string.Format("TrackRoamerBrickProximityBoardService::StartProximityBoard() timeout={0} ms", timeout)); _state.LinkState = "Initializing"; if (timeout > 0) { // // caller asked us to wait <timeout> milliseconds until we start. // yield return Arbiter.Receive(false, TimeoutPort(timeout), delegate(DateTime dt) { LogInfo(string.Format("StartProximityBoard() - Done Waiting {0} ms", timeout)); } ); } if (_pbCommanderTaskQueue == null) { // // The internal services run on their own dispatcher, we need to create that (once) // AllocateExecutionResource allocExecRes = new AllocateExecutionResource(0, "TrackRoamerProximityBoard"); ResourceManagerPort.Post(allocExecRes); yield return Arbiter.Choice( allocExecRes.Result, delegate(ExecutionAllocationResult result) { _pbCommanderTaskQueue = result.TaskQueue; }, delegate(Exception e) { LogError(e); } ); } _pbCommander = new ProximityBoardCcrServiceCommander(_pbCommanderTaskQueue ?? TaskQueue, _pbCommanderDataEventsPort, _state.VendorId, _state.ProductId); _pbCommander.Parent = ServiceInfo.Service; _pbCommander.Console = ConsoleOutputPort; _state.IsConnected = false; // Open is an empty operatiion, but we need to flush the internal queue - so let it be. FlushPortSet(_pbCommanderDataEventsPort); bool failed = false; yield return ( Arbiter.Choice( _pbCommander.Open(), delegate(SuccessResult success) { _state.LinkState = "Initializing - link opened"; LogInfo("Opened link to Proximity Board"); }, delegate(Exception exception) { _state.LinkState = "Error Initializing - could not open link"; failed = true; LogError(exception); } ) ); if (failed) { yield break; } // // Set the servo sweep rate: // yield return ( Arbiter.Choice( _pbCommander.SetServoSweepRate(), delegate(SuccessResult success) { _state.LinkState = "Servo Sweep Rate Set"; LogInfo(_state.LinkState); }, delegate(Exception exception) { _state.LinkState = "Error Initializing - could not set Servo Sweep Rate"; failed = true; LogError(exception); } ) ); if (failed) { yield break; } // // start continuous measurements. // yield return ( Arbiter.Choice( _pbCommander.SetContinuous(), delegate(SuccessResult success) { _state.LinkState = "Started Continuous Measurement"; _state.IsConnected = true; LogInfo(_state.LinkState); }, delegate(Exception failure) { _state.LinkState = "Error Initializing - could not start Continuous Measurement"; _pbCommanderDataEventsPort.Post(failure); failed = true; } ) ); if (failed) { yield break; } // somehow the board skips commands on startup, send it twice after a wait: yield return Arbiter.Receive(false, TimeoutPort(1000), delegate(DateTime dt) { } ); // // start continuous measurements - try 2. // yield return ( Arbiter.Choice( _pbCommander.SetContinuous(), delegate(SuccessResult success) { _state.LinkState = "Started Continuous Measurement"; _state.IsConnected = true; LogInfo(_state.LinkState); }, delegate(Exception failure) { _state.LinkState = "Error Initializing - could not start Continuous Measurement"; _pbCommanderDataEventsPort.Post(failure); failed = true; } ) ); if (failed) { yield break; } } private void FlushPortSet(IPortSet portSet) { Tracer.Trace("TrackRoamerBrickProximityBoardService::FlushPortSet()"); // retrieve and discard all messages from all ports in a portset foreach (IPortReceive port in portSet.Ports) { while (port.Test() != null) ; } } IEnumerator<ITask> UsbDeviceDetached(ProximityBoardUsbDeviceDetached linkDetached) { Tracer.Trace("TrackRoamerBrickProximityBoardService::UsbDeviceDetached(): " + linkDetached.Description); _submgrPort.Post(new submgr.Submit(new ResetType(), DsspActions.SubmitRequest)); _state.Description = linkDetached.Description; _state.LinkState = "USB Device Detached - closing link to Proximity Board"; _state.IsConnected = false; LogInfo("Closing link to Proximity Board"); yield return Arbiter.Choice( _pbCommander.Close(), delegate(SuccessResult success) { _state.LinkState = "USB Device Detached - link to Proximity Board closed"; }, delegate(Exception except) { _state.LinkState = "USB Device Detached - Error closing link to Proximity Board"; LogError(except); } ); _state.LinkState = "USB Device Detached - Proximity Board link closed, waiting 5 seconds"; LogInfo(_state.LinkState); _pbCommander = null; SpawnIterator(openDelayMs, StartProximityBoard); yield break; } IEnumerator<ITask> UsbDeviceAttached(ProximityBoardUsbDeviceAttached linkAttached) { bool failed = false; Tracer.Trace("TrackRoamerBrickProximityBoardService::UsbDeviceAttached(): " + linkAttached.Description); _state.Description = linkAttached.Description; _state.LinkState = "USB Device Attached: " + linkAttached.Description; LogInfo(_state.LinkState); // // the device has powered on. Find the HID. // yield return Arbiter.Choice( _pbCommander.TryFindTheHid(), delegate(SuccessResult success) { _state.LinkState = "USB Device Attached - Proximity Module HID Found"; LogInfo(_state.LinkState); }, delegate(Exception failure) { _state.LinkState = "USB Device Attached - Error looking for Proximity Module HID"; _pbCommanderDataEventsPort.Post(failure); failed = true; } ); if (failed) { yield break; } // // Set the servo sweep rate: // yield return Arbiter.Choice( _pbCommander.SetServoSweepRate(), delegate(SuccessResult success) { _state.LinkState = "USB Device Attached - Servo Sweep Rate Set"; LogInfo(_state.LinkState); }, delegate(Exception failure) { _state.LinkState = "USB Device Attached - Error - could not set Servo Sweep Rate"; _pbCommanderDataEventsPort.Post(failure); failed = true; } ); if (failed) { yield break; } // // start continuous measurements. // yield return Arbiter.Choice( _pbCommander.SetContinuous(), delegate(SuccessResult success) { _state.LinkState = "USB Device Attached - started Continuous Measurement"; _state.IsConnected = true; LogInfo(_state.LinkState); }, delegate(Exception failure) { _state.LinkState = "USB Device Attached - Error starting Continuous Measurement"; _pbCommanderDataEventsPort.Post(failure); failed = true; } ); /* if (failed) { yield break; } // // wait for confirm message that signals that the Proximity Board is now in continuous measurement mode. // yield return Arbiter.Choice( Arbiter.Receive<ProximityBoardConfirm>(false, _internalPort, delegate(ProximityBoardConfirm confirm) { // received Confirm }), Arbiter.Receive<DateTime>(false, TimeoutPort(10000), delegate(DateTime time) { _internalPort.Post(new TimeoutException("Timeout waiting for ProximityBoardConfirm after setting continuous measurement mode")); }) ); */ yield break; } #endregion #region Measurement events handlers /// <summary> /// Handle new measurement data from the Proximity Board. /// </summary> /// <param name="measurement">Measurement Data</param> void SonarMeasurementHandler(SonarData measurement) { //Tracer.Trace("TrackRoamerBrickProximityBoardService::SonarMeasurementHandler()"); try { _state.LastSampleTimestamp = new DateTime(measurement.TimeStamp); _state.MostRecentSonar = new SonarDataDssSerializable(measurement); _state.LinkState = "receiving Sonar Data"; // // Inform subscribed services that the state has changed. // _submgrPort.Post(new submgr.Submit(_state, DsspActions.ReplaceRequest)); UpdateSonarData usd = new UpdateSonarData(); usd.Body = _state.MostRecentSonar; //Tracer.Trace(" ========= sending UpdateSonarData notification =================="); base.SendNotification(_submgrPort, usd); } catch (Exception e) { _state.LinkState = "Error while receiving Sonar Data"; LogError(e); } } void DirectionMeasurementHandler(DirectionData measurement) { //Tracer.Trace("TrackRoamerBrickProximityBoardService::DirectionMeasurementHandler()"); try { _state.LastSampleTimestamp = new DateTime(measurement.TimeStamp); _state.MostRecentDirection = new DirectionDataDssSerializable(measurement); _state.LinkState = "receiving Direction Data"; // // Inform subscribed services that the state has changed. // _submgrPort.Post(new submgr.Submit(_state, DsspActions.ReplaceRequest)); UpdateDirectionData usd = new UpdateDirectionData(); usd.Body = _state.MostRecentDirection; base.SendNotification<UpdateDirectionData>(_submgrPort, usd); } catch (Exception e) { _state.LinkState = "Error while receiving Direction Data"; LogError(e); } } void AccelerometerMeasurementHandler(AccelerometerData measurement) { //Tracer.Trace("TrackRoamerBrickProximityBoardService::AccelerometerMeasurementHandler()"); try { _state.LastSampleTimestamp = new DateTime(measurement.TimeStamp); _state.MostRecentAccelerometer = new AccelerometerDataDssSerializable(measurement); _state.LinkState = "receiving Accelerometer Data"; // // Inform subscribed services that the state has changed. // _submgrPort.Post(new submgr.Submit(_state, DsspActions.ReplaceRequest)); UpdateAccelerometerData usd = new UpdateAccelerometerData(); usd.Body = _state.MostRecentAccelerometer; base.SendNotification<UpdateAccelerometerData>(_submgrPort, usd); } catch (Exception e) { _state.LinkState = "Error while receiving Accelerometer Data"; LogError(e); } } void ProximityMeasurementHandler(ProximityData measurement) { //Tracer.Trace("TrackRoamerBrickProximityBoardService::ProximityMeasurementHandler()"); try { _state.LastSampleTimestamp = new DateTime(measurement.TimeStamp); _state.MostRecentProximity = new ProximityDataDssSerializable(measurement); _state.LinkState = "receiving Proximity Data"; // // Inform subscribed services that the state has changed. // _submgrPort.Post(new submgr.Submit(_state, DsspActions.ReplaceRequest)); UpdateProximityData usd = new UpdateProximityData(); usd.Body = _state.MostRecentProximity; base.SendNotification<UpdateProximityData>(_submgrPort, usd); } catch (Exception e) { _state.LinkState = "Error while receiving Proximity Data"; LogError(e); } } void ParkingSensorMeasurementHandler(ParkingSensorData measurement) { //Tracer.Trace("TrackRoamerBrickProximityBoardService::ParkingSensorMeasurementHandler()"); try { _state.LastSampleTimestamp = new DateTime(measurement.TimeStamp); _state.MostRecentParkingSensor = new ParkingSensorDataDssSerializable(measurement); _state.LinkState = "receiving Parking Sensor Data"; // // Inform subscribed services that the state has changed. // _submgrPort.Post(new submgr.Submit(_state, DsspActions.ReplaceRequest)); UpdateParkingSensorData usd = new UpdateParkingSensorData(); usd.Body = _state.MostRecentParkingSensor; base.SendNotification<UpdateParkingSensorData>(_submgrPort, usd); } catch (Exception e) { _state.LinkState = "Error while receiving Parking Sensor Data"; LogError(e); } } void AnalogMeasurementHandler(AnalogData measurement) { //Tracer.Trace("TrackRoamerBrickProximityBoardService::PotMeasurementHandler() analogValue1=" + measurement.analogValue1); try { _state.MostRecentAnalogData = new AnalogDataDssSerializable() { analogValue1 = measurement.analogValue1, TimeStamp = new DateTime(measurement.TimeStamp) }; // // Inform subscribed services that the state has changed. // _submgrPort.Post(new submgr.Submit(_state, DsspActions.ReplaceRequest)); UpdateAnalogData usd = new UpdateAnalogData(); usd.Body = _state.MostRecentAnalogData; base.SendNotification<UpdateAnalogData>(_submgrPort, usd); } catch (Exception e) { _state.LinkState = "Error while receiving POT Data"; LogError(e); } } IEnumerator<ITask> ExceptionHandler(Exception exception) { Tracer.Trace("TrackRoamerBrickProximityBoardService::ExceptionHandler() exception=" + exception); LogError(exception); //BadPacketException bpe = exception as BadPacketException; //if (bpe != null && bpe.Count < 2) //{ // yield break; //} _submgrPort.Post(new submgr.Submit(new ResetType(), DsspActions.SubmitRequest)); _state.LinkState = "Exception " + exception.Message + " - Closing link to Proximity Board"; _state.IsConnected = false; LogInfo("Closing link to Proximity Board"); yield return Arbiter.Choice( _pbCommander.Close(), delegate(SuccessResult success) { }, delegate(Exception except) { LogError(except); } ); _state.LinkState = "Exception " + exception.Message + " - Proximity Board link closed, waiting 5 seconds to reopen"; LogInfo(_state.LinkState); _pbCommander = null; SpawnIterator(openDelayMs, StartProximityBoard); yield break; } #endregion #region DSSP operation handlers void GetHandler(Get get) { Tracer.Trace("TrackRoamerBrickProximityBoardService::GetHandler()"); get.ResponsePort.Post(_state); } void ReplaceHandler(Replace replace) { Tracer.Trace("TrackRoamerBrickProximityBoardService::ReplaceHandler()"); _state = replace.Body; replace.ResponsePort.Post(DefaultReplaceResponseType.Instance); } void DropHandler(DsspDefaultDrop drop) { Tracer.Trace("TrackRoamerBrickProximityBoardService::DropHandler()"); _state.LinkState = "Dropping service - Closing link to Proximity Board"; _state.IsConnected = false; try { if (_pbCommander != null) { // release dispatcher queue resource ResourceManagerPort.Post(new FreeExecutionResource(_pbCommander.TaskQueue)); _pbCommander.Close(); _pbCommander = null; _state.IsConnected = false; } } finally { base.DefaultDropHandler(drop); } } void ResetHandler(Reset reset) { Tracer.Trace("TrackRoamerBrickProximityBoardService::ResetHandler()"); _pbCommanderDataEventsPort.Post(new Exception("External Reset Requested")); reset.ResponsePort.Post(DefaultSubmitResponseType.Instance); } #endregion #region HttpGet Handlers static readonly string _root = "/trproxboard"; static readonly string _raw1 = "raw"; static readonly string _cylinder = "cylinder"; static readonly string _top = "top"; static readonly string _topw = "top/"; // example: http://localhost:50000/trproxboard/cylinder // no [ServiceHandler] here because Start() has been overwritten private void HttpGetHandler(HttpGet httpGet) { HttpListenerRequest request = httpGet.Body.Context.Request; string path = request.Url.AbsolutePath; Stream image = null; bool isMyPath = false; //Tracer.Trace("GET: path='" + path + "'"); if (path.StartsWith(_root)) { path = path.Substring(_root.Length); isMyPath = true; } if (isMyPath) { if (path.StartsWith("/")) { path = path.Substring(1); } if (path == _cylinder) { image = GenerateCylinder(); } else if (path == _top) { image = GenerateTop(600); } else if (path.StartsWith(_topw)) { int width; string remain = path.Substring(_topw.Length); if (int.TryParse(remain, out width)) { image = GenerateTop(width); } } else if (path == "" || path == _raw1) { HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, base.StateTransformPath); httpGet.ResponsePort.Post(rsp); return; } } if (image != null) { SendJpeg(httpGet.Body.Context, image); } else { httpGet.ResponsePort.Post(Fault.FromCodeSubcodeReason( W3C.Soap.FaultCodes.Receiver, DsspFaultCodes.OperationFailed, "Unable to generate Image for path '" + path + "'")); } } private void SendJpeg(HttpListenerContext context, Stream stream) { WriteResponseFromStream write = new WriteResponseFromStream(context, stream, MediaTypeNames.Image.Jpeg); _httpUtilities.Post(write); Activate( Arbiter.Choice( write.ResultPort, delegate(Stream res) { stream.Close(); }, delegate(Exception e) { stream.Close(); LogError(e); } ) ); } #endregion #region Image generators for HttpGet private Stream GenerateCylinder() { SonarDataDssSerializable lsd = _state.MostRecentSonar; if (lsd == null) { return null; } int nRays = lsd.RangeMeters.Length; MemoryStream memory = null; int scalefactor = 23; // 600 / 26 = 23.0769231 - to have width 600px when nRays = 26 int bmpWidth = nRays * scalefactor; int nearRange = 300; int farRange = 2000; int bmpHeight = 100; int topTextHeight = 17; // leave top for the text Font font = new Font(FontFamily.GenericSansSerif, 10, GraphicsUnit.Pixel); using (Bitmap bmp = new Bitmap(bmpWidth, bmpHeight)) { using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.LightGray); int half = (int)Math.Round(bmp.Height * 0.65d); int middle = nRays / 2; int rangeMax = 0; int pointMax = -1; Dictionary<int, string> labels = new Dictionary<int, string>(); for (int i=0; i < nRays ;i++) { int range = (int)(lsd.RangeMeters[i] * 1000.0d); int x = i * scalefactor; if (i == middle) { g.DrawLine(Pens.Gray, x, topTextHeight, x, bmpHeight); } if (range > 0 && range < 8192) { if (range > rangeMax) { rangeMax = range; pointMax = x; } int h = bmp.Height * 300 / range; if (h < 0) { h = 0; } Color col = ColorHelper.LinearColor(Color.OrangeRed, Color.LightGreen, nearRange, farRange, range); //Color col = ColorHelper.LinearColor(Color.DarkBlue, Color.LightGray, 0, 8192, range); g.DrawLine(new Pen(col, (float)scalefactor), bmp.Width - x, Math.Max(topTextHeight, half - h), bmp.Width - x, Math.Min(bmpHeight, half + h)); if (i > 0 && i % 2 == 0 && i < nRays - 1) { double roundRange = Math.Round(range / 1000.0d, 1); // meters string str = "" + roundRange; labels.Add(x, str); } } } foreach (int x in labels.Keys) { // draw labels (distance of every second ray in meters): string str = labels[x]; g.DrawString(str, font, Brushes.Black, bmp.Width - x - 8, (int)(bmpHeight - topTextHeight * 2 + Math.Abs((double)middle - x / scalefactor) * 20 / middle) - 30); } if (pointMax > 0) { // draw a vertical green line where the distance reaches its max value: double roundRangeMax = Math.Round(rangeMax / 1000.0d, 1); // meters int lineWidth = 4; g.DrawLine(new Pen(Color.DarkGreen, (float)lineWidth), bmp.Width - pointMax - lineWidth/2, half, bmp.Width - pointMax - lineWidth/2, bmpHeight); g.DrawString("" + roundRangeMax + "m", font, Brushes.DarkGreen, bmp.Width - pointMax, bmpHeight - topTextHeight); } g.DrawString( lsd.TimeStamp.ToString() + " max: " + rangeMax + " red: <" + nearRange + " green: >" + farRange + " mm", font, Brushes.Black, 0, 0 ); } memory = new MemoryStream(); bmp.Save(memory, ImageFormat.Jpeg); memory.Position = 0; } return memory; } internal class Lbl { public float lx = 0; public float ly = 0; public string label = ""; } private Stream GenerateTop(int imageWidth) { SonarDataDssSerializable lsd = _state.MostRecentSonar; if (lsd == null) { return null; } int nRays = lsd.RangeMeters.Length; MemoryStream memory = null; Font font = new Font(FontFamily.GenericSansSerif, 10, GraphicsUnit.Pixel); // Ultrasonic sensor reaches to about 3.5 meters; we scale the height of our display to this range: double maxExpectedRange = 5000.0d; // mm int imageHeight = imageWidth / 2; int extraHeight = 100; // shows state of proximity sensors using (Bitmap bmp = new Bitmap(imageWidth, imageHeight + extraHeight)) { using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.LightGray); double angularOffset = -90 + 180.0d / 2.0d; double piBy180 = Math.PI / 180.0d; double halfAngle = 1.0d / 2.0d; double scale = imageHeight / maxExpectedRange; double drangeMax = 0.0d; GraphicsPath path = new GraphicsPath(); Dictionary<int, Lbl> labels = new Dictionary<int, Lbl>(); for (int pass = 0; pass != 2; pass++) { for (int i = 0; i < nRays; i++) { int range = (int)(lsd.RangeMeters[i] * 1000.0d); if (range > 0 && range < 8192) { double angle = i * _state.AngularResolution - angularOffset; double lowAngle = (angle - halfAngle) * piBy180; double highAngle = (angle + halfAngle) * piBy180; double drange = range * scale; float lx = (float)(imageHeight + drange * Math.Cos(lowAngle)); float ly = (float)(imageHeight - drange * Math.Sin(lowAngle)); float hx = (float)(imageHeight + drange * Math.Cos(highAngle)); float hy = (float)(imageHeight - drange * Math.Sin(highAngle)); if (pass == 0) { if (i == 0) { path.AddLine(imageHeight, imageHeight, lx, ly); } path.AddLine(lx, ly, hx, hy); drangeMax = Math.Max(drangeMax, drange); } else { g.DrawLine(Pens.DarkBlue, lx, ly, hx, hy); if (i > 0 && i % 2 == 0 && i < nRays - 1) { float llx = (float)(imageHeight + drangeMax * 1.3f * Math.Cos(lowAngle)); float lly = (float)(imageHeight - drangeMax * 1.3f * Math.Sin(lowAngle)); double roundRange = Math.Round(range / 1000.0d, 1); // meters string str = "" + roundRange; labels.Add(i, new Lbl() { label = str, lx = llx, ly = lly }); } } } } if (pass == 0) { g.FillPath(Brushes.White, path); } } // now draw the robot. Trackroamer is 680 mm wide. float botHalfWidth = (float)(680 / 2.0d * scale); DrawHelper.drawRobotBoundaries(g, botHalfWidth, imageWidth / 2, imageHeight); g.DrawString(lsd.TimeStamp.ToString(), font, Brushes.Black, 0, 0); foreach (int x in labels.Keys) { Lbl lbl = labels[x]; g.DrawString(lbl.label, font, Brushes.Black, lbl.lx, lbl.ly); } // draw a 200x400 image of IR proximity sensors: Rectangle drawRect = new Rectangle(imageWidth/2 - extraHeight, imageHeight - extraHeight * 2, extraHeight * 2, extraHeight * 4); if (_state.MostRecentProximity != null) { DrawHelper.drawProximityVectors(g, drawRect, _state.MostRecentProximity.arrangedForDrawing, 1); } if (_state.MostRecentParkingSensor != null) { DrawHelper.drawProximityVectors(g, drawRect, _state.MostRecentParkingSensor.arrangedForDrawing, 2); } } memory = new MemoryStream(); bmp.Save(memory, ImageFormat.Jpeg); memory.Position = 0; } return memory; } #endregion } }
// // SourceRowRenderer.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2005-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; using Gdk; using Pango; using Hyena.Gui.Theming; using Hyena.Gui.Theatrics; using Banshee.ServiceStack; namespace Banshee.Sources.Gui { public class SourceRowRenderer : CellRendererText { public static void CellDataHandler (CellLayout layout, CellRenderer cell, TreeModel model, TreeIter iter) { SourceRowRenderer renderer = cell as SourceRowRenderer; Source source = model.GetValue (iter, 0) as Source; if (renderer == null) { return; } renderer.Source = source; renderer.Path = model.GetPath (iter); if (source == null) { return; } renderer.Text = source.Name; renderer.Sensitive = source.CanActivate; } private Source source; public Source Source { get { return source; } set { source = value; } } private SourceView view; private Widget parent_widget; public Widget ParentWidget { get { return parent_widget; } set { parent_widget = value; } } private TreePath path; public TreePath Path { get { return path; } set { path = value; } } private int padding; public int Padding { get { return padding; } set { padding = value; } } private int row_height = 22; public int RowHeight { get { return row_height; } set { row_height = value; } } public SourceRowRenderer () { } private StateType RendererStateToWidgetState (Widget widget, CellRendererState flags) { if (!Sensitive) { return StateType.Insensitive; } else if ((flags & CellRendererState.Selected) == CellRendererState.Selected) { return widget.HasFocus ? StateType.Selected : StateType.Active; } else if ((flags & CellRendererState.Prelit) == CellRendererState.Prelit) { ComboBox box = parent_widget as ComboBox; return box != null && box.PopupShown ? StateType.Prelight : StateType.Normal; } else if (widget.State == StateType.Insensitive) { return StateType.Insensitive; } else { return StateType.Normal; } } public override void GetSize (Widget widget, ref Gdk.Rectangle cell_area, out int x_offset, out int y_offset, out int width, out int height) { int text_x, text_y, text_w, text_h; base.GetSize (widget, ref cell_area, out text_x, out text_y, out text_w, out text_h); x_offset = 0; y_offset = 0; if (!(widget is TreeView)) { width = 200; } else { width = 0; } height = (int)Math.Max (RowHeight, text_h) + Padding; } protected override void Render (Gdk.Drawable drawable, Widget widget, Gdk.Rectangle background_area, Gdk.Rectangle cell_area, Gdk.Rectangle expose_area, CellRendererState flags) { if (source == null) { return; } view = widget as SourceView; bool path_selected = view != null && view.Selection.PathIsSelected (path); StateType state = RendererStateToWidgetState (widget, flags); RenderSelection (drawable, background_area, path_selected, state); int title_layout_width = 0, title_layout_height = 0; int count_layout_width = 0, count_layout_height = 0; int max_title_layout_width; bool hide_counts = source.Count <= 0; Pixbuf icon = SourceIconResolver.ResolveIcon (source, RowHeight); if (state == StateType.Insensitive) { // Code ported from gtk_cell_renderer_pixbuf_render() var icon_source = new IconSource () { Pixbuf = icon, Size = IconSize.SmallToolbar, SizeWildcarded = false }; icon = widget.Style.RenderIcon (icon_source, widget.Direction, state, (IconSize)(-1), widget, "SourceRowRenderer"); } FontDescription fd = widget.PangoContext.FontDescription.Copy (); fd.Weight = (ISource)ServiceManager.PlaybackController.NextSource == (ISource)source ? Pango.Weight.Bold : Pango.Weight.Normal; if (view != null && source == view.NewPlaylistSource) { fd.Style = Pango.Style.Italic; hide_counts = true; } Pango.Layout title_layout = new Pango.Layout (widget.PangoContext); Pango.Layout count_layout = null; if (!hide_counts) { count_layout = new Pango.Layout (widget.PangoContext); count_layout.FontDescription = fd; count_layout.SetMarkup (String.Format ("<span size=\"small\">{0}</span>", source.Count)); count_layout.GetPixelSize (out count_layout_width, out count_layout_height); } max_title_layout_width = cell_area.Width - (icon == null ? 0 : icon.Width) - count_layout_width - 10; if (!hide_counts && max_title_layout_width < 0) { hide_counts = true; } title_layout.FontDescription = fd; title_layout.Width = (int)(max_title_layout_width * Pango.Scale.PangoScale); title_layout.Ellipsize = EllipsizeMode.End; title_layout.SetText (source.Name); title_layout.GetPixelSize (out title_layout_width, out title_layout_height); Gdk.GC main_gc = widget.Style.TextGC (state); drawable.DrawLayout (main_gc, cell_area.X + (icon == null ? 0 : icon.Width) + 6, Middle (cell_area, title_layout_height), title_layout); if (icon != null) { drawable.DrawPixbuf (main_gc, icon, 0, 0, cell_area.X, Middle (cell_area, icon.Height), icon.Width, icon.Height, RgbDither.None, 0, 0); } if (hide_counts) { return; } Gdk.GC mod_gc = widget.Style.TextGC (state); if (state == StateType.Normal || (view != null && state == StateType.Prelight)) { Gdk.Color fgcolor = widget.Style.Base (state); Gdk.Color bgcolor = widget.Style.Text (state); mod_gc = new Gdk.GC (drawable); mod_gc.Copy (widget.Style.TextGC (state)); mod_gc.RgbFgColor = Hyena.Gui.GtkUtilities.ColorBlend (fgcolor, bgcolor); mod_gc.RgbBgColor = fgcolor; } drawable.DrawLayout (mod_gc, cell_area.X + cell_area.Width - count_layout_width - 2, Middle (cell_area, count_layout_height), count_layout); } private void RenderSelection (Gdk.Drawable drawable, Gdk.Rectangle background_area, bool path_selected, StateType state) { if (view == null) { return; } if (path_selected && view.Cr != null) { Gdk.Rectangle rect = background_area; rect.X -= 2; rect.Width += 4; // clear the standard GTK selection and focus drawable.DrawRectangle (view.Style.BaseGC (StateType.Normal), true, rect); // draw the hot cairo selection if (!view.EditingRow) { view.Theme.DrawRowSelection (view.Cr, background_area.X + 1, background_area.Y + 1, background_area.Width - 2, background_area.Height - 2); } } else if (path != null && path.Equals (view.HighlightedPath) && view.Cr != null) { view.Theme.DrawRowSelection (view.Cr, background_area.X + 1, background_area.Y + 1, background_area.Width - 2, background_area.Height - 2, false); } else if (view.NotifyStage.ActorCount > 0 && view.Cr != null) { TreeIter iter; if (view.Model.GetIter (out iter, path) && view.NotifyStage.Contains (iter)) { Actor<TreeIter> actor = view.NotifyStage[iter]; Cairo.Color color = view.Theme.Colors.GetWidgetColor (GtkColorClass.Background, StateType.Active); color.A = Math.Sin (actor.Percent * Math.PI); view.Theme.DrawRowSelection (view.Cr, background_area.X + 1, background_area.Y + 1, background_area.Width - 2, background_area.Height - 2, true, true, color); } } } private int Middle (Gdk.Rectangle area, int height) { return area.Y + (int)Math.Round ((double)(area.Height - height) / 2.0) + 1; } public override CellEditable StartEditing (Gdk.Event evnt, Widget widget, string path, Gdk.Rectangle background_area, Gdk.Rectangle cell_area, CellRendererState flags) { CellEditEntry text = new CellEditEntry (); text.EditingDone += OnEditDone; text.Text = source.Name; text.path = path; text.Show (); view.EditingRow = true; return text; } private void OnEditDone (object o, EventArgs args) { CellEditEntry edit = (CellEditEntry)o; if (view == null) { return; } view.EditingRow = false; view.UpdateRow (new TreePath (edit.path), edit.Text); } } }
//------------------------------------------------------------------------------ // <copyright file="XsltQilFactory.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ using System.Collections.Generic; using System.Diagnostics; using System.Xml.Schema; using System.Xml.Xsl.Qil; using System.Xml.Xsl.Runtime; using System.Xml.Xsl.XPath; namespace System.Xml.Xsl.Xslt { using Res = System.Xml.Utils.Res; using T = XmlQueryTypeFactory; internal class XsltQilFactory : XPathQilFactory { public XsltQilFactory(QilFactory f, bool debug) : base(f, debug) {} [Conditional("DEBUG")] public void CheckXsltType(QilNode n) { // Five possible types are: anyType, node-set, string, boolean, and number XmlQueryType xt = n.XmlType; switch (xt.TypeCode) { case XmlTypeCode.String: case XmlTypeCode.Boolean: case XmlTypeCode.Double: Debug.Assert(xt.IsSingleton && xt.IsStrict, "Xslt assumes that these types will always be singleton and strict"); break; case XmlTypeCode.Item: case XmlTypeCode.None: break; case XmlTypeCode.QName: Debug.Assert(IsDebug, "QName is reserved as the marker for missing values"); break; default: Debug.Assert(xt.IsNode, "Unexpected expression type: " + xt.ToString()); break; } } [Conditional("DEBUG")] public void CheckQName(QilNode n) { Debug.Assert(n != null && n.XmlType.IsSubtypeOf(T.QNameX), "Must be a singleton QName"); } // We use a value of XmlQualifiedName type to denote a missing parameter public QilNode DefaultValueMarker() { return QName("default-value", XmlReservedNs.NsXslDebug); } public QilNode IsDefaultValueMarker(QilNode n) { return IsType(n, T.QNameX); } public QilNode InvokeIsSameNodeSort(QilNode n1, QilNode n2) { CheckNodeNotRtf(n1); CheckNodeNotRtf(n2); return XsltInvokeEarlyBound(QName("is-same-node-sort"), XsltMethods.IsSameNodeSort, T.BooleanX, new QilNode[] { n1, n2 } ); } public QilNode InvokeSystemProperty(QilNode n) { CheckQName(n); return XsltInvokeEarlyBound(QName("system-property"), XsltMethods.SystemProperty, T.Choice(T.DoubleX, T.StringX), new QilNode[] { n } ); } public QilNode InvokeElementAvailable(QilNode n) { CheckQName(n); return XsltInvokeEarlyBound(QName("element-available"), XsltMethods.ElementAvailable, T.BooleanX, new QilNode[] { n } ); } public QilNode InvokeCheckScriptNamespace(string nsUri) { return XsltInvokeEarlyBound(QName("register-script-namespace"), XsltMethods.CheckScriptNamespace, T.IntX, new QilNode[] { String(nsUri) } ); } public QilNode InvokeFunctionAvailable(QilNode n) { CheckQName(n); return XsltInvokeEarlyBound(QName("function-available"), XsltMethods.FunctionAvailable, T.BooleanX, new QilNode[] { n } ); } public QilNode InvokeBaseUri(QilNode n) { CheckNode(n); return XsltInvokeEarlyBound(QName("base-uri"), XsltMethods.BaseUri, T.StringX, new QilNode[] { n } ); } public QilNode InvokeOnCurrentNodeChanged(QilNode n) { CheckNode(n); return XsltInvokeEarlyBound(QName("on-current-node-changed"), XsltMethods.OnCurrentNodeChanged, T.IntX, new QilNode[] { n } ); } public QilNode InvokeLangToLcid(QilNode n, bool fwdCompat) { CheckString(n); return XsltInvokeEarlyBound(QName("lang-to-lcid"), XsltMethods.LangToLcid, T.IntX, new QilNode[] { n, Boolean(fwdCompat) } ); } public QilNode InvokeNumberFormat(QilNode value, QilNode format, QilNode lang, QilNode letterValue, QilNode groupingSeparator, QilNode groupingSize) { Debug.Assert(value != null && ( value.XmlType.IsSubtypeOf(T.IntXS) || value.XmlType.IsSubtypeOf(T.DoubleX)), "Value must be either a sequence of ints, or a double singleton" ); CheckString(format); CheckDouble(lang); CheckString(letterValue); CheckString(groupingSeparator); CheckDouble(groupingSize); return XsltInvokeEarlyBound(QName("number-format"), XsltMethods.NumberFormat, T.StringX, new QilNode[] { value, format, lang, letterValue, groupingSeparator, groupingSize } ); } public QilNode InvokeRegisterDecimalFormat(DecimalFormatDecl format) { Debug.Assert(format != null); return XsltInvokeEarlyBound(QName("register-decimal-format"), XsltMethods.RegisterDecimalFormat, T.IntX, new QilNode[] { QName(format.Name.Name, format.Name.Namespace), String(format.InfinitySymbol), String(format.NanSymbol), String(new string(format.Characters)) } ); } public QilNode InvokeRegisterDecimalFormatter(QilNode formatPicture, DecimalFormatDecl format) { CheckString(formatPicture); Debug.Assert(format != null); return XsltInvokeEarlyBound(QName("register-decimal-formatter"), XsltMethods.RegisterDecimalFormatter, T.DoubleX, new QilNode[] { formatPicture, String(format.InfinitySymbol), String(format.NanSymbol), String(new string(format.Characters)) } ); } public QilNode InvokeFormatNumberStatic(QilNode value, QilNode decimalFormatIndex) { CheckDouble(value); CheckDouble(decimalFormatIndex); return XsltInvokeEarlyBound(QName("format-number-static"), XsltMethods.FormatNumberStatic, T.StringX, new QilNode[] { value, decimalFormatIndex } ); } public QilNode InvokeFormatNumberDynamic(QilNode value, QilNode formatPicture, QilNode decimalFormatName, QilNode errorMessageName) { CheckDouble(value); CheckString(formatPicture); CheckQName(decimalFormatName); CheckString(errorMessageName); return XsltInvokeEarlyBound(QName("format-number-dynamic"), XsltMethods.FormatNumberDynamic, T.StringX, new QilNode[] { value, formatPicture, decimalFormatName, errorMessageName } ); } public QilNode InvokeOuterXml(QilNode n) { CheckNode(n); return XsltInvokeEarlyBound(QName("outer-xml"), XsltMethods.OuterXml, T.StringX, new QilNode[] { n } ); } public QilNode InvokeMsFormatDateTime(QilNode datetime, QilNode format, QilNode lang, QilNode isDate) { CheckString(datetime); CheckString(format); CheckString(lang); CheckBool(isDate); return XsltInvokeEarlyBound(QName("ms:format-date-time"), XsltMethods.MSFormatDateTime, T.StringX, new QilNode[] { datetime, format, lang, isDate } ); } public QilNode InvokeMsStringCompare(QilNode x, QilNode y, QilNode lang, QilNode options) { CheckString(x ); CheckString(y ); CheckString(lang ); CheckString(options); return XsltInvokeEarlyBound(QName("ms:string-compare"), XsltMethods.MSStringCompare, T.DoubleX, new QilNode[] { x, y, lang, options } ); } public QilNode InvokeMsUtc(QilNode n) { CheckString(n); return XsltInvokeEarlyBound(QName("ms:utc"), XsltMethods.MSUtc, T.StringX, new QilNode[] { n } ); } public QilNode InvokeMsNumber(QilNode n) { return XsltInvokeEarlyBound(QName("ms:number"), XsltMethods.MSNumber, T.DoubleX, new QilNode[] { n } ); } public QilNode InvokeMsLocalName(QilNode n) { CheckString(n); return XsltInvokeEarlyBound(QName("ms:local-name"), XsltMethods.MSLocalName, T.StringX, new QilNode[] { n } ); } public QilNode InvokeMsNamespaceUri(QilNode n, QilNode currentNode) { CheckString(n); CheckNodeNotRtf(currentNode); return XsltInvokeEarlyBound(QName("ms:namespace-uri"), XsltMethods.MSNamespaceUri, T.StringX, new QilNode[] { n, currentNode } ); } public QilNode InvokeEXslObjectType(QilNode n) { return XsltInvokeEarlyBound(QName("exsl:object-type"), XsltMethods.EXslObjectType, T.StringX, new QilNode[] { n } ); } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id$")] namespace Elmah { #region Imports using System; using System.IO; using System.Text.RegularExpressions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using NameValueCollection = System.Collections.Specialized.NameValueCollection; #endregion /// <summary> /// Renders an HTML page displaying details about an error from the /// error log. /// </summary> internal sealed class ErrorDetailPage : ErrorPageBase { private ErrorLogEntry _errorEntry; protected override void OnLoad(EventArgs e) { // // Retrieve the ID of the error to display and read it from // the store. // string errorId = this.Request.QueryString["id"] ?? string.Empty; if (errorId.Length == 0) return; _errorEntry = this.ErrorLog.GetError(errorId); // // Perhaps the error has been deleted from the store? Whatever // the reason, bail out silently. // if (_errorEntry == null) { Response.Status = HttpStatus.NotFound.ToString(); return; } // // Setup the title of the page. // this.PageTitle = string.Format("Error: {0} [{1}]", _errorEntry.Error.Type, _errorEntry.Id); base.OnLoad(e); } protected override void RenderContents(HtmlTextWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); if (_errorEntry != null) RenderError(writer); else RenderNoError(writer); } private static void RenderNoError(HtmlTextWriter writer) { Debug.Assert(writer != null); writer.RenderBeginTag(HtmlTextWriterTag.P); writer.Write("Error not found in log."); writer.RenderEndTag(); // </p> writer.WriteLine(); } private void RenderError(HtmlTextWriter writer) { Debug.Assert(writer != null); Error error = _errorEntry.Error; // // Write out the page title containing error type and message. // writer.AddAttribute(HtmlTextWriterAttribute.Id, "PageTitle"); writer.RenderBeginTag(HtmlTextWriterTag.H1); HtmlEncode(error.Message, writer); writer.RenderEndTag(); // </h1> writer.WriteLine(); SpeedBar.Render(writer, SpeedBar.Home.Format(BasePageName), SpeedBar.Help, SpeedBar.About.Format(BasePageName)); writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTitle"); writer.RenderBeginTag(HtmlTextWriterTag.P); writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorType"); writer.RenderBeginTag(HtmlTextWriterTag.Span); HtmlEncode(error.Type, writer); writer.RenderEndTag(); // </span> writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTypeMessageSeparator"); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(": "); writer.RenderEndTag(); // </span> writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorMessage"); writer.RenderBeginTag(HtmlTextWriterTag.Span); HtmlEncode(error.Message, writer); writer.RenderEndTag(); // </span> writer.RenderEndTag(); // </p> writer.WriteLine(); // // Do we have details, like the stack trace? If so, then write // them out in a pre-formatted (pre) element. // NOTE: There is an assumption here that detail will always // contain a stack trace. If it doesn't then pre-formatting // might not be the right thing to do here. // if (error.Detail.Length != 0) { writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorDetail"); writer.RenderBeginTag(HtmlTextWriterTag.Pre); writer.Flush(); MarkupStackTrace(error.Detail, writer.InnerWriter); writer.RenderEndTag(); // </pre> writer.WriteLine(); } // // Write out the error log time. This will be in the local // time zone of the server. Would be a good idea to indicate // it here for the user. // writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorLogTime"); writer.RenderBeginTag(HtmlTextWriterTag.P); HtmlEncode(string.Format("Logged on {0} at {1}", error.Time.ToLongDateString(), error.Time.ToLongTimeString()), writer); writer.RenderEndTag(); // </p> writer.WriteLine(); // // Render alternate links. // writer.RenderBeginTag(HtmlTextWriterTag.P); writer.Write("See also:"); writer.RenderEndTag(); // </p> writer.WriteLine(); writer.RenderBeginTag(HtmlTextWriterTag.Ul); // // Do we have an HTML formatted message from ASP.NET? If yes // then write out a link to it instead of embedding it // with the rest of the content since it is an entire HTML // document in itself. // if (error.WebHostHtmlMessage.Length != 0) { writer.RenderBeginTag(HtmlTextWriterTag.Li); string htmlUrl = this.BasePageName + "/html?id=" + HttpUtility.UrlEncode(_errorEntry.Id); writer.AddAttribute(HtmlTextWriterAttribute.Href, htmlUrl); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write("Original ASP.NET error page"); writer.RenderEndTag(); // </a> writer.RenderEndTag(); // </li> } // // Add a link to the source XML and JSON data. // writer.RenderBeginTag(HtmlTextWriterTag.Li); writer.Write("Raw/Source data in "); writer.AddAttribute(HtmlTextWriterAttribute.Href, "xml" + Request.Url.Query); writer.AddAttribute(HtmlTextWriterAttribute.Rel, HtmlLinkType.Alternate); writer.AddAttribute(HtmlTextWriterAttribute.Type, "application/xml"); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write("XML"); writer.RenderEndTag(); // </a> writer.Write(" or in "); writer.AddAttribute(HtmlTextWriterAttribute.Href, "json" + Request.Url.Query); writer.AddAttribute(HtmlTextWriterAttribute.Rel, HtmlLinkType.Alternate); writer.AddAttribute(HtmlTextWriterAttribute.Type, "application/json"); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write("JSON"); writer.RenderEndTag(); // </a> writer.RenderEndTag(); // </li> // // End of alternate links. // writer.RenderEndTag(); // </ul> // // If this error has context, then write it out. // ServerVariables are good enough for most purposes, so // we only write those out at this time. // RenderCollection(writer, error.ServerVariables, "ServerVariables", "Server Variables"); base.RenderContents(writer); } private void RenderCollection(HtmlTextWriter writer, NameValueCollection collection, string id, string title) { Debug.Assert(writer != null); Debug.AssertStringNotEmpty(id); Debug.AssertStringNotEmpty(title); // // If the collection isn't there or it's empty, then bail out. // if (collection == null || collection.Count == 0) return; // // Surround the entire section with a <div> element. // writer.AddAttribute(HtmlTextWriterAttribute.Id, id); writer.RenderBeginTag(HtmlTextWriterTag.Div); // // Write out the table caption. // writer.AddAttribute(HtmlTextWriterAttribute.Class, "table-caption"); writer.RenderBeginTag(HtmlTextWriterTag.P); this.HtmlEncode(title, writer); writer.RenderEndTag(); // </p> writer.WriteLine(); // // Some values can be large and add scroll bars to the page // as well as ruin some formatting. So we encapsulate the // table into a scrollable view that is controlled via the // style sheet. // writer.AddAttribute(HtmlTextWriterAttribute.Class, "scroll-view"); writer.RenderBeginTag(HtmlTextWriterTag.Div); // // Create a table to display the name/value pairs of the // collection in 2 columns. // Table table = new Table(); table.CellSpacing = 0; // // Create the header row and columns. // TableRow headRow = new TableRow(); TableHeaderCell headCell; headCell = new TableHeaderCell(); headCell.Wrap = false; headCell.Text = "Name"; headCell.CssClass = "name-col"; headRow.Cells.Add(headCell); headCell = new TableHeaderCell(); headCell.Wrap = false; headCell.Text = "Value"; headCell.CssClass = "value-col"; headRow.Cells.Add(headCell); table.Rows.Add(headRow); // // Create a row for each entry in the collection. // string[] keys = collection.AllKeys; Array.Sort(keys, StringComparer.InvariantCulture); for (int keyIndex = 0; keyIndex < keys.Length; keyIndex++) { string key = keys[keyIndex]; TableRow bodyRow = new TableRow(); bodyRow.CssClass = keyIndex % 2 == 0 ? "even-row" : "odd-row"; TableCell cell; // // Create the key column. // cell = new TableCell(); cell.Text = HtmlEncode(key); cell.CssClass = "key-col"; bodyRow.Cells.Add(cell); // // Create the value column. // cell = new TableCell(); cell.Text = HtmlEncode(collection[key]); cell.CssClass = "value-col"; bodyRow.Cells.Add(cell); table.Rows.Add(bodyRow); } // // Write out the table and close container tags. // table.RenderControl(writer); writer.RenderEndTag(); // </div> writer.WriteLine(); writer.RenderEndTag(); // </div> writer.WriteLine(); } private static readonly Regex _reStackTrace = new Regex(@" ^ \s* \w+ \s+ (?<type> .+ ) \. (?<method> .+? ) (?<params> \( (?<params> .*? ) \) ) ( \s+ \w+ \s+ (?<file> [a-z] \: .+? ) \: \w+ \s+ (?<line> [0-9]+ ) \p{P}? )? \s* $", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); private void MarkupStackTrace(string text, TextWriter writer) { Debug.Assert(text != null); Debug.Assert(writer != null); int anchor = 0; foreach (Match match in _reStackTrace.Matches(text)) { HtmlEncode(text.Substring(anchor, match.Index - anchor), writer); MarkupStackFrame(text, match, writer); anchor = match.Index + match.Length; } HtmlEncode(text.Substring(anchor), writer); } private void MarkupStackFrame(string text, Match match, TextWriter writer) { Debug.Assert(text != null); Debug.Assert(match != null); Debug.Assert(writer != null); int anchor = match.Index; GroupCollection groups = match.Groups; // // Type + Method // Group type = groups["type"]; HtmlEncode(text.Substring(anchor, type.Index - anchor), writer); anchor = type.Index; writer.Write("<span class='st-frame'>"); anchor = StackFrameSpan(text, anchor, "st-type", type, writer); anchor = StackFrameSpan(text, anchor, "st-method", groups["method"], writer); // // Parameters // Group parameters = groups["params"]; HtmlEncode(text.Substring(anchor, parameters.Index - anchor), writer); writer.Write("<span class='st-params'>("); int position = 0; foreach (string parameter in parameters.Captures[0].Value.Split(',')) { int spaceIndex = parameter.LastIndexOf(' '); if (spaceIndex <= 0) { Span(writer, "st-param", parameter.Trim()); } else { if (position++ > 0) writer.Write(", "); string argType = parameter.Substring(0, spaceIndex).Trim(); Span(writer, "st-param-type", argType); writer.Write(' '); string argName = parameter.Substring(spaceIndex + 1).Trim(); Span(writer, "st-param-name", argName); } } writer.Write(")</span>"); anchor = parameters.Index + parameters.Length; // // File + Line // anchor = StackFrameSpan(text, anchor, "st-file", groups["file"], writer); anchor = StackFrameSpan(text, anchor, "st-line", groups["line"], writer); writer.Write("</span>"); // // Epilogue // int end = match.Index + match.Length; HtmlEncode(text.Substring(anchor, end - anchor), writer); } private int StackFrameSpan(string text, int anchor, string klass, Group group, TextWriter writer) { Debug.Assert(text != null); Debug.Assert(group != null); Debug.Assert(writer != null); return group.Success ? StackFrameSpan(text, anchor, klass, group.Value, group.Index, group.Length, writer) : anchor; } private int StackFrameSpan(string text, int anchor, string klass, string value, int index, int length, TextWriter writer) { Debug.Assert(text != null); Debug.Assert(writer != null); HtmlEncode(text.Substring(anchor, index - anchor), writer); Span(writer, klass, value); return index + length; } private void Span(TextWriter writer, string klass, string value) { Debug.Assert(writer != null); writer.Write("<span class='"); writer.Write(klass); writer.Write("'>"); HtmlEncode(value, writer); writer.Write("</span>"); } private string HtmlEncode(string text) { return Server.HtmlEncode(text); } private void HtmlEncode(string text, TextWriter writer) { Debug.Assert(writer != null); Server.HtmlEncode(text, writer); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** ** Purpose: Defines the settings that the loader uses to find assemblies in an ** AppDomain ** ** =============================================================================*/ namespace System { using System.Text; using System.Runtime.InteropServices; using System.Security; using Path = System.IO.Path; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Generic; internal sealed class AppDomainSetup { internal enum LoaderInformation { // If you add a new value, add the corresponding property // to AppDomain.GetData() and SetData()'s switch statements, // as well as fusionsetup.h. ApplicationBaseValue = 0, // LOADER_APPLICATION_BASE ConfigurationFileValue = 1, // LOADER_CONFIGURATION_BASE DynamicBaseValue = 2, // LOADER_DYNAMIC_BASE DevPathValue = 3, // LOADER_DEVPATH ApplicationNameValue = 4, // LOADER_APPLICATION_NAME PrivateBinPathValue = 5, // LOADER_PRIVATE_PATH PrivateBinPathProbeValue = 6, // LOADER_PRIVATE_BIN_PATH_PROBE ShadowCopyDirectoriesValue = 7, // LOADER_SHADOW_COPY_DIRECTORIES ShadowCopyFilesValue = 8, // LOADER_SHADOW_COPY_FILES CachePathValue = 9, // LOADER_CACHE_PATH LicenseFileValue = 10, // LOADER_LICENSE_FILE DisallowPublisherPolicyValue = 11, // LOADER_DISALLOW_PUBLISHER_POLICY DisallowCodeDownloadValue = 12, // LOADER_DISALLOW_CODE_DOWNLOAD DisallowBindingRedirectsValue = 13, // LOADER_DISALLOW_BINDING_REDIRECTS DisallowAppBaseProbingValue = 14, // LOADER_DISALLOW_APPBASE_PROBING ConfigurationBytesValue = 15, // LOADER_CONFIGURATION_BYTES LoaderMaximum = 18 // LOADER_MAXIMUM } // Constants from fusionsetup.h. private const string LOADER_OPTIMIZATION = "LOADER_OPTIMIZATION"; private const string ACTAG_APP_BASE_URL = "APPBASE"; // This class has an unmanaged representation so be aware you will need to make edits in vm\object.h if you change the order // of these fields or add new ones. private string[] _Entries; #pragma warning disable 169 private String _AppBase; // for compat with v1.1 #pragma warning restore 169 // A collection of strings used to indicate which breaking changes shouldn't be applied // to an AppDomain. We only use the keys, the values are ignored. private Dictionary<string, object> _CompatFlags; #if FEATURE_RANDOMIZED_STRING_HASHING private bool _UseRandomizedStringHashing; #endif internal AppDomainSetup(AppDomainSetup copy, bool copyDomainBoundData) { string[] mine = Value; if (copy != null) { string[] other = copy.Value; int mineSize = _Entries.Length; int otherSize = other.Length; int size = (otherSize < mineSize) ? otherSize : mineSize; for (int i = 0; i < size; i++) mine[i] = other[i]; if (size < mineSize) { // This case can happen when the copy is a deserialized version of // an AppDomainSetup object serialized by Everett. for (int i = size; i < mineSize; i++) mine[i] = null; } if (copy._CompatFlags != null) { SetCompatibilitySwitches(copy._CompatFlags.Keys); } #if FEATURE_RANDOMIZED_STRING_HASHING _UseRandomizedStringHashing = copy._UseRandomizedStringHashing; #endif } } public AppDomainSetup() { } internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false) { char[] sep = { '\\', '/' }; int i = imageLocation.LastIndexOfAny(sep); if (i == -1) { ApplicationName = imageLocation; } else { ApplicationName = imageLocation.Substring(i + 1); string appBase = imageLocation.Substring(0, i + 1); if (imageLocationAlreadyNormalized) Value[(int)LoaderInformation.ApplicationBaseValue] = appBase; else ApplicationBase = appBase; } } internal string[] Value { get { if (_Entries == null) _Entries = new String[(int)LoaderInformation.LoaderMaximum]; return _Entries; } } public String ApplicationBase { [Pure] get { return Value[(int)LoaderInformation.ApplicationBaseValue]; } set { Value[(int)LoaderInformation.ApplicationBaseValue] = (value == null || value.Length == 0)?null:Path.GetFullPath(value); } } // only needed by AppDomain.Setup(). Not really needed by users. internal Dictionary<string, object> GetCompatibilityFlags() { return _CompatFlags; } public void SetCompatibilitySwitches(IEnumerable<String> switches) { #if FEATURE_RANDOMIZED_STRING_HASHING _UseRandomizedStringHashing = false; #endif if (switches != null) { _CompatFlags = new Dictionary<string, object>(); foreach (String str in switches) { #if FEATURE_RANDOMIZED_STRING_HASHING if (StringComparer.OrdinalIgnoreCase.Equals("UseRandomizedStringHashAlgorithm", str)) { _UseRandomizedStringHashing = true; } #endif _CompatFlags.Add(str, null); } } else { _CompatFlags = null; } } // A target Framework moniker, in a format parsible by the FrameworkName class. public String TargetFrameworkName { get { return null; } } public String ApplicationName { get { return Value[(int)LoaderInformation.ApplicationNameValue]; } set { Value[(int)LoaderInformation.ApplicationNameValue] = value; } } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DynamoDB.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DynamoDB.Model.Internal.MarshallTransformations { /// <summary> /// Put Item Request Marshaller /// </summary> internal class PutItemRequestMarshaller : IMarshaller<IRequest, PutItemRequest> { public IRequest Marshall(PutItemRequest putItemRequest) { IRequest request = new DefaultRequest(putItemRequest, "AmazonDynamoDB"); string target = "DynamoDB_20111205.PutItem"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.0"; string uriResourcePath = ""; if (uriResourcePath.Contains("?")) { string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1); uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?")); foreach (string s in queryString.Split('&', ';')) { string[] nameValuePair = s.Split('='); if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0) { request.Parameters.Add(nameValuePair[0], nameValuePair[1]); } else { request.Parameters.Add(nameValuePair[0], null); } } } request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter()) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); if (putItemRequest != null && putItemRequest.IsSetTableName()) { writer.WritePropertyName("TableName"); writer.Write(putItemRequest.TableName); } if (putItemRequest != null) { if (putItemRequest.Item != null) { writer.WritePropertyName("Item"); writer.WriteObjectStart(); foreach (string putItemRequestItemKey in putItemRequest.Item.Keys) { AttributeValue itemListValue; bool itemListValueHasValue = putItemRequest.Item.TryGetValue(putItemRequestItemKey, out itemListValue); writer.WritePropertyName(putItemRequestItemKey); writer.WriteObjectStart(); if (itemListValue != null && itemListValue.IsSetS()) { writer.WritePropertyName("S"); writer.Write(itemListValue.S); } if (itemListValue != null && itemListValue.IsSetN()) { writer.WritePropertyName("N"); writer.Write(itemListValue.N); } if (itemListValue != null && itemListValue.IsSetB()) { writer.WritePropertyName("B"); writer.Write(StringUtils.FromMemoryStream(itemListValue.B)); } if (itemListValue != null && itemListValue.SS != null && itemListValue.SS.Count > 0) { List<string> sSList = itemListValue.SS; writer.WritePropertyName("SS"); writer.WriteArrayStart(); foreach (string sSListValue in sSList) { writer.Write(StringUtils.FromString(sSListValue)); } writer.WriteArrayEnd(); } if (itemListValue != null && itemListValue.NS != null && itemListValue.NS.Count > 0) { List<string> nSList = itemListValue.NS; writer.WritePropertyName("NS"); writer.WriteArrayStart(); foreach (string nSListValue in nSList) { writer.Write(StringUtils.FromString(nSListValue)); } writer.WriteArrayEnd(); } if (itemListValue != null && itemListValue.BS != null && itemListValue.BS.Count > 0) { List<MemoryStream> bSList = itemListValue.BS; writer.WritePropertyName("BS"); writer.WriteArrayStart(); foreach (MemoryStream bSListValue in bSList) { writer.Write(StringUtils.FromMemoryStream(bSListValue)); } writer.WriteArrayEnd(); } writer.WriteObjectEnd(); } writer.WriteObjectEnd(); } } if (putItemRequest != null) { if (putItemRequest.Expected != null) { writer.WritePropertyName("Expected"); writer.WriteObjectStart(); foreach (string putItemRequestExpectedKey in putItemRequest.Expected.Keys) { ExpectedAttributeValue expectedListValue; bool expectedListValueHasValue = putItemRequest.Expected.TryGetValue(putItemRequestExpectedKey, out expectedListValue); writer.WritePropertyName(putItemRequestExpectedKey); writer.WriteObjectStart(); if (expectedListValue != null) { AttributeValue value = expectedListValue.Value; if (value != null) { writer.WritePropertyName("Value"); writer.WriteObjectStart(); if (value != null && value.IsSetS()) { writer.WritePropertyName("S"); writer.Write(value.S); } if (value != null && value.IsSetN()) { writer.WritePropertyName("N"); writer.Write(value.N); } if (value != null && value.IsSetB()) { writer.WritePropertyName("B"); writer.Write(StringUtils.FromMemoryStream(value.B)); } if (value != null && value.SS != null && value.SS.Count > 0) { List<string> sSList = value.SS; writer.WritePropertyName("SS"); writer.WriteArrayStart(); foreach (string sSListValue in sSList) { writer.Write(StringUtils.FromString(sSListValue)); } writer.WriteArrayEnd(); } if (value != null && value.NS != null && value.NS.Count > 0) { List<string> nSList = value.NS; writer.WritePropertyName("NS"); writer.WriteArrayStart(); foreach (string nSListValue in nSList) { writer.Write(StringUtils.FromString(nSListValue)); } writer.WriteArrayEnd(); } if (value != null && value.BS != null && value.BS.Count > 0) { List<MemoryStream> bSList = value.BS; writer.WritePropertyName("BS"); writer.WriteArrayStart(); foreach (MemoryStream bSListValue in bSList) { writer.Write(StringUtils.FromMemoryStream(bSListValue)); } writer.WriteArrayEnd(); } writer.WriteObjectEnd(); } } if (expectedListValue != null && expectedListValue.IsSetExists()) { writer.WritePropertyName("Exists"); writer.Write(expectedListValue.Exists); } writer.WriteObjectEnd(); } writer.WriteObjectEnd(); } } if (putItemRequest != null && putItemRequest.IsSetReturnValues()) { writer.WritePropertyName("ReturnValues"); writer.Write(putItemRequest.ReturnValues); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; #if CORE #endif #if GDI using System.Drawing; #endif #if WPF using System.Windows; using SysPoint = System.Windows.Point; using SysSize = System.Windows.Size; #endif #if NETFX_CORE using Windows.UI.Xaml.Media; using SysPoint = Windows.Foundation.Point; using SysSize = Windows.Foundation.Size; #endif #if !EDF_CORE using PdfSharp.Internal; #else using PdfSharp.Internal; #endif #if !EDF_CORE namespace PdfSharp.Drawing #else namespace Edf.Drawing #endif { /// <summary> /// Represents a pair of floating point x- and y-coordinates that defines a point /// in a two-dimensional plane. /// </summary> [DebuggerDisplay("{DebuggerDisplay}")] [Serializable] [StructLayout(LayoutKind.Sequential)] // TypeConverter(typeof(PointConverter)), ValueSerializer(typeof(PointValueSerializer))] public struct XPoint : IFormattable { /// <summary> /// Initializes a new instance of the XPoint class with the specified coordinates. /// </summary> public XPoint(double x, double y) { _x = x; _y = y; } #if GDI /// <summary> /// Initializes a new instance of the XPoint class with the specified point. /// </summary> public XPoint(System.Drawing.Point point) { _x = point.X; _y = point.Y; } #endif #if WPF || NETFX_CORE /// <summary> /// Initializes a new instance of the XPoint class with the specified point. /// </summary> public XPoint(SysPoint point) { _x = point.X; _y = point.Y; } #endif #if GDI /// <summary> /// Initializes a new instance of the XPoint class with the specified point. /// </summary> public XPoint(PointF point) { _x = point.X; _y = point.Y; } #endif /// <summary> /// Determines whether two points are equal. /// </summary> public static bool operator ==(XPoint point1, XPoint point2) { // ReSharper disable CompareOfFloatsByEqualityOperator return point1._x == point2._x && point1._y == point2._y; // ReSharper restore CompareOfFloatsByEqualityOperator } /// <summary> /// Determines whether two points are not equal. /// </summary> public static bool operator !=(XPoint point1, XPoint point2) { return !(point1 == point2); } /// <summary> /// Indicates whether the specified points are equal. /// </summary> public static bool Equals(XPoint point1, XPoint point2) { return point1.X.Equals(point2.X) && point1.Y.Equals(point2.Y); } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> public override bool Equals(object o) { if (!(o is XPoint)) return false; return Equals(this, (XPoint)o); } /// <summary> /// Indicates whether this instance and a specified point are equal. /// </summary> public bool Equals(XPoint value) { return Equals(this, value); } /// <summary> /// Returns the hash code for this instance. /// </summary> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } /// <summary> /// Parses the point from a string. /// </summary> public static XPoint Parse(string source) { CultureInfo cultureInfo = CultureInfo.InvariantCulture; TokenizerHelper helper = new TokenizerHelper(source, cultureInfo); string str = helper.NextTokenRequired(); XPoint point = new XPoint(Convert.ToDouble(str, cultureInfo), Convert.ToDouble(helper.NextTokenRequired(), cultureInfo)); helper.LastTokenRequired(); return point; } /// <summary> /// Parses an array of points from a string. /// </summary> public static XPoint[] ParsePoints(string value) { if (value == null) throw new ArgumentNullException("value"); // TODO: Reflect reliabel implementation from Avalon // TODOWPF string[] values = value.Split(' '); int count = values.Length; XPoint[] points = new XPoint[count]; for (int idx = 0; idx < count; idx++) points[idx] = Parse(values[idx]); return points; } /// <summary> /// Gets the x-coordinate of this XPoint. /// </summary> public double X { get { return _x; } set { _x = value; } } double _x; /// <summary> /// Gets the x-coordinate of this XPoint. /// </summary> public double Y { get { return _y; } set { _y = value; } } double _y; #if CORE #if UseGdiObjects /// <summary> /// Converts this XPoint to a System.Drawing.Point. /// </summary> public PointF ToPointF() { return new PointF((float)_x, (float)_y); } #endif #endif #if GDI /// <summary> /// Converts this XPoint to a System.Drawing.Point. /// </summary> public PointF ToPointF() { return new PointF((float)_x, (float)_y); } #endif #if WPF || NETFX_CORE /// <summary> /// Converts this XPoint to a System.Windows.Point. /// </summary> public SysPoint ToPoint() { return new SysPoint(_x, _y); } #endif /// <summary> /// Converts this XPoint to a human readable string. /// </summary> public override string ToString() { return ConvertToString(null, null); } /// <summary> /// Converts this XPoint to a human readable string. /// </summary> public string ToString(IFormatProvider provider) { return ConvertToString(null, provider); } /// <summary> /// Converts this XPoint to a human readable string. /// </summary> string IFormattable.ToString(string format, IFormatProvider provider) { return ConvertToString(format, provider); } /// <summary> /// Implements ToString. /// </summary> internal string ConvertToString(string format, IFormatProvider provider) { char numericListSeparator = TokenizerHelper.GetNumericListSeparator(provider); provider = provider ?? CultureInfo.InvariantCulture; return string.Format(provider, "{1:" + format + "}{0}{2:" + format + "}", new object[] { numericListSeparator, _x, _y }); } /// <summary> /// Offsets the x and y value of this point. /// </summary> public void Offset(double offsetX, double offsetY) { _x += offsetX; _y += offsetY; } /// <summary> /// Adds a point and a vector. /// </summary> public static XPoint operator +(XPoint point, XVector vector) { return new XPoint(point._x + vector.X, point._y + vector.Y); } /// <summary> /// Adds a point and a size. /// </summary> public static XPoint operator +(XPoint point, XSize size) // TODO: make obsolete { return new XPoint(point._x + size.Width, point._y + size.Height); } /// <summary> /// Adds a point and a vector. /// </summary> public static XPoint Add(XPoint point, XVector vector) { return new XPoint(point._x + vector.X, point._y + vector.Y); } /// <summary> /// Subtracts a vector from a point. /// </summary> public static XPoint operator -(XPoint point, XVector vector) { return new XPoint(point._x - vector.X, point._y - vector.Y); } /// <summary> /// Subtracts a vector from a point. /// </summary> public static XPoint Subtract(XPoint point, XVector vector) { return new XPoint(point._x - vector.X, point._y - vector.Y); } /// <summary> /// Subtracts a point from a point. /// </summary> public static XVector operator -(XPoint point1, XPoint point2) { return new XVector(point1._x - point2._x, point1._y - point2._y); } /// <summary> /// Subtracts a size from a point. /// </summary> [Obsolete("Use XVector instead of XSize as second parameter.")] public static XPoint operator -(XPoint point, XSize size) // TODO: make obsolete { return new XPoint(point._x - size.Width, point._y - size.Height); } /// <summary> /// Subtracts a point from a point. /// </summary> public static XVector Subtract(XPoint point1, XPoint point2) { return new XVector(point1._x - point2._x, point1._y - point2._y); } /// <summary> /// Multiplies a point with a matrix. /// </summary> public static XPoint operator *(XPoint point, XMatrix matrix) { return matrix.Transform(point); } /// <summary> /// Multiplies a point with a matrix. /// </summary> public static XPoint Multiply(XPoint point, XMatrix matrix) { return matrix.Transform(point); } /// <summary> /// Multiplies a point with a scalar value. /// </summary> public static XPoint operator *(XPoint point, double value) { return new XPoint(point._x * value, point._y * value); } /// <summary> /// Multiplies a point with a scalar value. /// </summary> public static XPoint operator *(double value, XPoint point) { return new XPoint(value * point._x, value * point._y); } /// <summary> /// Performs an explicit conversion from XPoint to XSize. /// </summary> public static explicit operator XSize(XPoint point) { return new XSize(Math.Abs(point._x), Math.Abs(point._y)); } /// <summary> /// Performs an explicit conversion from XPoint to XVector. /// </summary> public static explicit operator XVector(XPoint point) { return new XVector(point._x, point._y); } #if WPF || NETFX_CORE /// <summary> /// Performs an implicit conversion from XPoint to Point. /// </summary> public static implicit operator SysPoint(XPoint point) { return new SysPoint(point.X, point.Y); } /// <summary> /// Performs an implicit conversion from Point to XPoint. /// </summary> public static implicit operator XPoint(SysPoint point) { return new XPoint(point.X, point.Y); } #endif /// <summary> /// Gets the DebuggerDisplayAttribute text. /// </summary> // ReSharper disable UnusedMember.Local string DebuggerDisplay // ReSharper restore UnusedMember.Local { get { const string format = Config.SignificantFigures10; return String.Format(CultureInfo.InvariantCulture, "point=({0:" + format + "}, {1:" + format + "})", _x, _y); } } } }
using System; using System.Diagnostics; using System.IO; using System.Linq; using Mono.Cecil; using NUnit.Framework; namespace Mono.Cecil.Tests { [TestFixture] public class ModuleTests : BaseTestFixture { [Test] public void CreateModuleEscapesAssemblyName () { var module = ModuleDefinition.CreateModule ("Test.dll", ModuleKind.Dll); Assert.AreEqual ("Test", module.Assembly.Name.Name); module = ModuleDefinition.CreateModule ("Test.exe", ModuleKind.Console); Assert.AreEqual ("Test", module.Assembly.Name.Name); } [Test] public void SingleModule () { TestModule ("hello.exe", module => { var assembly = module.Assembly; Assert.AreEqual (1, assembly.Modules.Count); Assert.IsNotNull (assembly.MainModule); }); } [Test] public void EntryPoint () { TestModule ("hello.exe", module => { var entry_point = module.EntryPoint; Assert.IsNotNull (entry_point); Assert.AreEqual ("System.Void Program::Main()", entry_point.ToString ()); module.EntryPoint = null; Assert.IsNull (module.EntryPoint); module.EntryPoint = entry_point; Assert.IsNotNull (module.EntryPoint); }); } [Test] public void MultiModules () { IgnoreOnCoreClr (); TestModule("mma.exe", module => { var assembly = module.Assembly; Assert.AreEqual (3, assembly.Modules.Count); Assert.AreEqual ("mma.exe", assembly.Modules [0].Name); Assert.AreEqual (ModuleKind.Console, assembly.Modules [0].Kind); Assert.AreEqual ("moda.netmodule", assembly.Modules [1].Name); Assert.AreEqual ("eedb4721-6c3e-4d9a-be30-49021121dd92", assembly.Modules [1].Mvid.ToString ()); Assert.AreEqual (ModuleKind.NetModule, assembly.Modules [1].Kind); Assert.AreEqual ("modb.netmodule", assembly.Modules [2].Name); Assert.AreEqual ("46c5c577-11b2-4ea0-bb3c-3c71f1331dd0", assembly.Modules [2].Mvid.ToString ()); Assert.AreEqual (ModuleKind.NetModule, assembly.Modules [2].Kind); }); } [Test] public void ModuleInformation () { TestModule ("hello.exe", module => { Assert.IsNotNull (module); Assert.AreEqual ("hello.exe", module.Name); Assert.AreEqual (new Guid ("C3BC2BD3-2576-4D00-A80E-465B5632415F"), module.Mvid); }); } [Test] public void AssemblyReferences () { TestModule ("hello.exe", module => { Assert.AreEqual (1, module.AssemblyReferences.Count); var reference = module.AssemblyReferences [0]; Assert.AreEqual ("mscorlib", reference.Name); Assert.AreEqual (new Version (2, 0, 0, 0), reference.Version); Assert.AreEqual (new byte [] { 0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89 }, reference.PublicKeyToken); }); } [Test] public void ModuleReferences () { TestModule ("pinvoke.exe", module => { Assert.AreEqual (2, module.ModuleReferences.Count); Assert.AreEqual ("kernel32.dll", module.ModuleReferences [0].Name); Assert.AreEqual ("shell32.dll", module.ModuleReferences [1].Name); }); } [Test] public void Types () { TestModule ("hello.exe", module => { Assert.AreEqual (2, module.Types.Count); Assert.AreEqual ("<Module>", module.Types [0].FullName); Assert.AreEqual ("<Module>", module.GetType ("<Module>").FullName); Assert.AreEqual ("Program", module.Types [1].FullName); Assert.AreEqual ("Program", module.GetType ("Program").FullName); }); } [Test] public void LinkedResource () { TestModule ("libres.dll", module => { var resource = module.Resources.Where (res => res.Name == "linked.txt").First () as LinkedResource; Assert.IsNotNull (resource); Assert.AreEqual ("linked.txt", resource.Name); Assert.AreEqual ("linked.txt", resource.File); Assert.AreEqual (ResourceType.Linked, resource.ResourceType); Assert.IsTrue (resource.IsPublic); }); } [Test] public void EmbeddedResource () { TestModule ("libres.dll", module => { var resource = module.Resources.Where (res => res.Name == "embedded1.txt").First () as EmbeddedResource; Assert.IsNotNull (resource); Assert.AreEqual ("embedded1.txt", resource.Name); Assert.AreEqual (ResourceType.Embedded, resource.ResourceType); Assert.IsTrue (resource.IsPublic); using (var reader = new StreamReader (resource.GetResourceStream ())) Assert.AreEqual ("Hello", reader.ReadToEnd ()); resource = module.Resources.Where (res => res.Name == "embedded2.txt").First () as EmbeddedResource; Assert.IsNotNull (resource); Assert.AreEqual ("embedded2.txt", resource.Name); Assert.AreEqual (ResourceType.Embedded, resource.ResourceType); Assert.IsTrue (resource.IsPublic); using (var reader = new StreamReader (resource.GetResourceStream ())) Assert.AreEqual ("World", reader.ReadToEnd ()); }); } [Test] public void ExportedTypeFromNetModule () { IgnoreOnCoreClr (); TestModule ("mma.exe", module => { Assert.IsTrue (module.HasExportedTypes); Assert.AreEqual (2, module.ExportedTypes.Count); var exported_type = module.ExportedTypes [0]; Assert.AreEqual ("Module.A.Foo", exported_type.FullName); Assert.AreEqual ("moda.netmodule", exported_type.Scope.Name); exported_type = module.ExportedTypes [1]; Assert.AreEqual ("Module.B.Baz", exported_type.FullName); Assert.AreEqual ("modb.netmodule", exported_type.Scope.Name); }); } [Test] public void NestedTypeForwarder () { TestCSharp ("CustomAttributes.cs", module => { Assert.IsTrue (module.HasExportedTypes); Assert.AreEqual (2, module.ExportedTypes.Count); var exported_type = module.ExportedTypes [0]; Assert.AreEqual ("System.Diagnostics.DebuggableAttribute", exported_type.FullName); Assert.AreEqual (Platform.OnCoreClr ? "System.Private.CoreLib" : "mscorlib", exported_type.Scope.Name); Assert.IsTrue (exported_type.IsForwarder); var nested_exported_type = module.ExportedTypes [1]; Assert.AreEqual ("System.Diagnostics.DebuggableAttribute/DebuggingModes", nested_exported_type.FullName); Assert.AreEqual (exported_type, nested_exported_type.DeclaringType); Assert.AreEqual (Platform.OnCoreClr ? "System.Private.CoreLib" : "mscorlib", nested_exported_type.Scope.Name); }); } [Test] public void HasTypeReference () { TestCSharp ("CustomAttributes.cs", module => { Assert.IsTrue (module.HasTypeReference ("System.Attribute")); Assert.IsTrue (module.HasTypeReference (Platform.OnCoreClr ? "System.Private.CoreLib" : "mscorlib", "System.Attribute")); Assert.IsFalse (module.HasTypeReference ("System.Core", "System.Attribute")); Assert.IsFalse (module.HasTypeReference ("System.Linq.Enumerable")); }); } [Test] public void Win32FileVersion () { IgnoreOnCoreClr (); TestModule ("libhello.dll", module => { var version = FileVersionInfo.GetVersionInfo (module.FileName); Assert.AreEqual ("0.0.0.0", version.FileVersion); }); } [Test] public void ModuleWithoutBlob () { TestModule ("noblob.dll", module => { Assert.IsNull (module.Image.BlobHeap); }); } [Test] public void MixedModeModule () { using (var module = GetResourceModule ("cppcli.dll")) { Assert.AreEqual (1, module.ModuleReferences.Count); Assert.AreEqual (string.Empty, module.ModuleReferences [0].Name); } } [Test] public void OpenIrrelevantFile () { Assert.Throws<BadImageFormatException> (() => GetResourceModule ("text_file.txt")); } [Test] public void GetTypeNamespacePlusName () { using (var module = GetResourceModule ("moda.netmodule")) { var type = module.GetType ("Module.A", "Foo"); Assert.IsNotNull (type); } } [Test] public void GetNonExistentTypeRuntimeName () { using (var module = GetResourceModule ("libhello.dll")) { var type = module.GetType ("DoesNotExist", runtimeName: true); Assert.IsNull (type); } } [Test] public void OpenModuleImmediate () { using (var module = GetResourceModule ("hello.exe", ReadingMode.Immediate)) { Assert.AreEqual (ReadingMode.Immediate, module.ReadingMode); } } [Test] public void OpenModuleDeferred () { using (var module = GetResourceModule ("hello.exe", ReadingMode.Deferred)) { Assert.AreEqual (ReadingMode.Deferred, module.ReadingMode); } } [Test] public void OpenModuleDeferredAndThenPerformImmediateRead () { using (var module = GetResourceModule ("hello.exe", ReadingMode.Deferred)) { Assert.AreEqual (ReadingMode.Deferred, module.ReadingMode); module.ImmediateRead (); Assert.AreEqual (ReadingMode.Immediate, module.ReadingMode); } } [Test] public void ImmediateReadDoesNothingForModuleWithNoImage () { using (var module = new ModuleDefinition ()) { var initialReadingMode = module.ReadingMode; module.ImmediateRead (); Assert.AreEqual (initialReadingMode, module.ReadingMode); } } [Test] public void OwnedStreamModuleFileName () { var path = GetAssemblyResourcePath ("hello.exe"); using (var file = File.Open (path, FileMode.Open)) { using (var module = ModuleDefinition.ReadModule (file)) { Assert.IsNotNull (module.FileName); Assert.IsNotEmpty (module.FileName); Assert.AreEqual (path, module.FileName); } } } [Test] public void ReadAndWriteFile () { var path = Path.GetTempFileName (); var original = ModuleDefinition.CreateModule ("FooFoo", ModuleKind.Dll); var type = new TypeDefinition ("Foo", "Foo", TypeAttributes.Abstract | TypeAttributes.Sealed); original.Types.Add (type); original.Write (path); using (var module = ModuleDefinition.ReadModule (path, new ReaderParameters { ReadWrite = true })) { module.Write (); } using (var module = ModuleDefinition.ReadModule (path)) Assert.AreEqual ("Foo.Foo", module.Types [1].FullName); } [Test] public void ExceptionInWriteDoesNotKeepLockOnFile () { var path = Path.GetTempFileName (); var module = ModuleDefinition.CreateModule ("FooFoo", ModuleKind.Dll); // Mixed mode module that Cecil can not write module.Attributes = (ModuleAttributes) 0; Assert.Throws<NotSupportedException>(() => module.Write (path)); // Ensure you can still delete the file File.Delete (path); } } }
// // Authors: // Atsushi Enomoto // // Copyright 2007 Novell (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using XPI = System.Xml.Linq.XProcessingInstruction; namespace System.Xml.Linq { public abstract class XNode : XObject { public static int CompareDocumentOrder (XNode n1, XNode n2) { return order_comparer.Compare (n1, n2); } public static bool DeepEquals (XNode n1, XNode n2) { return eq_comparer.Equals (n1, n2); } static XNodeEqualityComparer eq_comparer = new XNodeEqualityComparer (); static XNodeDocumentOrderComparer order_comparer = new XNodeDocumentOrderComparer (); XNode previous; XNode next; internal XNode () { } public static XNodeDocumentOrderComparer DocumentOrderComparer { get { return order_comparer; } } public static XNodeEqualityComparer EqualityComparer { get { return eq_comparer; } } public XNode PreviousNode { get { return previous; } internal set { previous = value; } } public XNode NextNode { get { return next; } internal set { next = value; } } public string ToString (SaveOptions options) { StringWriter sw = new StringWriter (); XmlWriterSettings s = new XmlWriterSettings (); s.ConformanceLevel = ConformanceLevel.Auto; s.Indent = options != SaveOptions.DisableFormatting; XmlWriter xw = XmlWriter.Create (sw, s); WriteTo (xw); xw.Close (); return sw.ToString (); } public void AddAfterSelf (object content) { if (Owner == null) throw new InvalidOperationException (); XNode here = this; XNode orgNext = next; foreach (object o in XUtil.ExpandArray (content)) { if (o == null || Owner.OnAddingObject (o, true, here, false)) continue; XNode n = XUtil.ToNode (o); n = (XNode) XUtil.GetDetachedObject (n); n.SetOwner (Owner); n.previous = here; here.next = n; n.next = orgNext; if (orgNext != null) orgNext.previous = n; else Owner.LastNode = n; here = n; } } public void AddAfterSelf (params object [] content) { if (Owner == null) throw new InvalidOperationException (); AddAfterSelf ((object) content); } public void AddBeforeSelf (object content) { if (Owner == null) throw new InvalidOperationException (); foreach (object o in XUtil.ExpandArray (content)) { if (o == null || Owner.OnAddingObject (o, true, previous, true)) continue; XNode n = XUtil.ToNode (o); n = (XNode) XUtil.GetDetachedObject (n); n.SetOwner (Owner); n.previous = previous; n.next = this; if (previous != null) previous.next = n; previous = n; if (Owner.FirstNode == this) Owner.FirstNode = n; } } public void AddBeforeSelf (params object [] content) { if (Owner == null) throw new InvalidOperationException (); AddBeforeSelf ((object) content); } public static XNode ReadFrom (XmlReader r) { return ReadFrom (r, LoadOptions.None); } internal static XNode ReadFrom (XmlReader r, LoadOptions options) { switch (r.NodeType) { case XmlNodeType.Element: return XElement.LoadCore (r, options); case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Text: XText t = new XText (r.Value); t.FillLineInfoAndBaseUri (r, options); r.Read (); return t; case XmlNodeType.CDATA: XCData c = new XCData (r.Value); c.FillLineInfoAndBaseUri (r, options); r.Read (); return c; case XmlNodeType.ProcessingInstruction: XPI pi = new XPI (r.Name, r.Value); pi.FillLineInfoAndBaseUri (r, options); r.Read (); return pi; case XmlNodeType.Comment: XComment cm = new XComment (r.Value); cm.FillLineInfoAndBaseUri (r, options); r.Read (); return cm; case XmlNodeType.DocumentType: XDocumentType d = new XDocumentType (r.Name, r.GetAttribute ("PUBLIC"), r.GetAttribute ("SYSTEM"), r.Value); d.FillLineInfoAndBaseUri (r, options); r.Read (); return d; default: throw new InvalidOperationException (String.Format ("Node type {0} is not supported", r.NodeType)); } } public void Remove () { if (Owner == null) throw new InvalidOperationException ("Owner is missing"); if (Owner.FirstNode == this) Owner.FirstNode = next; if (Owner.LastNode == this) Owner.LastNode = previous; if (previous != null) previous.next = next; if (next != null) next.previous = previous; previous = null; next = null; SetOwner (null); } public override string ToString () { return ToString (SaveOptions.None); } public abstract void WriteTo (XmlWriter w); public IEnumerable<XElement> Ancestors () { for (XElement el = Parent; el != null; el = el.Parent) yield return el; } public IEnumerable<XElement> Ancestors (XName name) { foreach (XElement el in Ancestors ()) if (el.Name == name) yield return el; } public XmlReader CreateReader () { return new XNodeReader (this); } public IEnumerable<XElement> ElementsAfterSelf () { foreach (XNode n in NodesAfterSelf ()) if (n is XElement) yield return (XElement) n; } public IEnumerable<XElement> ElementsAfterSelf (XName name) { foreach (XElement el in ElementsAfterSelf ()) if (el.Name == name) yield return el; } public IEnumerable<XElement> ElementsBeforeSelf () { foreach (XNode n in NodesBeforeSelf ()) if (n is XElement) yield return (XElement) n; } public IEnumerable<XElement> ElementsBeforeSelf (XName name) { foreach (XElement el in ElementsBeforeSelf ()) if (el.Name == name) yield return el; } public bool IsAfter (XNode other) { return XNode.DocumentOrderComparer.Compare (this, other) > 0; } public bool IsBefore (XNode other) { return XNode.DocumentOrderComparer.Compare (this, other) < 0; } public IEnumerable<XNode> NodesAfterSelf () { if (Owner == null) yield break; for (XNode n = NextNode; n != null; n = n.NextNode) yield return n; } public IEnumerable<XNode> NodesBeforeSelf () { if (Owner == null) yield break; for (XNode n = Owner.FirstNode; n != this; n = n.NextNode) yield return n; } public void ReplaceWith (object content) { if (Owner == null) throw new InvalidOperationException (); XNode here = previous; XNode orgNext = next; XContainer orgOwner = Owner; Remove(); foreach (object o in XUtil.ExpandArray (content)) { if (o == null || orgOwner.OnAddingObject (o, true, here, false)) continue; XNode n = XUtil.ToNode (o); n = (XNode) XUtil.GetDetachedObject (n); n.SetOwner (orgOwner); n.previous = here; if (here != null) here.next = n; else orgOwner.FirstNode = n; n.next = orgNext; if (orgNext != null) orgNext.previous = n; else orgOwner.LastNode = n; here = n; } } public void ReplaceWith (params object [] content) { if (Owner == null) throw new InvalidOperationException (); ReplaceWith ((object) content); } } }
using System; using System.Data; using Codentia.Common.Data; using Codentia.Test.Helper; using NUnit.Framework; namespace Codentia.Common.Reporting.DL.Test { /// <summary> /// Unit testing framework for ReportingData /// </summary> [TestFixture] public class ReportingDataTest { /// <summary> /// Scenario: Check the No of Enums in the database equals the number of project enums /// Expected: Process completes without error /// </summary> [Test] public void _001_ReportParameterType_EnumCheck() { DataTable dt = DbInterface.ExecuteQueryDataTable("SELECT * FROM ReportParameterType"); // Check count string[] enums = Enum.GetNames(typeof(ReportParameterType)); Assert.That(enums.Length, Is.EqualTo(dt.Rows.Count), "Total count of enums does not match database"); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; string code = Convert.ToString(dr["ReportParameterTypeCode"]); int id = Convert.ToInt32(dr["ReportParameterTypeId"]); Assert.That(code, Is.EqualTo(Enum.Format(typeof(ReportParameterType), id, "F")), string.Format("id for {0} incorrect", code)); } } /// <summary> /// Scenario: Get All Reports that should appear in a report list /// Expected: Process completes without error /// </summary> [Test] public void _002_GetReports() { int rowCount = DbInterface.ExecuteQueryScalar<int>("SELECT COUNT(ReportId) FROM dbo.Report WHERE OnReportPageList=1"); DataTable dt = ReportingData.GetReports(); Assert.That(dt.Rows.Count, Is.EqualTo(rowCount), "Row count does not match"); } /// <summary> /// Scenario: Run GetParametersForDataSource with an invalid id /// Expected: reportId is not valid Exception raised /// </summary> [Test] public void _003_GetParametersForDataSource_InvalidReportId() { // 0 Assert.That(delegate { ReportingData.GetParametersForDataSource(0); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("reportDataSourceId: 0 is not valid")); // -1 Assert.That(delegate { ReportingData.GetParametersForDataSource(-1); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("reportDataSourceId: -1 is not valid")); // mon-existant int reportDataSourceIdNonExistant = SqlHelper.GetUnusedIdFromTable("reporting_sql", "ReportDataSource"); Assert.That(delegate { ReportingData.GetParametersForDataSource(reportDataSourceIdNonExistant); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo(string.Format("reportDataSourceId: {0} does not exist", reportDataSourceIdNonExistant))); } /// <summary> /// Scenario: Get All Parameters for a ReportDataSource /// Expected: Process completes without error /// </summary> [Test] public void _005_GetParametersForDataSource_ValidReportDataSourceId() { int reportDataSourceId = DbInterface.ExecuteQueryScalar<int>("SELECT TOP 1 ReportDataSourceId FROM dbo.ReportDataSource ORDER BY NEWID()"); int rowCount = DbInterface.ExecuteQueryScalar<int>(string.Format("SELECT COUNT(*) FROM dbo.ReportDataSource_ReportParameter WHERE ReportDataSourceId={0}", reportDataSourceId)); DataTable dt = ReportingData.GetParametersForDataSource(reportDataSourceId); Assert.That(dt.Rows.Count, Is.EqualTo(rowCount), string.Format("Expected row count does not match (reportDataSourceId: {0})", reportDataSourceId)); } /// <summary> /// Scenario: RunReportProc with a null or empty string for procedureName /// Expected: ProcedureName not specified exception raised /// </summary> [Test] public void _006_RunReportProc_NullOrEmptyProcedureName() { // null Assert.That(delegate { ReportingData.RunReportProc(null, null); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("procedureName is not specified")); // empty Assert.That(delegate { ReportingData.RunReportProc(string.Empty, null); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("procedureName is not specified")); } /// <summary> /// Scenario: RunReportProc with null parameters object /// Expected: Process runs succesfully /// </summary> [Test] public void _007_RunReportProc_NullParameters() { DataTable dt = ReportingData.RunReportProc("TestReportSP", null); Assert.That(dt.Rows.Count, Is.GreaterThan(0), "Expected row count greater than 0"); } /// <summary> /// Scenario: RunReportProc with parameters /// Expected: Process runs succesfully /// </summary> [Test] public void _008_RunReportProc_WithParameters() { DbParameter[] parameters = { new DbParameter("@Param1", DbType.Int32), new DbParameter("@Param2", DbType.DateTime), new DbParameter("@Param3", DbType.Xml), new DbParameter("@Param4", DbType.Int32), new DbParameter("@Param5", DbType.Boolean) }; parameters[0].Value = 0; parameters[1].Value = DateTime.Now; parameters[2].Value = "<mytest>blahblah</mytest>"; parameters[3].Value = 10000; parameters[4].Value = true; DataTable dt = ReportingData.RunReportProc("TestReportSPWithParameters", parameters); Assert.That(dt.Rows.Count, Is.GreaterThan(0), "Expected row count greater than 0"); } /// <summary> /// Scenario: ReportExists (Id) Negative Tests /// Expected: Exceptions raised /// </summary> [Test] public void _009_ReportExists_Id_NegativeTests() { NUnitHelper.DoNegativeTests("reporting_sql", "Codentia.Common.Reporting.dll", "Codentia.Common.Reporting.DL.ReportingData", "ReportExists", "System.Int32", string.Empty, string.Empty); } /// <summary> /// Scenario: ReportExists (String) Negative Tests /// Expected: Exceptions raised /// </summary> [Test] public void _010_ReportExists_String_NegativeTests() { NUnitHelper.DoNegativeTests("reporting_sql", "Codentia.Common.Reporting.dll", "Codentia.Common.Reporting.DL.ReportingData", "ReportExists", "System.String", string.Empty, string.Empty); } /// <summary> /// Scenario: Call ReportExists with an invalid Id /// Expected: ReportExists returns false /// </summary> [Test] public void _011_ReportExists_InvalidId() { int reportId = SqlHelper.GetUnusedIdFromTable("reporting_sql", "Report"); Assert.That(ReportingData.ReportExists(reportId), Is.False, "false expected"); } /// <summary> /// Scenario: Call ReportExists with a valid Id /// Expected: ReportExists returns true /// </summary> [Test] public void _012_ReportExists_ValidId() { int reportId = DbInterface.ExecuteQueryScalar<int>("SELECT TOP 1 ReportId FROM dbo.Report ORDER BY NEWID()"); Assert.That(ReportingData.ReportExists(reportId), Is.True, "true expected"); } /// <summary> /// Scenario: Call ReportExists with a valid code /// Expected: ReportExists returns true /// </summary> [Test] public void _013_ReportExists_ValidCode() { string reportCode = DbInterface.ExecuteQueryScalar<string>("SELECT TOP 1 ReportCode FROM dbo.Report ORDER BY NEWID()"); Assert.That(ReportingData.ReportExists(reportCode), Is.True, "true expected"); } /// <summary> /// Scenario: GetDataForReport (String) Negative Tests /// Expected: Exceptions raised /// </summary> [Test] public void _014_GetDataForReport_NegativeTests() { NUnitHelper.DoNegativeTests("reporting_sql", "Codentia.Common.Reporting.dll", "Codentia.Common.Reporting.DL.ReportingData", "GetDataForReport", "System.String", "reportId=[Report]", string.Empty); } /// <summary> /// Scenario: Call GetDataForReport with a valid code /// Expected: Process runs succesfully /// </summary> [Test] public void _015_GetDataForReport_ValidCode() { DataTable dt = DbInterface.ExecuteQueryDataTable("SELECT TOP 1 ReportCode, ReportId, ReportName, rdlName, isRdlc, TagReplacementXml, TagReplacementSP FROM dbo.Report ORDER BY NEWID()"); string reportCode = Convert.ToString(dt.Rows[0]["ReportCode"]); int reportId = Convert.ToInt32(dt.Rows[0]["ReportId"]); string reportName = Convert.ToString(dt.Rows[0]["ReportName"]); string rdlName = Convert.ToString(dt.Rows[0]["RdlName"]); bool isRdlc = Convert.ToBoolean(dt.Rows[0]["isRdlc"]); string tagReplacementXml = Convert.ToString(dt.Rows[0]["TagReplacementXml"]); string tagReplacementSP = Convert.ToString(dt.Rows[0]["TagReplacementSP"]); DataTable dtResult = ReportingData.GetDataForReport(reportCode); int testReportId = Convert.ToInt32(dtResult.Rows[0]["ReportId"]); string testReportName = Convert.ToString(dtResult.Rows[0]["ReportName"]); string testRdlName = Convert.ToString(dtResult.Rows[0]["RdlName"]); bool testIsRdlc = Convert.ToBoolean(dtResult.Rows[0]["isRdlc"]); string testTagReplacementXml = Convert.ToString(dtResult.Rows[0]["TagReplacementXml"]); string testTagReplacementSP = Convert.ToString(dtResult.Rows[0]["TagReplacementSP"]); Assert.That(reportId, Is.EqualTo(testReportId), "testReportId does not match"); Assert.That(reportName, Is.EqualTo(testReportName), "testReportName does not match"); Assert.That(rdlName, Is.EqualTo(testRdlName), "testRdlName does not match"); Assert.That(isRdlc, Is.EqualTo(testIsRdlc), "testIsRdlc does not match"); Assert.That(tagReplacementXml, Is.EqualTo(testTagReplacementXml), "testTagReplacementXml does not match"); Assert.That(tagReplacementSP, Is.EqualTo(testTagReplacementSP), "testTagReplacementSP does not match"); } /// <summary> /// Scenario: Run GetDataSourcesForReport with an invalid id /// Expected: reportId is not valid Exception raised /// </summary> [Test] public void _017_GetDataSourcesForReport_InvalidReportId() { NUnitHelper.DoNegativeTests("reporting_sql", "Codentia.Common.Reporting.dll", "Codentia.Common.Reporting.DL.ReportingData", "GetDataSourcesForReport", "reportId=[Report]", string.Empty); } /// <summary> /// Scenario: Get All DataSources for a Report /// Expected: Process completes without error /// </summary> [Test] public void _018_GetDataSourcesForReport_ValidReportDataSourceId() { int reportId = DbInterface.ExecuteQueryScalar<int>("SELECT TOP 1 ReportId FROM dbo.Report ORDER BY NEWID()"); int rowCount = DbInterface.ExecuteQueryScalar<int>(string.Format("SELECT COUNT(*) FROM dbo.ReportDataSource WHERE ReportId={0}", reportId)); DataTable dt = ReportingData.GetDataSourcesForReport(reportId); Assert.That(dt.Rows.Count, Is.EqualTo(rowCount), string.Format("Expected row count does not match (reportId: {0})", reportId)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Threading; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.IoT.TimeSeriesInsights { /// <summary> /// A client that can be used to query for events, series and aggregate series on Time Series Insights. /// </summary> public class TimeSeriesInsightsQueries { private readonly QueryRestClient _queryRestClient; private readonly ClientDiagnostics _clientDiagnostics; /// <summary> /// Initializes a new instance of TimeSeriesInsightsQueries. This constructor should only be used for mocking purposes. /// </summary> protected TimeSeriesInsightsQueries() { } internal TimeSeriesInsightsQueries(QueryRestClient queryRestClient, ClientDiagnostics clientDiagnostics) { Argument.AssertNotNull(queryRestClient, nameof(queryRestClient)); Argument.AssertNotNull(clientDiagnostics, nameof(clientDiagnostics)); _queryRestClient = queryRestClient; _clientDiagnostics = clientDiagnostics; } /// <summary> /// Retrieve raw events for a given Time Series Id asynchronously. /// </summary> /// <param name="timeSeriesId">The Time Series Id to retrieve raw events for.</param> /// <param name="startTime">Start timestamp of the time range. Events that have this timestamp are included.</param> /// <param name="endTime">End timestamp of the time range. Events that match this timestamp are excluded.</param> /// <param name="options">Optional parameters to use when querying for events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The <see cref="TimeSeriesQueryAnalyzer"/> object that can be used to retrieve the pageable list <see cref="AsyncPageable{TimeSeriesPoint}"/>.</returns> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleQueryEvents" language="csharp"> /// Console.WriteLine(&quot;\n\nQuery for raw temperature events over the past 10 minutes.\n&quot;); /// /// // Get events from last 10 minute /// DateTimeOffset endTime = DateTime.UtcNow; /// DateTimeOffset startTime = endTime.AddMinutes(-10); /// /// TimeSeriesQueryAnalyzer temperatureEventsQuery = queriesClient.CreateEventsQuery(tsId, startTime, endTime); /// await foreach (TimeSeriesPoint point in temperatureEventsQuery.GetResultsAsync()) /// { /// TimeSeriesValue temperatureValue = point.GetValue(&quot;Temperature&quot;); /// /// // Figure out what is the underlying type for the time series value. Since you know your Time Series Insights /// // environment best, you probably do not need this logic and you can skip to directly casting to the proper /// // type. This logic demonstrates how you can figure out what type to cast to in the case where you are not /// // too familiar with the property type. /// if (temperatureValue.Type == typeof(double?)) /// { /// Console.WriteLine($&quot;{point.Timestamp} - Temperature: {point.GetNullableDouble(&quot;Temperature&quot;)}&quot;); /// } /// else if (temperatureValue.Type == typeof(int?)) /// { /// Console.WriteLine($&quot;{point.Timestamp} - Temperature: {point.GetNullableInt(&quot;Temperature&quot;)}&quot;); /// } /// else /// { /// Console.WriteLine(&quot;The type of the Time Series value for Temperature is not numeric.&quot;); /// } /// } /// </code> /// </example> public virtual TimeSeriesQueryAnalyzer CreateEventsQuery( TimeSeriesId timeSeriesId, DateTimeOffset startTime, DateTimeOffset endTime, QueryEventsRequestOptions options = null, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetEvents)}"); scope.Start(); try { var searchSpan = new DateTimeRange(startTime, endTime); var queryRequest = new QueryRequest { GetEvents = new GetEvents(timeSeriesId, searchSpan) }; BuildEventsRequestOptions(options, queryRequest); return new TimeSeriesQueryAnalyzer(_queryRestClient, queryRequest, options?.Store?.ToString(), cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Retrieve raw events for a given Time Series Id over a specified time interval asynchronously. /// </summary> /// <param name="timeSeriesId">The Time Series Id to retrieve raw events for.</param> /// <param name="timeSpan">The time interval over which to query data.</param> /// <param name="endTime">End timestamp of the time range. Events that match this timestamp are excluded. If null is provided, <c>DateTimeOffset.UtcNow</c> is used.</param> /// <param name="options">Optional parameters to use when querying for events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The <see cref="TimeSeriesQueryAnalyzer"/> object that can be used to retrieve the pageable list <see cref="AsyncPageable{TimeSeriesPoint}"/>.</returns> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleQueryEventsUsingTimeSpan" language="csharp"> /// Console.WriteLine(&quot;\n\nQuery for raw humidity events over the past 30 seconds.\n&quot;); /// /// TimeSeriesQueryAnalyzer humidityEventsQuery = queriesClient.CreateEventsQuery(tsId, TimeSpan.FromSeconds(30)); /// await foreach (TimeSeriesPoint point in humidityEventsQuery.GetResultsAsync()) /// { /// TimeSeriesValue humidityValue = point.GetValue(&quot;Humidity&quot;); /// /// // Figure out what is the underlying type for the time series value. Since you know your Time Series Insights /// // environment best, you probably do not need this logic and you can skip to directly casting to the proper /// // type. This logic demonstrates how you can figure out what type to cast to in the case where you are not /// // too familiar with the property type. /// if (humidityValue.Type == typeof(double?)) /// { /// Console.WriteLine($&quot;{point.Timestamp} - Humidity: {point.GetNullableDouble(&quot;Humidity&quot;)}&quot;); /// } /// else if (humidityValue.Type == typeof(int?)) /// { /// Console.WriteLine($&quot;{point.Timestamp} - Humidity: {point.GetNullableInt(&quot;Humidity&quot;)}&quot;); /// } /// else /// { /// Console.WriteLine(&quot;The type of the Time Series value for Humidity is not numeric.&quot;); /// } /// } /// </code> /// </example> public virtual TimeSeriesQueryAnalyzer CreateEventsQuery( TimeSeriesId timeSeriesId, TimeSpan timeSpan, DateTimeOffset? endTime = null, QueryEventsRequestOptions options = null, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetEvents)}"); scope.Start(); try { DateTimeOffset rangeEndTime = endTime ?? DateTimeOffset.UtcNow; DateTimeOffset rangeStartTime = rangeEndTime - timeSpan; var searchSpan = new DateTimeRange(rangeStartTime, rangeEndTime); var queryRequest = new QueryRequest { GetEvents = new GetEvents(timeSeriesId, searchSpan) }; BuildEventsRequestOptions(options, queryRequest); return new TimeSeriesQueryAnalyzer(_queryRestClient, queryRequest, options?.Store?.ToString(), cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Retrieve series events for a given Time Series Id asynchronously. /// </summary> /// <param name="timeSeriesId">The Time Series Id to retrieve series events for.</param> /// <param name="startTime">Start timestamp of the time range. Events that have this timestamp are included.</param> /// <param name="endTime">End timestamp of the time range. Events that match this timestamp are excluded.</param> /// <param name="options">Optional parameters to use when querying for series events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The <see cref="TimeSeriesQueryAnalyzer"/> object that can be used to retrieve the pageable list <see cref="AsyncPageable{TimeSeriesPoint}"/>.</returns> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleQuerySeries" language="csharp"> /// Console.WriteLine($&quot;\n\nQuery for temperature series in Celsius and Fahrenheit over the past 10 minutes. &quot; + /// $&quot;The Time Series instance belongs to a type that has predefined numeric variable that represents the temperature &quot; + /// $&quot;in Celsuis, and a predefined numeric variable that represents the temperature in Fahrenheit.\n&quot;); /// /// DateTimeOffset endTime = DateTime.UtcNow; /// DateTimeOffset startTime = endTime.AddMinutes(-10); /// TimeSeriesQueryAnalyzer seriesQuery = queriesClient.CreateSeriesQuery( /// tsId, /// startTime, /// endTime); /// /// await foreach (TimeSeriesPoint point in seriesQuery.GetResultsAsync()) /// { /// double? tempInCelsius = point.GetNullableDouble(celsiusVariableName); /// double? tempInFahrenheit = point.GetNullableDouble(fahrenheitVariableName); /// /// Console.WriteLine($&quot;{point.Timestamp} - Average temperature in Celsius: {tempInCelsius}. &quot; + /// $&quot;Average temperature in Fahrenheit: {tempInFahrenheit}.&quot;); /// } /// </code> /// </example> public virtual TimeSeriesQueryAnalyzer CreateSeriesQuery( TimeSeriesId timeSeriesId, DateTimeOffset startTime, DateTimeOffset endTime, QuerySeriesRequestOptions options = null, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetSeries)}"); scope.Start(); try { var searchSpan = new DateTimeRange(startTime, endTime); var queryRequest = new QueryRequest { GetSeries = new GetSeries(timeSeriesId, searchSpan) }; BuildSeriesRequestOptions(options, queryRequest); return new TimeSeriesQueryAnalyzer(_queryRestClient, queryRequest, options?.Store?.ToString(), cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Retrieve series events for a given Time Series Id over a specified time interval asynchronously. /// </summary> /// <param name="timeSeriesId">The Time Series Id to retrieve series events for.</param> /// <param name="timeSpan">The time interval over which to query data.</param> /// <param name="endTime">End timestamp of the time range. Events that match this timestamp are excluded. If null is provided, <c>DateTimeOffset.UtcNow</c> is used.</param> /// <param name="options">Optional parameters to use when querying for series events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The <see cref="TimeSeriesQueryAnalyzer"/> object that can be used to retrieve the pageable list <see cref="AsyncPageable{TimeSeriesPoint}"/>.</returns> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleQuerySeriesWithInlineVariables" language="csharp"> /// Console.WriteLine(&quot;\n\nQuery for temperature series in Celsius and Fahrenheit over the past 10 minutes.\n&quot;); /// /// var celsiusVariable = new NumericVariable( /// new TimeSeriesExpression(&quot;$event.Temperature&quot;), /// new TimeSeriesExpression(&quot;avg($value)&quot;)); /// var fahrenheitVariable = new NumericVariable( /// new TimeSeriesExpression(&quot;$event.Temperature * 1.8 + 32&quot;), /// new TimeSeriesExpression(&quot;avg($value)&quot;)); /// /// var querySeriesRequestOptions = new QuerySeriesRequestOptions(); /// querySeriesRequestOptions.InlineVariables[&quot;TemperatureInCelsius&quot;] = celsiusVariable; /// querySeriesRequestOptions.InlineVariables[&quot;TemperatureInFahrenheit&quot;] = fahrenheitVariable; /// /// TimeSeriesQueryAnalyzer seriesQuery = queriesClient.CreateSeriesQuery( /// tsId, /// TimeSpan.FromMinutes(10), /// null, /// querySeriesRequestOptions); /// /// await foreach (TimeSeriesPoint point in seriesQuery.GetResultsAsync()) /// { /// double? tempInCelsius = (double?)point.GetValue(&quot;TemperatureInCelsius&quot;); /// double? tempInFahrenheit = (double?)point.GetValue(&quot;TemperatureInFahrenheit&quot;); /// /// Console.WriteLine($&quot;{point.Timestamp} - Average temperature in Celsius: {tempInCelsius}. Average temperature in Fahrenheit: {tempInFahrenheit}.&quot;); /// } /// </code> /// </example> public virtual TimeSeriesQueryAnalyzer CreateSeriesQuery( TimeSeriesId timeSeriesId, TimeSpan timeSpan, DateTimeOffset? endTime = null, QuerySeriesRequestOptions options = null, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetSeries)}"); scope.Start(); try { DateTimeOffset rangeEndTime = endTime ?? DateTimeOffset.UtcNow; DateTimeOffset rangeStartTime = rangeEndTime - timeSpan; var searchSpan = new DateTimeRange(rangeStartTime, rangeEndTime); var queryRequest = new QueryRequest { GetSeries = new GetSeries(timeSeriesId, searchSpan) }; BuildSeriesRequestOptions(options, queryRequest); return new TimeSeriesQueryAnalyzer(_queryRestClient, queryRequest, options?.Store?.ToString(), cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Retrieve aggregated time series from events for a given Time Series Id asynchronously. /// </summary> /// <param name="timeSeriesId">The Time Series Id to retrieve series events for.</param> /// <param name="startTime">Start timestamp of the time range. Events that have this timestamp are included.</param> /// <param name="endTime">End timestamp of the time range. Events that match this timestamp are excluded.</param> /// <param name="interval">Interval size used to group events by.</param> /// <param name="options">Optional parameters to use when querying for aggregated series events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The <see cref="TimeSeriesQueryAnalyzer"/> object that can be used to retrieve the pageable list <see cref="AsyncPageable{TimeSeriesPoint}"/>.</returns> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleQueryAggregateSeriesWithAggregateVariable" language="csharp"> /// Console.WriteLine(&quot;\n\nCount the number of temperature events over the past 3 minutes, in 1-minute time slots.\n&quot;); /// /// // Get the count of events in 60-second time slots over the past 3 minutes /// DateTimeOffset endTime = DateTime.UtcNow; /// DateTimeOffset startTime = endTime.AddMinutes(-3); /// /// var aggregateVariable = new AggregateVariable( /// new TimeSeriesExpression(&quot;count()&quot;)); /// /// var countVariableName = &quot;Count&quot;; /// /// var aggregateSeriesRequestOptions = new QueryAggregateSeriesRequestOptions(); /// aggregateSeriesRequestOptions.InlineVariables[countVariableName] = aggregateVariable; /// aggregateSeriesRequestOptions.ProjectedVariableNames.Add(countVariableName); /// /// TimeSeriesQueryAnalyzer query = queriesClient.CreateAggregateSeriesQuery( /// tsId, /// startTime, /// endTime, /// TimeSpan.FromSeconds(60), /// aggregateSeriesRequestOptions); /// /// await foreach (TimeSeriesPoint point in query.GetResultsAsync()) /// { /// long? temperatureCount = (long?)point.GetValue(countVariableName); /// Console.WriteLine($&quot;{point.Timestamp} - Temperature count: {temperatureCount}&quot;); /// } /// </code> /// </example> public virtual TimeSeriesQueryAnalyzer CreateAggregateSeriesQuery( TimeSeriesId timeSeriesId, DateTimeOffset startTime, DateTimeOffset endTime, TimeSpan interval, QueryAggregateSeriesRequestOptions options = null, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(CreateAggregateSeriesQuery)}"); scope.Start(); try { var searchSpan = new DateTimeRange(startTime, endTime); var queryRequest = new QueryRequest { AggregateSeries = new AggregateSeries(timeSeriesId, searchSpan, interval) }; BuildAggregateSeriesRequestOptions(options, queryRequest); return new TimeSeriesQueryAnalyzer(_queryRestClient, queryRequest, options?.Store?.ToString(), cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Retrieve aggregated time series from events for a given Time Series Id over a specified time interval asynchronously. /// </summary> /// <param name="timeSeriesId">The Time Series Id to retrieve series events for.</param> /// <param name="interval">Interval size used to group events by.</param> /// <param name="timeSpan">The time interval over which to query data.</param> /// <param name="endTime">End timestamp of the time range. Events that match this timestamp are excluded. If null is provided, <c>DateTimeOffset.UtcNow</c> is used.</param> /// <param name="options">Optional parameters to use when querying for aggregated series events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The <see cref="TimeSeriesQueryAnalyzer"/> object that can be used to retrieve the pageable list <see cref="AsyncPageable{TimeSeriesPoint}"/>.</returns> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleQueryAggregateSeriesWithNumericVariable" language="csharp"> /// Console.WriteLine(&quot;\n\nQuery for the average temperature over the past 30 seconds, in 2-second time slots.\n&quot;); /// /// var numericVariable = new NumericVariable( /// new TimeSeriesExpression(&quot;$event.Temperature&quot;), /// new TimeSeriesExpression(&quot;avg($value)&quot;)); /// /// var requestOptions = new QueryAggregateSeriesRequestOptions(); /// requestOptions.InlineVariables[&quot;Temperature&quot;] = numericVariable; /// requestOptions.ProjectedVariableNames.Add(&quot;Temperature&quot;); /// /// TimeSeriesQueryAnalyzer aggregateSeriesQuery = queriesClient.CreateAggregateSeriesQuery( /// tsId, /// TimeSpan.FromSeconds(2), /// TimeSpan.FromSeconds(30), /// null, /// requestOptions); /// /// await foreach (TimeSeriesPoint point in aggregateSeriesQuery.GetResultsAsync()) /// { /// double? averageTemperature = point.GetNullableDouble(&quot;Temperature&quot;); /// if (averageTemperature != null) /// { /// Console.WriteLine($&quot;{point.Timestamp} - Average temperature: {averageTemperature}.&quot;); /// } /// } /// </code> /// </example> public virtual TimeSeriesQueryAnalyzer CreateAggregateSeriesQuery( TimeSeriesId timeSeriesId, TimeSpan interval, TimeSpan timeSpan, DateTimeOffset? endTime = null, QueryAggregateSeriesRequestOptions options = null, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(CreateAggregateSeriesQuery)}"); scope.Start(); try { DateTimeOffset rangeEndTime = endTime ?? DateTimeOffset.UtcNow; DateTimeOffset rangeStartTime = rangeEndTime - timeSpan; var searchSpan = new DateTimeRange(rangeStartTime, rangeEndTime); var queryRequest = new QueryRequest { AggregateSeries = new AggregateSeries(timeSeriesId, searchSpan, interval) }; BuildAggregateSeriesRequestOptions(options, queryRequest); return new TimeSeriesQueryAnalyzer(_queryRestClient, queryRequest, options?.Store?.ToString(), cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } private static void BuildEventsRequestOptions(QueryEventsRequestOptions options, QueryRequest queryRequest) { if (options != null) { if (options.Filter != null) { queryRequest.GetEvents.Filter = options.Filter; } if (options.ProjectedProperties != null) { foreach (TimeSeriesInsightsEventProperty projectedProperty in options.ProjectedProperties) { queryRequest.GetEvents.ProjectedProperties.Add(projectedProperty); } } queryRequest.GetEvents.Take = options.MaxNumberOfEvents; } } private static void BuildSeriesRequestOptions(QuerySeriesRequestOptions options, QueryRequest queryRequest) { if (options != null) { if (options.Filter != null) { queryRequest.GetSeries.Filter = options.Filter; } if (options.ProjectedVariableNames != null) { foreach (string projectedVariable in options.ProjectedVariableNames) { queryRequest.GetSeries.ProjectedVariables.Add(projectedVariable); } } if (options.InlineVariables != null) { foreach (string inlineVariableKey in options.InlineVariables.Keys) { queryRequest.GetSeries.InlineVariables[inlineVariableKey] = options.InlineVariables[inlineVariableKey]; } } queryRequest.GetSeries.Take = options.MaxNumberOfEvents; } } private static void BuildAggregateSeriesRequestOptions(QueryAggregateSeriesRequestOptions options, QueryRequest queryRequest) { if (options != null) { if (options.Filter != null) { queryRequest.AggregateSeries.Filter = options.Filter; } if (options.ProjectedVariableNames != null) { foreach (string projectedVariable in options.ProjectedVariableNames) { queryRequest.AggregateSeries.ProjectedVariables.Add(projectedVariable); } } if (options.InlineVariables != null) { foreach (string inlineVariableKey in options.InlineVariables.Keys) { queryRequest.AggregateSeries.InlineVariables[inlineVariableKey] = options.InlineVariables[inlineVariableKey]; } } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.DataLake.Store; using Microsoft.Azure.Management.DataLake.Store.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.DataLake.Store { /// <summary> /// Creates a Data Lake Store account management client. /// </summary> public partial class DataLakeStoreManagementClient : ServiceClient<DataLakeStoreManagementClient>, IDataLakeStoreManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private string _userAgentSuffix; /// <summary> /// Gets or sets the additional UserAgent text to be added to the user /// agent header. This is used to further differentiate where requests /// are coming from internally. /// </summary> public string UserAgentSuffix { get { return this._userAgentSuffix; } set { this._userAgentSuffix = value; } } private IDataLakeStoreAccountOperations _dataLakeStoreAccount; /// <summary> /// Operations for managing Data Lake Store accounts /// </summary> public virtual IDataLakeStoreAccountOperations DataLakeStoreAccount { get { return this._dataLakeStoreAccount; } } /// <summary> /// Initializes a new instance of the DataLakeStoreManagementClient /// class. /// </summary> public DataLakeStoreManagementClient() : base() { this._dataLakeStoreAccount = new DataLakeStoreAccountOperations(this); this._userAgentSuffix = ""; this._apiVersion = "2015-10-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the DataLakeStoreManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public DataLakeStoreManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the DataLakeStoreManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public DataLakeStoreManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the DataLakeStoreManagementClient /// class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public DataLakeStoreManagementClient(HttpClient httpClient) : base(httpClient) { this._dataLakeStoreAccount = new DataLakeStoreAccountOperations(this); this._userAgentSuffix = ""; this._apiVersion = "2015-10-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the DataLakeStoreManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public DataLakeStoreManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the DataLakeStoreManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public DataLakeStoreManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// DataLakeStoreManagementClient instance /// </summary> /// <param name='client'> /// Instance of DataLakeStoreManagementClient to clone to /// </param> protected override void Clone(ServiceClient<DataLakeStoreManagementClient> client) { base.Clone(client); if (client is DataLakeStoreManagementClient) { DataLakeStoreManagementClient clonedClient = ((DataLakeStoreManagementClient)client); clonedClient._userAgentSuffix = this._userAgentSuffix; clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// Parse enum values for type DataLakeStoreAccountState. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static DataLakeStoreAccountState ParseDataLakeStoreAccountState(string value) { if ("active".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeStoreAccountState.Active; } if ("suspended".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeStoreAccountState.Suspended; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type DataLakeStoreAccountState to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string DataLakeStoreAccountStateToString(DataLakeStoreAccountState value) { if (value == DataLakeStoreAccountState.Active) { return "active"; } if (value == DataLakeStoreAccountState.Suspended) { return "suspended"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type DataLakeStoreAccountStatus. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static DataLakeStoreAccountStatus ParseDataLakeStoreAccountStatus(string value) { if ("Failed".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeStoreAccountStatus.Failed; } if ("Creating".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeStoreAccountStatus.Creating; } if ("Running".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeStoreAccountStatus.Running; } if ("Succeeded".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeStoreAccountStatus.Succeeded; } if ("Patching".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeStoreAccountStatus.Patching; } if ("Suspending".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeStoreAccountStatus.Suspending; } if ("Resuming".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeStoreAccountStatus.Resuming; } if ("Deleting".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeStoreAccountStatus.Deleting; } if ("Deleted".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DataLakeStoreAccountStatus.Deleted; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type DataLakeStoreAccountStatus to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string DataLakeStoreAccountStatusToString(DataLakeStoreAccountStatus value) { if (value == DataLakeStoreAccountStatus.Failed) { return "Failed"; } if (value == DataLakeStoreAccountStatus.Creating) { return "Creating"; } if (value == DataLakeStoreAccountStatus.Running) { return "Running"; } if (value == DataLakeStoreAccountStatus.Succeeded) { return "Succeeded"; } if (value == DataLakeStoreAccountStatus.Patching) { return "Patching"; } if (value == DataLakeStoreAccountStatus.Suspending) { return "Suspending"; } if (value == DataLakeStoreAccountStatus.Resuming) { return "Resuming"; } if (value == DataLakeStoreAccountStatus.Deleting) { return "Deleting"; } if (value == DataLakeStoreAccountStatus.Deleted) { return "Deleted"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='azureAsyncOperation'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<AzureAsyncOperationResponse> GetLongRunningOperationStatusAsync(string azureAsyncOperation, CancellationToken cancellationToken) { // Validate if (azureAsyncOperation == null) { throw new ArgumentNullException("azureAsyncOperation"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("azureAsyncOperation", azureAsyncOperation); TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + azureAsyncOperation; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureAsyncOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AzureAsyncOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true)); result.Status = statusInstance; } JToken errorValue = responseDoc["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { Error errorInstance = new Error(); result.Error = errorInstance; JToken codeValue = errorValue["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = errorValue["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = errorValue["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } JToken detailsArray = errorValue["details"]; if (detailsArray != null && detailsArray.Type != JTokenType.Null) { foreach (JToken detailsValue in ((JArray)detailsArray)) { ErrorDetails errorDetailsInstance = new ErrorDetails(); errorInstance.Details.Add(errorDetailsInstance); JToken codeValue2 = detailsValue["code"]; if (codeValue2 != null && codeValue2.Type != JTokenType.Null) { string codeInstance2 = ((string)codeValue2); errorDetailsInstance.Code = codeInstance2; } JToken messageValue2 = detailsValue["message"]; if (messageValue2 != null && messageValue2.Type != JTokenType.Null) { string messageInstance2 = ((string)messageValue2); errorDetailsInstance.Message = messageInstance2; } JToken targetValue2 = detailsValue["target"]; if (targetValue2 != null && targetValue2.Type != JTokenType.Null) { string targetInstance2 = ((string)targetValue2); errorDetailsInstance.Target = targetInstance2; } } } JToken innerErrorValue = errorValue["innerError"]; if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null) { InnerError innerErrorInstance = new InnerError(); errorInstance.InnerError = innerErrorInstance; JToken traceValue = innerErrorValue["trace"]; if (traceValue != null && traceValue.Type != JTokenType.Null) { string traceInstance = ((string)traceValue); innerErrorInstance.Trace = traceInstance; } JToken contextValue = innerErrorValue["context"]; if (contextValue != null && contextValue.Type != JTokenType.Null) { string contextInstance = ((string)contextValue); innerErrorInstance.Context = contextInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata { public struct TypeDefinition { private readonly MetadataReader _reader; // Workaround: JIT doesn't generate good code for nested structures, so use RowId. private readonly uint _treatmentAndRowId; internal TypeDefinition(MetadataReader reader, uint treatmentAndRowId) { Debug.Assert(reader != null); Debug.Assert(treatmentAndRowId != 0); _reader = reader; _treatmentAndRowId = treatmentAndRowId; } private uint RowId { get { return _treatmentAndRowId & TokenTypeIds.RIDMask; } } private TypeDefTreatment Treatment { get { return (TypeDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); } } private TypeDefinitionHandle Handle { get { return TypeDefinitionHandle.FromRowId(RowId); } } public TypeAttributes Attributes { get { if (Treatment == 0) { return _reader.TypeDefTable.GetFlags(Handle); } return GetProjectedFlags(); } } /// <summary> /// Name of the type. /// </summary> public StringHandle Name { get { if (Treatment == 0) { return _reader.TypeDefTable.GetName(Handle); } return GetProjectedName(); } } /// <summary> /// Namespace of the type, or nil if the type is nested or defined in a root namespace. /// </summary> public NamespaceDefinitionHandle Namespace { get { if (Treatment == 0) { return _reader.TypeDefTable.GetNamespace(Handle); } return GetProjectedNamespace(); } } /// <summary> /// The base type of the type definition: either /// <see cref="TypeSpecificationHandle"/>, <see cref="TypeReferenceHandle"/> or <see cref="TypeDefinitionHandle"/>. /// </summary> public Handle BaseType { get { if (Treatment == 0) { return _reader.TypeDefTable.GetExtends(Handle); } return GetProjectedBaseType(); } } public TypeLayout GetLayout() { uint classLayoutRowId = _reader.ClassLayoutTable.FindRow(Handle); if (classLayoutRowId == 0) { // NOTE: We don't need a bool/TryGetLayout because zero also means use default: // // Spec: // ClassSize of zero does not mean the class has zero size. It means that no .size directive was specified // at definition time, in which case, the actual size is calculated from the field types, taking account of // packing size (default or specified) and natural alignment on the target, runtime platform. // // PackingSize shall be one of {0, 1, 2, 4, 8, 16, 32, 64, 128}. (0 means use // the default pack size for the platform on which the application is // running.) return default(TypeLayout); } int size = (int)_reader.ClassLayoutTable.GetClassSize(classLayoutRowId); int packingSize = _reader.ClassLayoutTable.GetPackingSize(classLayoutRowId); return new TypeLayout(size, packingSize); } /// <summary> /// Returns the enclosing type of a specified nested type or nil handle if the type is not nested. /// </summary> public TypeDefinitionHandle GetDeclaringType() { return _reader.NestedClassTable.FindEnclosingType(Handle); } public GenericParameterHandleCollection GetGenericParameters() { return _reader.GenericParamTable.FindGenericParametersForType(Handle); } public MethodDefinitionHandleCollection GetMethods() { return new MethodDefinitionHandleCollection(_reader, Handle); } public FieldDefinitionHandleCollection GetFields() { return new FieldDefinitionHandleCollection(_reader, Handle); } public PropertyDefinitionHandleCollection GetProperties() { return new PropertyDefinitionHandleCollection(_reader, Handle); } public EventDefinitionHandleCollection GetEvents() { return new EventDefinitionHandleCollection(_reader, Handle); } /// <summary> /// Returns an array of types nested in the specified type. /// </summary> public ImmutableArray<TypeDefinitionHandle> GetNestedTypes() { return _reader.GetNestedTypes(Handle); } public MethodImplementationHandleCollection GetMethodImplementations() { return new MethodImplementationHandleCollection(_reader, Handle); } public InterfaceImplementationHandleCollection GetInterfaceImplementations() { return new InterfaceImplementationHandleCollection(_reader, Handle); } public CustomAttributeHandleCollection GetCustomAttributes() { return new CustomAttributeHandleCollection(_reader, Handle); } public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes() { return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle); } #region Projections private TypeAttributes GetProjectedFlags() { var flags = _reader.TypeDefTable.GetFlags(Handle); var treatment = Treatment; switch (treatment & TypeDefTreatment.KindMask) { case TypeDefTreatment.NormalNonAttribute: flags |= TypeAttributes.WindowsRuntime | TypeAttributes.Import; break; case TypeDefTreatment.NormalAttribute: flags |= TypeAttributes.WindowsRuntime | TypeAttributes.Sealed; break; case TypeDefTreatment.UnmangleWinRTName: flags = flags & ~TypeAttributes.SpecialName | TypeAttributes.Public; break; case TypeDefTreatment.PrefixWinRTName: flags = flags & ~TypeAttributes.Public | TypeAttributes.Import; break; case TypeDefTreatment.RedirectedToClrType: flags = flags & ~TypeAttributes.Public | TypeAttributes.Import; break; case TypeDefTreatment.RedirectedToClrAttribute: flags &= ~TypeAttributes.Public; break; } if ((treatment & TypeDefTreatment.MarkAbstractFlag) != 0) { flags |= TypeAttributes.Abstract; } if ((treatment & TypeDefTreatment.MarkInternalFlag) != 0) { flags &= ~TypeAttributes.Public; } return flags; } private StringHandle GetProjectedName() { var name = _reader.TypeDefTable.GetName(Handle); switch (Treatment & TypeDefTreatment.KindMask) { case TypeDefTreatment.UnmangleWinRTName: return name.SuffixRaw(MetadataReader.ClrPrefix.Length); case TypeDefTreatment.PrefixWinRTName: return name.WithWinRTPrefix(); } return name; } private NamespaceDefinitionHandle GetProjectedNamespace() { // NOTE: NamespaceDefinitionHandle currently relies on never having virtual values. If this ever gets projected // to a virtual namespace name, then that assumption will need to be removed. // no change: return _reader.TypeDefTable.GetNamespace(Handle); } private Handle GetProjectedBaseType() { // no change: return _reader.TypeDefTable.GetExtends(Handle); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using InstallerLib; using dotNetUnitTestsRunner; using System.IO; namespace dotNetInstallerUnitTests { [TestFixture] public class UninstallUnitTests { [Test] public void TestSupportsNone() { Console.WriteLine("TestSupportsNone"); // a configuration with no components ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); setupConfiguration.supports_install = false; setupConfiguration.supports_uninstall = false; // save config file string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // execute dotNetInstaller Assert.AreNotEqual(0, dotNetInstallerExeUtils.Run(configFilename)); File.Delete(configFilename); } [Test] public void TestSupportsInstall() { Console.WriteLine("TestSupportsInstall"); // a configuration with no components ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); setupConfiguration.supports_install = true; setupConfiguration.supports_uninstall = false; // save config file string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename)); // uninstall is not supported dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions(configFilename); options.uninstall = true; Assert.AreNotEqual(0, dotNetInstallerExeUtils.Run(options)); File.Delete(configFilename); } [Test] public void TestSupportsUninstall() { Console.WriteLine("TestSupportsUninstall"); // a configuration with no components ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); setupConfiguration.supports_install = false; setupConfiguration.supports_uninstall = true; // save config file string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // execute dotNetInstaller Assert.AreNotEqual(0, dotNetInstallerExeUtils.Run(configFilename)); // uninstall is not supported dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions(configFilename); options.uninstall = true; Assert.AreEqual(0, dotNetInstallerExeUtils.Run(options)); File.Delete(configFilename); } [Test] public void TestUninstallSwitch() { Console.WriteLine("TestUninstallSwitch"); ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); ComponentCmd cmd = new ComponentCmd(); setupConfiguration.Children.Add(cmd); cmd.command = "cmd.exe /C exit /b 1"; // would fail if ran cmd.required_install = true; cmd.uninstall_command = "cmd.exe /C exit /b 0"; cmd.supports_install = true; cmd.supports_uninstall = true; string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // execute uninstall dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions(configFilename); options.uninstall = false; Assert.AreNotEqual(0, dotNetInstallerExeUtils.Run(options)); options.uninstall = true; Assert.AreEqual(0, dotNetInstallerExeUtils.Run(options)); File.Delete(configFilename); } [Test] public void TestUninstallAuto() { Console.WriteLine("TestUninstallAuto"); // a component that's already installed ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); ComponentCmd cmd = new ComponentCmd(); setupConfiguration.Children.Add(cmd); cmd.id = "cmd1"; cmd.command = "cmd.exe /C exit /b 1"; // would fail if ran cmd.uninstall_command = "cmd.exe /C exit /b 0"; cmd.supports_install = true; cmd.supports_uninstall = true; InstalledCheckFile check = new InstalledCheckFile(); cmd.Children.Add(check); check.comparison = installcheckfile_comparison.exists; check.filename = dotNetInstallerExeUtils.Executable; // a second component that doesn't support uninstall ComponentCmd cmd2 = new ComponentCmd(); setupConfiguration.Children.Add(cmd2); cmd2.id = "cmd2"; cmd2.command = "cmd.exe /C exit /b 1"; // would fail if ran cmd2.uninstall_command = "cmd.exe /C exit /b 1"; // would fail if ran cmd2.supports_install = true; cmd2.supports_uninstall = false; cmd2.Children.Add(check); string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // will fallback to uninstall since all components are installed Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename)); File.Delete(configFilename); } [Test] public void TestUninstallMsiSilentMode() { Console.WriteLine("TestUninstallMsiSilentMode"); InstallUILevel[] testUILevels = { InstallUILevel.basic, InstallUILevel.silent }; foreach (InstallUILevel uilevel in testUILevels) { // a configuration with no components ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); ComponentMsi msi = new ComponentMsi(); msi.package = "msidoesntexist.msi"; msi.uninstall_cmdparameters = ""; msi.uninstall_cmdparameters_basic = "/qb-"; msi.uninstall_cmdparameters_silent = "/qb-"; InstalledCheckFile self = new InstalledCheckFile(); self.filename = dotNetInstallerExeUtils.Executable; self.comparison = installcheckfile_comparison.exists; msi.Children.Add(self); setupConfiguration.Children.Add(msi); // silent install, no dialog messages configFile.ui_level = uilevel; // save config file string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // execute dotNetInstaller dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions(configFilename); options.uninstall = true; Assert.AreEqual(1619, dotNetInstallerExeUtils.Run(options)); File.Delete(configFilename); } } [Test] public void TestUninstallMspSilentMode() { Console.WriteLine("TestUninstallMspSilentMode"); InstallUILevel[] testUILevels = { InstallUILevel.basic, InstallUILevel.silent }; foreach (InstallUILevel uilevel in testUILevels) { // a configuration with no components ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); ComponentMsp msp = new ComponentMsp(); msp.package = "mspdoesntexist.msp"; msp.uninstall_cmdparameters = ""; msp.uninstall_cmdparameters_basic = "/qb-"; msp.uninstall_cmdparameters_silent = "/qb-"; InstalledCheckFile self = new InstalledCheckFile(); self.filename = dotNetInstallerExeUtils.Executable; self.comparison = installcheckfile_comparison.exists; msp.Children.Add(self); setupConfiguration.Children.Add(msp); // silent install, no dialog messages configFile.ui_level = uilevel; // save config file string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // execute dotNetInstaller dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions(configFilename); options.uninstall = true; Assert.AreEqual(1619, dotNetInstallerExeUtils.Run(options)); File.Delete(configFilename); } } [Test] public void TestUninstallAutoWithOptionalComponent() { Console.WriteLine("TestUninstallAutoWithOptionalComponent"); // a component that's already installed ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); ComponentCmd cmd = new ComponentCmd(); setupConfiguration.Children.Add(cmd); cmd.id = "cmd1"; cmd.command = "cmd.exe /C exit /b 1"; // would fail if ran cmd.uninstall_command = "cmd.exe /C exit /b 0"; cmd.supports_install = true; cmd.supports_uninstall = true; InstalledCheckFile check = new InstalledCheckFile(); cmd.Children.Add(check); check.comparison = installcheckfile_comparison.exists; check.filename = dotNetInstallerExeUtils.Executable; // a second component that is optional ComponentCmd cmd2 = new ComponentCmd(); setupConfiguration.Children.Add(cmd2); cmd2.id = "cmd2"; cmd2.command = "cmd.exe /C exit /b 1"; // would fail if ran cmd2.uninstall_command = "cmd.exe /C exit /b 1"; // would fail if ran cmd2.supports_install = true; cmd2.required_install = false; cmd2.supports_uninstall = false; cmd2.Children.Add(check); string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // will fallback to uninstall since all required components are installed Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename)); File.Delete(configFilename); } } }
// *********************************************************************** // Copyright (c) 2012-2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.IO; using System.Reflection; using System.Threading; using NUnit.Common; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Execution; #if !SILVERLIGHT && !NETCF && !PORTABLE using System.Diagnostics; using System.Windows.Forms; #endif namespace NUnit.Framework.Api { /// <summary> /// Implementation of ITestAssemblyRunner /// </summary> public class NUnitTestAssemblyRunner : ITestAssemblyRunner { private static Logger log = InternalTrace.GetLogger("DefaultTestAssemblyRunner"); private ITestAssemblyBuilder _builder; private ManualResetEvent _runComplete = new ManualResetEvent(false); #if !SILVERLIGHT && !NETCF && !PORTABLE // Saved Console.Out and Console.Error private TextWriter _savedOut; private TextWriter _savedErr; #endif #if PARALLEL // Event Pump private EventPump _pump; #endif #region Constructors /// <summary> /// Initializes a new instance of the <see cref="NUnitTestAssemblyRunner"/> class. /// </summary> /// <param name="builder">The builder.</param> public NUnitTestAssemblyRunner(ITestAssemblyBuilder builder) { _builder = builder; } #endregion #region Properties #if PARALLEL /// <summary> /// Gets the default level of parallel execution (worker threads) /// </summary> public static int DefaultLevelOfParallelism { #if NETCF get { return 2; } #else get { return Math.Max(Environment.ProcessorCount, 2); } #endif } #endif /// <summary> /// The tree of tests that was loaded by the builder /// </summary> public ITest LoadedTest { get; private set; } /// <summary> /// The test result, if a run has completed /// </summary> public ITestResult Result { get { return TopLevelWorkItem == null ? null : TopLevelWorkItem.Result; } } /// <summary> /// Indicates whether a test is loaded /// </summary> public bool IsTestLoaded { get { return LoadedTest != null; } } /// <summary> /// Indicates whether a test is running /// </summary> public bool IsTestRunning { get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Running; } } /// <summary> /// Indicates whether a test run is complete /// </summary> public bool IsTestComplete { get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Complete; } } /// <summary> /// Our settings, specified when loading the assembly /// </summary> private IDictionary Settings { get; set; } /// <summary> /// The top level WorkItem created for the assembly as a whole /// </summary> private WorkItem TopLevelWorkItem { get; set; } /// <summary> /// The TestExecutionContext for the top level WorkItem /// </summary> private TestExecutionContext Context { get; set; } #endregion #region Public Methods /// <summary> /// Loads the tests found in an Assembly /// </summary> /// <param name="assemblyName">File name of the assembly to load</param> /// <param name="settings">Dictionary of option settings for loading the assembly</param> /// <returns>True if the load was successful</returns> public ITest Load(string assemblyName, IDictionary settings) { Settings = settings; Randomizer.InitialSeed = GetInitialSeed(settings); return LoadedTest = _builder.Build(assemblyName, settings); } /// <summary> /// Loads the tests found in an Assembly /// </summary> /// <param name="assembly">The assembly to load</param> /// <param name="settings">Dictionary of option settings for loading the assembly</param> /// <returns>True if the load was successful</returns> public ITest Load(Assembly assembly, IDictionary settings) { Settings = settings; Randomizer.InitialSeed = GetInitialSeed(settings); return LoadedTest = _builder.Build(assembly, settings); } /// <summary> /// Count Test Cases using a filter /// </summary> /// <param name="filter">The filter to apply</param> /// <returns>The number of test cases found</returns> public int CountTestCases(ITestFilter filter) { if (LoadedTest == null) throw new InvalidOperationException("The CountTestCases method was called but no test has been loaded"); return CountTestCases(LoadedTest, filter); } /// <summary> /// Run selected tests and return a test result. The test is run synchronously, /// and the listener interface is notified as it progresses. /// </summary> /// <param name="listener">Interface to receive EventListener notifications.</param> /// <param name="filter">A test filter used to select tests to be run</param> /// <returns></returns> public ITestResult Run(ITestListener listener, ITestFilter filter) { RunAsync(listener, filter); WaitForCompletion(Timeout.Infinite); return Result; } /// <summary> /// Run selected tests asynchronously, notifying the listener interface as it progresses. /// </summary> /// <param name="listener">Interface to receive EventListener notifications.</param> /// <param name="filter">A test filter used to select tests to be run</param> /// <remarks> /// RunAsync is a template method, calling various abstract and /// virtual methods to be overridden by derived classes. /// </remarks> public void RunAsync(ITestListener listener, ITestFilter filter) { log.Info("Running tests"); if (LoadedTest == null) throw new InvalidOperationException("The Run method was called but no test has been loaded"); _runComplete.Reset(); CreateTestExecutionContext(listener); TopLevelWorkItem = WorkItem.CreateWorkItem(LoadedTest, filter); TopLevelWorkItem.InitializeContext(Context); TopLevelWorkItem.Completed += OnRunCompleted; StartRun(listener); } /// <summary> /// Wait for the ongoing run to complete. /// </summary> /// <param name="timeout">Time to wait in milliseconds</param> /// <returns>True if the run completed, otherwise false</returns> public bool WaitForCompletion(int timeout) { #if !SILVERLIGHT && !PORTABLE return _runComplete.WaitOne(timeout, false); #else return _runComplete.WaitOne(timeout); #endif } /// <summary> /// Initiate the test run. /// </summary> public void StartRun(ITestListener listener) { #if !SILVERLIGHT && !NETCF && !PORTABLE // Save Console.Out and Error for later restoration _savedOut = Console.Out; _savedErr = Console.Error; Console.SetOut(new TextCapture(Console.Out)); Console.SetError(new TextCapture(Console.Error)); #endif #if PARALLEL // Queue and pump events, unless settings have SynchronousEvents == false if (!Settings.Contains(PackageSettings.SynchronousEvents) || !(bool)Settings[PackageSettings.SynchronousEvents]) { QueuingEventListener queue = new QueuingEventListener(); Context.Listener = queue; _pump = new EventPump(listener, queue.Events); _pump.Start(); } #endif #if !NETCF if (!System.Diagnostics.Debugger.IsAttached && Settings.Contains(PackageSettings.DebugTests) && (bool)Settings[PackageSettings.DebugTests]) System.Diagnostics.Debugger.Launch(); #if !SILVERLIGHT && !PORTABLE if (Settings.Contains(PackageSettings.PauseBeforeRun) && (bool)Settings[PackageSettings.PauseBeforeRun]) PauseBeforeRun(); #endif #endif Context.Dispatcher.Dispatch(TopLevelWorkItem); } /// <summary> /// Signal any test run that is in process to stop. Return without error if no test is running. /// </summary> /// <param name="force">If true, kill any tests that are currently running</param> public void StopRun(bool force) { if (IsTestRunning) { Context.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested; Context.Dispatcher.CancelRun(force); } } #endregion #region Helper Methods /// <summary> /// Create the initial TestExecutionContext used to run tests /// </summary> /// <param name="listener">The ITestListener specified in the RunAsync call</param> private void CreateTestExecutionContext(ITestListener listener) { Context = new TestExecutionContext(); if (Settings.Contains(PackageSettings.DefaultTimeout)) Context.TestCaseTimeout = (int)Settings[PackageSettings.DefaultTimeout]; if (Settings.Contains(PackageSettings.StopOnError)) Context.StopOnError = (bool)Settings[PackageSettings.StopOnError]; if (Settings.Contains(PackageSettings.WorkDirectory)) Context.WorkDirectory = (string)Settings[PackageSettings.WorkDirectory]; else Context.WorkDirectory = Env.DefaultWorkDirectory; // Overriding runners may replace this Context.Listener = listener; #if PARALLEL int levelOfParallelism = GetLevelOfParallelism(); if (levelOfParallelism > 0) { Context.Dispatcher = new ParallelWorkItemDispatcher(levelOfParallelism); // Assembly does not have IApplyToContext attributes applied // when the test is built, so we do it here. // TODO: Generalize this if (LoadedTest.Properties.ContainsKey(PropertyNames.ParallelScope)) Context.ParallelScope = (ParallelScope)LoadedTest.Properties.Get(PropertyNames.ParallelScope) & ~ParallelScope.Self; } else Context.Dispatcher = new SimpleWorkItemDispatcher(); #else Context.Dispatcher = new SimpleWorkItemDispatcher(); #endif } /// <summary> /// Handle the the Completed event for the top level work item /// </summary> private void OnRunCompleted(object sender, EventArgs e) { #if PARALLEL if (_pump != null) _pump.Dispose(); #endif #if !SILVERLIGHT && !NETCF && !PORTABLE Console.SetOut(_savedOut); Console.SetError(_savedErr); #endif _runComplete.Set(); } private int CountTestCases(ITest test, ITestFilter filter) { if (!test.IsSuite) return 1; int count = 0; foreach (ITest child in test.Tests) if (filter.Pass(child)) count += CountTestCases(child, filter); return count; } private static int GetInitialSeed(IDictionary settings) { return settings.Contains(PackageSettings.RandomSeed) ? (int)settings[PackageSettings.RandomSeed] : new Random().Next(); } #if PARALLEL private int GetLevelOfParallelism() { return Settings.Contains(PackageSettings.NumberOfTestWorkers) ? (int)Settings[PackageSettings.NumberOfTestWorkers] : (LoadedTest.Properties.ContainsKey(PropertyNames.LevelOfParallelism) ? (int)LoadedTest.Properties.Get(PropertyNames.LevelOfParallelism) : NUnitTestAssemblyRunner.DefaultLevelOfParallelism); } #endif #if !SILVERLIGHT && !NETCF && !PORTABLE private static void PauseBeforeRun() { var process = Process.GetCurrentProcess(); string attachMessage = string.Format("Attach debugger to Process {0}.exe with Id {1} if desired.", process.ProcessName, process.Id); MessageBox.Show(attachMessage, process.ProcessName, MessageBoxButtons.OK, MessageBoxIcon.Information); } #endif #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class AverageTests { // // Average // // Get a set of ranges from 0 to each count, with an extra parameter containing the expected average. public static IEnumerable<object[]> AverageData(int[] counts) { Func<int, double> average = x => (x - 1) / 2.0; foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), average)) yield return results; } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Int(Labeled<ParallelQuery<int>> labeled, int count, double average) { ParallelQuery<int> query = labeled.Item; Assert.Equal(average, query.Average()); Assert.Equal((double?)average, query.Select(x => (int?)x).Average()); Assert.Equal(-average, query.Average(x => -x)); Assert.Equal(-(double?)average, query.Average(x => -(int?)x)); } [Theory] [OuterLoop] [MemberData("AverageData", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }))] public static void Average_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double average) { Average_Int(labeled, count, average); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double average) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (int?)x : null).Average()); Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(int?)x : null)); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double average) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (int?)null).Average()); Assert.Null(query.Average(x => (int?)null)); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Long(Labeled<ParallelQuery<int>> labeled, int count, double average) { ParallelQuery<int> query = labeled.Item; Assert.Equal(average, query.Select(x => (long)x).Average()); Assert.Equal((double?)average, query.Select(x => (long?)x).Average()); Assert.Equal(-average, query.Average(x => -(long)x)); Assert.Equal(-(double?)average, query.Average(x => -(long?)x)); } [Theory] [OuterLoop] [MemberData("AverageData", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }))] public static void Average_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double average) { Average_Long(labeled, count, average); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Average_Long_Overflow(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? 1 : long.MaxValue).Average()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? (long?)1 : long.MaxValue).Average()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Average(x => x == 0 ? -1 : long.MinValue)); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Average(x => x == 0 ? (long?)-1 : long.MinValue)); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double average) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (long?)x : null).Average()); Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(long?)x : null)); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double average) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (long?)null).Average()); Assert.Null(query.Average(x => (long?)null)); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Float(Labeled<ParallelQuery<int>> labeled, int count, float average) { ParallelQuery<int> query = labeled.Item; Assert.Equal(average, query.Select(x => (float)x).Average()); Assert.Equal((float?)average, query.Select(x => (float?)x).Average()); Assert.Equal(-average, query.Average(x => -(float)x)); Assert.Equal(-(float?)average, query.Average(x => -(float?)x)); } [Theory] [OuterLoop] [MemberData("AverageData", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }))] public static void Average_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float average) { Average_Float(labeled, count, average); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float average) { ParallelQuery<int> query = labeled.Item; Assert.Equal((float?)Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (float?)x : null).Average()); Assert.Equal((float?)Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(float?)x : null)); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float average) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (float?)null).Average()); Assert.Null(query.Average(x => (float?)null)); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Double(Labeled<ParallelQuery<int>> labeled, int count, double average) { ParallelQuery<int> query = labeled.Item; Assert.Equal(average, query.Select(x => (double)x).Average()); Assert.Equal((double?)average, query.Select(x => (double?)x).Average()); Assert.Equal(-average, query.Average(x => -(double)x)); Assert.Equal(-(double?)average, query.Average(x => -(double?)x)); } [Theory] [OuterLoop] [MemberData("AverageData", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }))] public static void Average_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double average) { Average_Double(labeled, count, average); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double average) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (double?)x : null).Average()); Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(double?)x : null)); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double average) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (double?)null).Average()); Assert.Null(query.Average(x => (double?)null)); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal average) { ParallelQuery<int> query = labeled.Item; Assert.Equal(average, query.Select(x => (decimal)x).Average()); Assert.Equal((decimal?)average, query.Select(x => (decimal?)x).Average()); Assert.Equal(-average, query.Average(x => -(decimal)x)); Assert.Equal(-(decimal?)average, query.Average(x => -(decimal?)x)); } [Theory] [OuterLoop] [MemberData("AverageData", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }))] public static void Average_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal average) { Average_Decimal(labeled, count, average); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal average) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (decimal?)x : null).Average()); Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(decimal?)x : null)); } [Theory] [MemberData("AverageData", (object)(new int[] { 1, 2, 16 }))] public static void Average_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal average) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (decimal?)null).Average()); Assert.Null(query.Average(x => (decimal?)null)); } [Fact] public static void Average_InvalidOperationException() { Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Average()); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Average(x => x)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<long>().Average()); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<long>().Average(x => x)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<float>().Average()); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<float>().Average(x => x)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<double>().Average()); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<double>().Average(x => x)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<decimal>().Average()); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<decimal>().Average(x => x)); // Nullables return null when empty Assert.Null(ParallelEnumerable.Empty<int?>().Average()); Assert.Null(ParallelEnumerable.Empty<int?>().Average(x => x)); Assert.Null(ParallelEnumerable.Empty<long?>().Average()); Assert.Null(ParallelEnumerable.Empty<long?>().Average(x => x)); Assert.Null(ParallelEnumerable.Empty<float?>().Average()); Assert.Null(ParallelEnumerable.Empty<float?>().Average(x => x)); Assert.Null(ParallelEnumerable.Empty<double?>().Average()); Assert.Null(ParallelEnumerable.Empty<double?>().Average(x => x)); Assert.Null(ParallelEnumerable.Empty<decimal?>().Average()); Assert.Null(ParallelEnumerable.Empty<decimal?>().Average(x => x)); } [Theory] [MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void Average_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (int?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (long)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (long?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (float)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (float?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (double)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (double?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (decimal)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (decimal?)x)); } [Theory] [MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void Average_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, int>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, int?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, long>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, long?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, float>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, float?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, double>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, double?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, decimal>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, decimal?>)(x => { throw new DeliberateTestException(); }))); } [Fact] public static void Average_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Average()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Average((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Average()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Average((Func<int?, int?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Average()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Average((Func<long, long>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Average()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Average((Func<long?, long?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Average()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Average((Func<float, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Average()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Average((Func<float?, float?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Average()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Average((Func<double, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Average()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Average((Func<double?, double?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Average()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Average((Func<decimal, decimal>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Average()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Average((Func<decimal?, decimal?>)null)); } } }
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Apis.Http; using Google.Apis.Upload; using Google.Cloud.ClientTesting; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Xunit; using Object = Google.Apis.Storage.v1.Data.Object; namespace Google.Cloud.Storage.V1.IntegrationTests { using static TestHelpers; [Collection(nameof(StorageFixture))] public class UploadObjectTest { private readonly StorageFixture _fixture; public UploadObjectTest(StorageFixture fixture) { _fixture = fixture; } [Fact] public void SimpleUpload() { var name = IdGenerator.FromGuid(); var contentType = "application/octet-stream"; var source = GenerateData(100); var result = _fixture.Client.UploadObject(_fixture.MultiVersionBucket, name, contentType, source); Assert.Equal(_fixture.MultiVersionBucket, result.Bucket); Assert.Equal(name, result.Name); Assert.Equal(contentType, result.ContentType); ValidateData(_fixture.MultiVersionBucket, name, source); } [Fact] public void UploadWithObject() { var destination = new Object { Bucket = _fixture.MultiVersionBucket, Name = IdGenerator.FromGuid(), ContentType = "test/type", ContentDisposition = "attachment", Metadata = new Dictionary<string, string> { { "x", "y" } } }; var source = GenerateData(100); var result = _fixture.Client.UploadObject(destination, source); Assert.NotSame(destination, result); Assert.Equal(destination.Name, result.Name); Assert.Equal(destination.Bucket, result.Bucket); Assert.Equal(destination.ContentType, result.ContentType); Assert.Equal(destination.ContentDisposition, result.ContentDisposition); Assert.Equal(destination.Metadata, result.Metadata); ValidateData(_fixture.MultiVersionBucket, destination.Name, source); } [Fact] public async Task UploadAsyncWithProgress() { var chunks = 2; var name = IdGenerator.FromGuid(); var contentType = "application/octet-stream"; var source = GenerateData(UploadObjectOptions.MinimumChunkSize * chunks); int progressCount = 0; var progress = new Progress<IUploadProgress>(p => progressCount++); var result = await _fixture.Client.UploadObjectAsync(_fixture.MultiVersionBucket, name, contentType, source, new UploadObjectOptions { ChunkSize = UploadObjectOptions.MinimumChunkSize }, CancellationToken.None, progress); Assert.Equal(chunks + 1, progressCount); // Should start with a 0 progress Assert.Equal(name, result.Name); // Assume the rest of the properties are okay... ValidateData(_fixture.MultiVersionBucket, name, source); } [Fact] public void ReplaceObject() { var client = _fixture.Client; var bucket = _fixture.MultiVersionBucket; var name = IdGenerator.FromGuid(); var contentType = "application/octet-stream"; var source1 = GenerateData(100); var firstVersion = client.UploadObject(bucket, name, contentType, source1); ValidateData(_fixture.MultiVersionBucket, name, source1); var source2 = GenerateData(50); firstVersion.ContentType = "application/x-replaced"; // Clear hash and cache information, as we're changing the data. firstVersion.Crc32c = null; firstVersion.ETag = null; firstVersion.Md5Hash = null; var secondVersion = client.UploadObject(firstVersion, source2); ValidateData(_fixture.MultiVersionBucket, name, source2); Assert.NotEqual(firstVersion.Generation, secondVersion.Generation); Assert.Equal(firstVersion.ContentType, secondVersion.ContentType); // The modified content type should stick // When we ask for the first generation, we get the original data back. var firstGenerationData = new MemoryStream(); client.DownloadObject(firstVersion, firstGenerationData, new DownloadObjectOptions { Generation = firstVersion.Generation }, null); Assert.Equal(source1.ToArray(), firstGenerationData.ToArray()); } [Fact] public void UploadObjectIfGenerationMatch_NewFile() { var stream = GenerateData(50); var name = IdGenerator.FromGuid(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.UploadObject( _fixture.MultiVersionBucket, name, "", stream, new UploadObjectOptions { IfGenerationMatch = 100 }, null)); } [Fact] public void UploadObjectIfGenerationMatch_Matching() { var existing = GetExistingObject(); var stream = GenerateData(50); _fixture.Client.UploadObject(existing, stream, new UploadObjectOptions { IfGenerationMatch = existing.Generation }, null); } [Fact] public void UploadObjectIfGenerationMatch_NotMatching() { var existing = GetExistingObject(); var stream = GenerateData(50); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.UploadObject(existing, stream, new UploadObjectOptions { IfGenerationMatch = existing.Generation + 1 }, null)); Assert.Equal(HttpStatusCode.PreconditionFailed, exception.HttpStatusCode); } [Fact] public void UploadObjectIfGenerationNotMatch_Matching() { var existing = GetExistingObject(); var stream = GenerateData(50); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.UploadObject(existing, stream, new UploadObjectOptions { IfGenerationNotMatch = existing.Generation }, null)); Assert.Equal(HttpStatusCode.NotModified, exception.HttpStatusCode); } [Fact] public void UploadObjectIfGenerationNotMatch_NotMatching() { var existing = GetExistingObject(); var stream = GenerateData(50); _fixture.Client.UploadObject(existing, stream, new UploadObjectOptions { IfGenerationNotMatch = existing.Generation + 1 }, null); } [Fact] public void UploadObject_IfGenerationMatchAndNotMatch() { Assert.Throws<ArgumentException>(() => _fixture.Client.UploadObject(_fixture.MultiVersionBucket, IdGenerator.FromGuid(), "", new MemoryStream(), new UploadObjectOptions { IfGenerationMatch = 1, IfGenerationNotMatch = 2 }, null)); } [Fact] public void UploadObjectIfMetagenerationMatch_Matching() { var existing = GetExistingObject(); var stream = GenerateData(50); _fixture.Client.UploadObject(existing, stream, new UploadObjectOptions { IfMetagenerationMatch = existing.Metageneration }, null); } [Fact] public void UploadObjectIfMetagenerationMatch_NotMatching() { var existing = GetExistingObject(); var stream = GenerateData(50); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.UploadObject(existing, stream, new UploadObjectOptions { IfMetagenerationMatch = existing.Metageneration + 1 }, null)); Assert.Equal(HttpStatusCode.PreconditionFailed, exception.HttpStatusCode); } [Fact] public void UploadObjectIfMetagenerationNotMatch_Matching() { var existing = GetExistingObject(); var stream = GenerateData(50); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.UploadObject(existing, stream, new UploadObjectOptions { IfMetagenerationNotMatch = existing.Metageneration }, null)); Assert.Equal(HttpStatusCode.NotModified, exception.HttpStatusCode); } [Fact] public void UploadObjectIfMetagenerationNotMatch_NotMatching() { var existing = GetExistingObject(); var stream = GenerateData(50); _fixture.Client.UploadObject(existing, stream, new UploadObjectOptions { IfMetagenerationNotMatch = existing.Metageneration + 1 }, null); } [Fact] public void UploadObject_IfMetagenerationMatchAndNotMatch() { Assert.Throws<ArgumentException>(() => _fixture.Client.UploadObject(_fixture.MultiVersionBucket, IdGenerator.FromGuid(), "", new MemoryStream(), new UploadObjectOptions { IfMetagenerationMatch = 1, IfMetagenerationNotMatch = 2 }, null)); } [Fact] public void UploadObject_NullContentType() { _fixture.Client.UploadObject(_fixture.MultiVersionBucket, IdGenerator.FromGuid(), null, new MemoryStream()); } [Fact] public void UploadObject_InvalidHash_None() { var client = StorageClient.Create(); var interceptor = new BreakUploadInterceptor(); client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor); var stream = GenerateData(50); var name = IdGenerator.FromGuid(); var bucket = _fixture.MultiVersionBucket; var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.None }; // Upload succeeds despite the data being broken. client.UploadObject(bucket, name, null, stream, options); // The object should contain our "wrong" bytes. ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes)); } [Fact] public void UploadObject_InvalidHash_ThrowOnly() { var client = StorageClient.Create(); var interceptor = new BreakUploadInterceptor(); client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor); var stream = GenerateData(50); var name = IdGenerator.FromGuid(); var bucket = _fixture.MultiVersionBucket; var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.ThrowOnly }; Assert.Throws<UploadValidationException>(() => client.UploadObject(bucket, name, null, stream, options)); // We don't delete the object, so it's still present. ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes)); } [Fact] public void UploadObject_InvalidHash_DeleteAndThrow() { var client = StorageClient.Create(); var interceptor = new BreakUploadInterceptor(); client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor); var stream = GenerateData(50); var name = IdGenerator.FromGuid(); var bucket = _fixture.MultiVersionBucket; var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.DeleteAndThrow }; Assert.Throws<UploadValidationException>(() => client.UploadObject(bucket, name, null, stream, options)); var notFound = Assert.Throws<GoogleApiException>(() => _fixture.Client.GetObject(bucket, name)); Assert.Equal(HttpStatusCode.NotFound, notFound.HttpStatusCode); } [Fact] public void UploadObject_InvalidHash_DeleteAndThrow_DeleteFails() { var client = StorageClient.Create(); var interceptor = new BreakUploadInterceptor(); client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor); client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(new BreakDeleteInterceptor()); var stream = GenerateData(50); var name = IdGenerator.FromGuid(); var bucket = _fixture.MultiVersionBucket; var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.DeleteAndThrow }; var ex = Assert.Throws<UploadValidationException>(() => client.UploadObject(bucket, name, null, stream, options)); Assert.NotNull(ex.AdditionalFailures); // The deletion failed, so the uploaded object still exists. ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes)); } [Fact] public async Task UploadObjectAsync_InvalidHash_None() { var client = StorageClient.Create(); var interceptor = new BreakUploadInterceptor(); client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor); var stream = GenerateData(50); var name = IdGenerator.FromGuid(); var bucket = _fixture.MultiVersionBucket; var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.None }; // Upload succeeds despite the data being broken. await client.UploadObjectAsync(bucket, name, null, stream, options); // The object should contain our "wrong" bytes. ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes)); } [Fact] public async Task UploadObjectAsync_InvalidHash_ThrowOnly() { var client = StorageClient.Create(); var interceptor = new BreakUploadInterceptor(); client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor); var stream = GenerateData(50); var name = IdGenerator.FromGuid(); var bucket = _fixture.MultiVersionBucket; var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.ThrowOnly }; await Assert.ThrowsAsync<UploadValidationException>(() => client.UploadObjectAsync(bucket, name, null, stream, options)); // We don't delete the object, so it's still present. ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes)); } [Fact] public async Task UploadObjectAsync_InvalidHash_DeleteAndThrow() { var client = StorageClient.Create(); var interceptor = new BreakUploadInterceptor(); client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor); var stream = GenerateData(50); var name = IdGenerator.FromGuid(); var bucket = _fixture.MultiVersionBucket; var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.DeleteAndThrow }; await Assert.ThrowsAsync<UploadValidationException>(() => client.UploadObjectAsync(bucket, name, null, stream, options)); var notFound = await Assert.ThrowsAsync<GoogleApiException>(() => _fixture.Client.GetObjectAsync(bucket, name)); Assert.Equal(HttpStatusCode.NotFound, notFound.HttpStatusCode); } [Fact] public async Task UploadObjectAsync_InvalidHash_DeleteAndThrow_DeleteFails() { var client = StorageClient.Create(); var interceptor = new BreakUploadInterceptor(); client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor); client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(new BreakDeleteInterceptor()); var stream = GenerateData(50); var name = IdGenerator.FromGuid(); var bucket = _fixture.MultiVersionBucket; var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.DeleteAndThrow }; var ex = await Assert.ThrowsAsync<UploadValidationException>(() => client.UploadObjectAsync(bucket, name, null, stream, options)); Assert.NotNull(ex.AdditionalFailures); // The deletion failed, so the uploaded object still exists. ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes)); } private class BreakUploadInterceptor : IHttpExecuteInterceptor { internal byte[] UploadedBytes { get; set; } public async Task InterceptAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // We only care about Put requests, as that's what upload uses. if (request.Method != HttpMethod.Put) { return; } var originalContent = request.Content; var bytes = await originalContent.ReadAsByteArrayAsync().ConfigureAwait(false); // Unlikely, but if we get an empty request, just leave it alone. if (bytes.Length == 0) { return; } bytes[0]++; request.Content = new ByteArrayContent(bytes); UploadedBytes = bytes; foreach (var header in originalContent.Headers) { request.Content.Headers.Add(header.Key, header.Value); } } } private class BreakDeleteInterceptor : IHttpExecuteInterceptor { public Task InterceptAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // We only care about Delete requests if (request.Method == HttpMethod.Delete) { // Ugly but effective hack: replace the generation URL parameter so that we add a leading 9, // so the generation we try to delete is the wrong one. request.RequestUri = new Uri(request.RequestUri.ToString().Replace("generation=", "generation=9")); } return Task.FromResult(0); } } private Object GetExistingObject() { var obj = _fixture.Client.UploadObject(_fixture.MultiVersionBucket, IdGenerator.FromGuid(), "application/octet-stream", GenerateData(100)); // Clear hash and cache information, ready for a new version. obj.Crc32c = null; obj.ETag = null; obj.Md5Hash = null; return obj; } } }
using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography.ECC; using Neo.IO.Json; using Neo.SmartContract; using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace Neo.UnitTests.SmartContract { [TestClass] public class UT_ContractParameter { [TestMethod] public void TestGenerator1() { ContractParameter contractParameter = new(); Assert.IsNotNull(contractParameter); } [TestMethod] public void TestGenerator2() { ContractParameter contractParameter1 = new(ContractParameterType.Signature); byte[] expectedArray1 = new byte[64]; Assert.IsNotNull(contractParameter1); Assert.AreEqual(Encoding.Default.GetString(expectedArray1), Encoding.Default.GetString((byte[])contractParameter1.Value)); ContractParameter contractParameter2 = new(ContractParameterType.Boolean); Assert.IsNotNull(contractParameter2); Assert.AreEqual(false, contractParameter2.Value); ContractParameter contractParameter3 = new(ContractParameterType.Integer); Assert.IsNotNull(contractParameter3); Assert.AreEqual(0, contractParameter3.Value); ContractParameter contractParameter4 = new(ContractParameterType.Hash160); Assert.IsNotNull(contractParameter4); Assert.AreEqual(new UInt160(), contractParameter4.Value); ContractParameter contractParameter5 = new(ContractParameterType.Hash256); Assert.IsNotNull(contractParameter5); Assert.AreEqual(new UInt256(), contractParameter5.Value); ContractParameter contractParameter6 = new(ContractParameterType.ByteArray); byte[] expectedArray6 = Array.Empty<byte>(); Assert.IsNotNull(contractParameter6); Assert.AreEqual(Encoding.Default.GetString(expectedArray6), Encoding.Default.GetString((byte[])contractParameter6.Value)); ContractParameter contractParameter7 = new(ContractParameterType.PublicKey); Assert.IsNotNull(contractParameter7); Assert.AreEqual(ECCurve.Secp256r1.G, contractParameter7.Value); ContractParameter contractParameter8 = new(ContractParameterType.String); Assert.IsNotNull(contractParameter8); Assert.AreEqual("", contractParameter8.Value); ContractParameter contractParameter9 = new(ContractParameterType.Array); Assert.IsNotNull(contractParameter9); Assert.AreEqual(0, ((List<ContractParameter>)contractParameter9.Value).Count); ContractParameter contractParameter10 = new(ContractParameterType.Map); Assert.IsNotNull(contractParameter10); Assert.AreEqual(0, ((List<KeyValuePair<ContractParameter, ContractParameter>>)contractParameter10.Value).Count); Action action = () => new ContractParameter(ContractParameterType.Void); action.Should().Throw<ArgumentException>(); } [TestMethod] public void TestFromAndToJson() { ContractParameter contractParameter1 = new(ContractParameterType.Signature); JObject jobject1 = contractParameter1.ToJson(); Assert.AreEqual(jobject1.ToString(), ContractParameter.FromJson(jobject1).ToJson().ToString()); ContractParameter contractParameter2 = new(ContractParameterType.Boolean); JObject jobject2 = contractParameter2.ToJson(); Assert.AreEqual(jobject2.ToString(), ContractParameter.FromJson(jobject2).ToJson().ToString()); ContractParameter contractParameter3 = new(ContractParameterType.Integer); JObject jobject3 = contractParameter3.ToJson(); Assert.AreEqual(jobject3.ToString(), ContractParameter.FromJson(jobject3).ToJson().ToString()); ContractParameter contractParameter4 = new(ContractParameterType.Hash160); JObject jobject4 = contractParameter4.ToJson(); Assert.AreEqual(jobject4.ToString(), ContractParameter.FromJson(jobject4).ToJson().ToString()); ContractParameter contractParameter5 = new(ContractParameterType.Hash256); JObject jobject5 = contractParameter5.ToJson(); Assert.AreEqual(jobject5.ToString(), ContractParameter.FromJson(jobject5).ToJson().ToString()); ContractParameter contractParameter6 = new(ContractParameterType.ByteArray); JObject jobject6 = contractParameter6.ToJson(); Assert.AreEqual(jobject6.ToString(), ContractParameter.FromJson(jobject6).ToJson().ToString()); ContractParameter contractParameter7 = new(ContractParameterType.PublicKey); JObject jobject7 = contractParameter7.ToJson(); Assert.AreEqual(jobject7.ToString(), ContractParameter.FromJson(jobject7).ToJson().ToString()); ContractParameter contractParameter8 = new(ContractParameterType.String); JObject jobject8 = contractParameter8.ToJson(); Assert.AreEqual(jobject8.ToString(), ContractParameter.FromJson(jobject8).ToJson().ToString()); ContractParameter contractParameter9 = new(ContractParameterType.Array); JObject jobject9 = contractParameter9.ToJson(); Assert.AreEqual(jobject9.ToString(), ContractParameter.FromJson(jobject9).ToJson().ToString()); ContractParameter contractParameter10 = new(ContractParameterType.Map); JObject jobject10 = contractParameter10.ToJson(); Assert.AreEqual(jobject10.ToString(), ContractParameter.FromJson(jobject10).ToJson().ToString()); ContractParameter contractParameter11 = new(ContractParameterType.String); JObject jobject11 = contractParameter11.ToJson(); jobject11["type"] = "Void"; Action action = () => ContractParameter.FromJson(jobject11); action.Should().Throw<ArgumentException>(); } [TestMethod] public void TestSetValue() { ContractParameter contractParameter1 = new(ContractParameterType.Signature); byte[] expectedArray1 = new byte[64]; contractParameter1.SetValue(new byte[64].ToHexString()); Assert.AreEqual(Encoding.Default.GetString(expectedArray1), Encoding.Default.GetString((byte[])contractParameter1.Value)); Action action1 = () => contractParameter1.SetValue(new byte[50].ToHexString()); action1.Should().Throw<FormatException>(); ContractParameter contractParameter2 = new(ContractParameterType.Boolean); contractParameter2.SetValue("true"); Assert.AreEqual(true, contractParameter2.Value); ContractParameter contractParameter3 = new(ContractParameterType.Integer); contractParameter3.SetValue("11"); Assert.AreEqual(new BigInteger(11), contractParameter3.Value); ContractParameter contractParameter4 = new(ContractParameterType.Hash160); contractParameter4.SetValue("0x0000000000000000000000000000000000000001"); Assert.AreEqual(UInt160.Parse("0x0000000000000000000000000000000000000001"), contractParameter4.Value); ContractParameter contractParameter5 = new(ContractParameterType.Hash256); contractParameter5.SetValue("0x0000000000000000000000000000000000000000000000000000000000000000"); Assert.AreEqual(UInt256.Parse("0x0000000000000000000000000000000000000000000000000000000000000000"), contractParameter5.Value); ContractParameter contractParameter6 = new(ContractParameterType.ByteArray); contractParameter6.SetValue("2222"); byte[] expectedArray6 = new byte[2]; expectedArray6[0] = 0x22; expectedArray6[1] = 0x22; Assert.AreEqual(Encoding.Default.GetString(expectedArray6), Encoding.Default.GetString((byte[])contractParameter6.Value)); ContractParameter contractParameter7 = new(ContractParameterType.PublicKey); Random random7 = new(); byte[] privateKey7 = new byte[32]; for (int j = 0; j < privateKey7.Length; j++) privateKey7[j] = (byte)random7.Next(256); ECPoint publicKey7 = ECCurve.Secp256r1.G * privateKey7; contractParameter7.SetValue(publicKey7.ToString()); Assert.AreEqual(true, publicKey7.Equals(contractParameter7.Value)); ContractParameter contractParameter8 = new(ContractParameterType.String); contractParameter8.SetValue("AAA"); Assert.AreEqual("AAA", contractParameter8.Value); ContractParameter contractParameter9 = new(ContractParameterType.Array); Action action9 = () => contractParameter9.SetValue("AAA"); action9.Should().Throw<ArgumentException>(); } [TestMethod] public void TestToString() { ContractParameter contractParameter1 = new(); Assert.AreEqual("(null)", contractParameter1.ToString()); ContractParameter contractParameter2 = new(ContractParameterType.ByteArray); contractParameter2.Value = new byte[1]; Assert.AreEqual("00", contractParameter2.ToString()); ContractParameter contractParameter3 = new(ContractParameterType.Array); Assert.AreEqual("[]", contractParameter3.ToString()); ContractParameter internalContractParameter3 = new(ContractParameterType.Boolean); ((IList<ContractParameter>)contractParameter3.Value).Add(internalContractParameter3); Assert.AreEqual("[False]", contractParameter3.ToString()); ContractParameter contractParameter4 = new(ContractParameterType.Map); Assert.AreEqual("[]", contractParameter4.ToString()); ContractParameter internalContractParameter4 = new(ContractParameterType.Boolean); ((IList<KeyValuePair<ContractParameter, ContractParameter>>)contractParameter4.Value).Add(new KeyValuePair<ContractParameter, ContractParameter>( internalContractParameter4, internalContractParameter4 )); Assert.AreEqual("[{False,False}]", contractParameter4.ToString()); ContractParameter contractParameter5 = new(ContractParameterType.String); Assert.AreEqual("", contractParameter5.ToString()); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: unittest_issues.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace UnitTest.Issues.TestProtos { /// <summary>Holder for reflection information generated from unittest_issues.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class UnittestIssuesReflection { #region Descriptor /// <summary>File descriptor for unittest_issues.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static UnittestIssuesReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChV1bml0dGVzdF9pc3N1ZXMucHJvdG8SD3VuaXR0ZXN0X2lzc3VlcyInCghJ", "c3N1ZTMwNxobCgpOZXN0ZWRPbmNlGg0KC05lc3RlZFR3aWNlIrABChNOZWdh", "dGl2ZUVudW1NZXNzYWdlEiwKBXZhbHVlGAEgASgOMh0udW5pdHRlc3RfaXNz", "dWVzLk5lZ2F0aXZlRW51bRIxCgZ2YWx1ZXMYAiADKA4yHS51bml0dGVzdF9p", "c3N1ZXMuTmVnYXRpdmVFbnVtQgIQABI4Cg1wYWNrZWRfdmFsdWVzGAMgAygO", "Mh0udW5pdHRlc3RfaXNzdWVzLk5lZ2F0aXZlRW51bUICEAEiEQoPRGVwcmVj", "YXRlZENoaWxkIrkCChdEZXByZWNhdGVkRmllbGRzTWVzc2FnZRIaCg5Qcmlt", "aXRpdmVWYWx1ZRgBIAEoBUICGAESGgoOUHJpbWl0aXZlQXJyYXkYAiADKAVC", "AhgBEjoKDE1lc3NhZ2VWYWx1ZRgDIAEoCzIgLnVuaXR0ZXN0X2lzc3Vlcy5E", "ZXByZWNhdGVkQ2hpbGRCAhgBEjoKDE1lc3NhZ2VBcnJheRgEIAMoCzIgLnVu", "aXR0ZXN0X2lzc3Vlcy5EZXByZWNhdGVkQ2hpbGRCAhgBEjYKCUVudW1WYWx1", "ZRgFIAEoDjIfLnVuaXR0ZXN0X2lzc3Vlcy5EZXByZWNhdGVkRW51bUICGAES", "NgoJRW51bUFycmF5GAYgAygOMh8udW5pdHRlc3RfaXNzdWVzLkRlcHJlY2F0", "ZWRFbnVtQgIYASIZCglJdGVtRmllbGQSDAoEaXRlbRgBIAEoBSJECg1SZXNl", "cnZlZE5hbWVzEg0KBXR5cGVzGAEgASgFEhIKCmRlc2NyaXB0b3IYAiABKAUa", "EAoOU29tZU5lc3RlZFR5cGUioAEKFVRlc3RKc29uRmllbGRPcmRlcmluZxIT", "CgtwbGFpbl9pbnQzMhgEIAEoBRITCglvMV9zdHJpbmcYAiABKAlIABISCghv", "MV9pbnQzMhgFIAEoBUgAEhQKDHBsYWluX3N0cmluZxgBIAEoCRISCghvMl9p", "bnQzMhgGIAEoBUgBEhMKCW8yX3N0cmluZxgDIAEoCUgBQgQKAm8xQgQKAm8y", "IksKDFRlc3RKc29uTmFtZRIMCgRuYW1lGAEgASgJEhkKC2Rlc2NyaXB0aW9u", "GAIgASgJUgRkZXNjEhIKBGd1aWQYAyABKAlSBGV4aWQqVQoMTmVnYXRpdmVF", "bnVtEhYKEk5FR0FUSVZFX0VOVU1fWkVSTxAAEhYKCUZpdmVCZWxvdxD7////", "//////8BEhUKCE1pbnVzT25lEP///////////wEqLgoORGVwcmVjYXRlZEVu", "dW0SEwoPREVQUkVDQVRFRF9aRVJPEAASBwoDb25lEAFCH0gBqgIaVW5pdFRl", "c3QuSXNzdWVzLlRlc3RQcm90b3NiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::UnitTest.Issues.TestProtos.NegativeEnum), typeof(global::UnitTest.Issues.TestProtos.DeprecatedEnum), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307), global::UnitTest.Issues.TestProtos.Issue307.Parser, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce), global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Parser, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Types.NestedTwice), global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Types.NestedTwice.Parser, null, null, null, null)})}), new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.NegativeEnumMessage), global::UnitTest.Issues.TestProtos.NegativeEnumMessage.Parser, new[]{ "Value", "Values", "PackedValues" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.DeprecatedChild), global::UnitTest.Issues.TestProtos.DeprecatedChild.Parser, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.DeprecatedFieldsMessage), global::UnitTest.Issues.TestProtos.DeprecatedFieldsMessage.Parser, new[]{ "PrimitiveValue", "PrimitiveArray", "MessageValue", "MessageArray", "EnumValue", "EnumArray" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ItemField), global::UnitTest.Issues.TestProtos.ItemField.Parser, new[]{ "Item" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames), global::UnitTest.Issues.TestProtos.ReservedNames.Parser, new[]{ "Types_", "Descriptor_" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames.Types.SomeNestedType), global::UnitTest.Issues.TestProtos.ReservedNames.Types.SomeNestedType.Parser, null, null, null, null)}), new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.TestJsonFieldOrdering), global::UnitTest.Issues.TestProtos.TestJsonFieldOrdering.Parser, new[]{ "PlainInt32", "O1String", "O1Int32", "PlainString", "O2Int32", "O2String" }, new[]{ "O1", "O2" }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.TestJsonName), global::UnitTest.Issues.TestProtos.TestJsonName.Parser, new[]{ "Name", "Description", "Guid" }, null, null, null) })); } #endregion } #region Enums public enum NegativeEnum { [pbr::OriginalName("NEGATIVE_ENUM_ZERO")] Zero = 0, [pbr::OriginalName("FiveBelow")] FiveBelow = -5, [pbr::OriginalName("MinusOne")] MinusOne = -1, } public enum DeprecatedEnum { [pbr::OriginalName("DEPRECATED_ZERO")] DeprecatedZero = 0, [pbr::OriginalName("one")] One = 1, } #endregion #region Messages /// <summary> /// Issue 307: when generating doubly-nested types, any references /// should be of the form A.Types.B.Types.C. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Issue307 : pb::IMessage<Issue307> { private static readonly pb::MessageParser<Issue307> _parser = new pb::MessageParser<Issue307>(() => new Issue307()); public static pb::MessageParser<Issue307> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Issue307() { OnConstruction(); } partial void OnConstruction(); public Issue307(Issue307 other) : this() { } public Issue307 Clone() { return new Issue307(this); } public override bool Equals(object other) { return Equals(other as Issue307); } public bool Equals(Issue307 other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return true; } public override int GetHashCode() { int hash = 1; return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { int size = 0; return size; } public void MergeFrom(Issue307 other) { if (other == null) { return; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; } } } #region Nested types /// <summary>Container for nested types declared in the Issue307 message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class NestedOnce : pb::IMessage<NestedOnce> { private static readonly pb::MessageParser<NestedOnce> _parser = new pb::MessageParser<NestedOnce>(() => new NestedOnce()); public static pb::MessageParser<NestedOnce> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.Issue307.Descriptor.NestedTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public NestedOnce() { OnConstruction(); } partial void OnConstruction(); public NestedOnce(NestedOnce other) : this() { } public NestedOnce Clone() { return new NestedOnce(this); } public override bool Equals(object other) { return Equals(other as NestedOnce); } public bool Equals(NestedOnce other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return true; } public override int GetHashCode() { int hash = 1; return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { int size = 0; return size; } public void MergeFrom(NestedOnce other) { if (other == null) { return; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; } } } #region Nested types /// <summary>Container for nested types declared in the NestedOnce message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class NestedTwice : pb::IMessage<NestedTwice> { private static readonly pb::MessageParser<NestedTwice> _parser = new pb::MessageParser<NestedTwice>(() => new NestedTwice()); public static pb::MessageParser<NestedTwice> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Descriptor.NestedTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public NestedTwice() { OnConstruction(); } partial void OnConstruction(); public NestedTwice(NestedTwice other) : this() { } public NestedTwice Clone() { return new NestedTwice(this); } public override bool Equals(object other) { return Equals(other as NestedTwice); } public bool Equals(NestedTwice other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return true; } public override int GetHashCode() { int hash = 1; return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { int size = 0; return size; } public void MergeFrom(NestedTwice other) { if (other == null) { return; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; } } } } } #endregion } } #endregion } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class NegativeEnumMessage : pb::IMessage<NegativeEnumMessage> { private static readonly pb::MessageParser<NegativeEnumMessage> _parser = new pb::MessageParser<NegativeEnumMessage>(() => new NegativeEnumMessage()); public static pb::MessageParser<NegativeEnumMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public NegativeEnumMessage() { OnConstruction(); } partial void OnConstruction(); public NegativeEnumMessage(NegativeEnumMessage other) : this() { value_ = other.value_; values_ = other.values_.Clone(); packedValues_ = other.packedValues_.Clone(); } public NegativeEnumMessage Clone() { return new NegativeEnumMessage(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private global::UnitTest.Issues.TestProtos.NegativeEnum value_ = 0; public global::UnitTest.Issues.TestProtos.NegativeEnum Value { get { return value_; } set { value_ = value; } } /// <summary>Field number for the "values" field.</summary> public const int ValuesFieldNumber = 2; private static readonly pb::FieldCodec<global::UnitTest.Issues.TestProtos.NegativeEnum> _repeated_values_codec = pb::FieldCodec.ForEnum(16, x => (int) x, x => (global::UnitTest.Issues.TestProtos.NegativeEnum) x); private readonly pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum> values_ = new pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum>(); public pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum> Values { get { return values_; } } /// <summary>Field number for the "packed_values" field.</summary> public const int PackedValuesFieldNumber = 3; private static readonly pb::FieldCodec<global::UnitTest.Issues.TestProtos.NegativeEnum> _repeated_packedValues_codec = pb::FieldCodec.ForEnum(26, x => (int) x, x => (global::UnitTest.Issues.TestProtos.NegativeEnum) x); private readonly pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum> packedValues_ = new pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum>(); public pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum> PackedValues { get { return packedValues_; } } public override bool Equals(object other) { return Equals(other as NegativeEnumMessage); } public bool Equals(NegativeEnumMessage other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; if(!values_.Equals(other.values_)) return false; if(!packedValues_.Equals(other.packedValues_)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Value != 0) hash ^= Value.GetHashCode(); hash ^= values_.GetHashCode(); hash ^= packedValues_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Value != 0) { output.WriteRawTag(8); output.WriteEnum((int) Value); } values_.WriteTo(output, _repeated_values_codec); packedValues_.WriteTo(output, _repeated_packedValues_codec); } public int CalculateSize() { int size = 0; if (Value != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Value); } size += values_.CalculateSize(_repeated_values_codec); size += packedValues_.CalculateSize(_repeated_packedValues_codec); return size; } public void MergeFrom(NegativeEnumMessage other) { if (other == null) { return; } if (other.Value != 0) { Value = other.Value; } values_.Add(other.values_); packedValues_.Add(other.packedValues_); } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { value_ = (global::UnitTest.Issues.TestProtos.NegativeEnum) input.ReadEnum(); break; } case 18: case 16: { values_.AddEntriesFrom(input, _repeated_values_codec); break; } case 26: case 24: { packedValues_.AddEntriesFrom(input, _repeated_packedValues_codec); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class DeprecatedChild : pb::IMessage<DeprecatedChild> { private static readonly pb::MessageParser<DeprecatedChild> _parser = new pb::MessageParser<DeprecatedChild>(() => new DeprecatedChild()); public static pb::MessageParser<DeprecatedChild> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public DeprecatedChild() { OnConstruction(); } partial void OnConstruction(); public DeprecatedChild(DeprecatedChild other) : this() { } public DeprecatedChild Clone() { return new DeprecatedChild(this); } public override bool Equals(object other) { return Equals(other as DeprecatedChild); } public bool Equals(DeprecatedChild other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return true; } public override int GetHashCode() { int hash = 1; return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { int size = 0; return size; } public void MergeFrom(DeprecatedChild other) { if (other == null) { return; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class DeprecatedFieldsMessage : pb::IMessage<DeprecatedFieldsMessage> { private static readonly pb::MessageParser<DeprecatedFieldsMessage> _parser = new pb::MessageParser<DeprecatedFieldsMessage>(() => new DeprecatedFieldsMessage()); public static pb::MessageParser<DeprecatedFieldsMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public DeprecatedFieldsMessage() { OnConstruction(); } partial void OnConstruction(); public DeprecatedFieldsMessage(DeprecatedFieldsMessage other) : this() { primitiveValue_ = other.primitiveValue_; primitiveArray_ = other.primitiveArray_.Clone(); MessageValue = other.messageValue_ != null ? other.MessageValue.Clone() : null; messageArray_ = other.messageArray_.Clone(); enumValue_ = other.enumValue_; enumArray_ = other.enumArray_.Clone(); } public DeprecatedFieldsMessage Clone() { return new DeprecatedFieldsMessage(this); } /// <summary>Field number for the "PrimitiveValue" field.</summary> public const int PrimitiveValueFieldNumber = 1; private int primitiveValue_; [global::System.ObsoleteAttribute()] public int PrimitiveValue { get { return primitiveValue_; } set { primitiveValue_ = value; } } /// <summary>Field number for the "PrimitiveArray" field.</summary> public const int PrimitiveArrayFieldNumber = 2; private static readonly pb::FieldCodec<int> _repeated_primitiveArray_codec = pb::FieldCodec.ForInt32(18); private readonly pbc::RepeatedField<int> primitiveArray_ = new pbc::RepeatedField<int>(); [global::System.ObsoleteAttribute()] public pbc::RepeatedField<int> PrimitiveArray { get { return primitiveArray_; } } /// <summary>Field number for the "MessageValue" field.</summary> public const int MessageValueFieldNumber = 3; private global::UnitTest.Issues.TestProtos.DeprecatedChild messageValue_; [global::System.ObsoleteAttribute()] public global::UnitTest.Issues.TestProtos.DeprecatedChild MessageValue { get { return messageValue_; } set { messageValue_ = value; } } /// <summary>Field number for the "MessageArray" field.</summary> public const int MessageArrayFieldNumber = 4; private static readonly pb::FieldCodec<global::UnitTest.Issues.TestProtos.DeprecatedChild> _repeated_messageArray_codec = pb::FieldCodec.ForMessage(34, global::UnitTest.Issues.TestProtos.DeprecatedChild.Parser); private readonly pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedChild> messageArray_ = new pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedChild>(); [global::System.ObsoleteAttribute()] public pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedChild> MessageArray { get { return messageArray_; } } /// <summary>Field number for the "EnumValue" field.</summary> public const int EnumValueFieldNumber = 5; private global::UnitTest.Issues.TestProtos.DeprecatedEnum enumValue_ = 0; [global::System.ObsoleteAttribute()] public global::UnitTest.Issues.TestProtos.DeprecatedEnum EnumValue { get { return enumValue_; } set { enumValue_ = value; } } /// <summary>Field number for the "EnumArray" field.</summary> public const int EnumArrayFieldNumber = 6; private static readonly pb::FieldCodec<global::UnitTest.Issues.TestProtos.DeprecatedEnum> _repeated_enumArray_codec = pb::FieldCodec.ForEnum(50, x => (int) x, x => (global::UnitTest.Issues.TestProtos.DeprecatedEnum) x); private readonly pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedEnum> enumArray_ = new pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedEnum>(); [global::System.ObsoleteAttribute()] public pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedEnum> EnumArray { get { return enumArray_; } } public override bool Equals(object other) { return Equals(other as DeprecatedFieldsMessage); } public bool Equals(DeprecatedFieldsMessage other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (PrimitiveValue != other.PrimitiveValue) return false; if(!primitiveArray_.Equals(other.primitiveArray_)) return false; if (!object.Equals(MessageValue, other.MessageValue)) return false; if(!messageArray_.Equals(other.messageArray_)) return false; if (EnumValue != other.EnumValue) return false; if(!enumArray_.Equals(other.enumArray_)) return false; return true; } public override int GetHashCode() { int hash = 1; if (PrimitiveValue != 0) hash ^= PrimitiveValue.GetHashCode(); hash ^= primitiveArray_.GetHashCode(); if (messageValue_ != null) hash ^= MessageValue.GetHashCode(); hash ^= messageArray_.GetHashCode(); if (EnumValue != 0) hash ^= EnumValue.GetHashCode(); hash ^= enumArray_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (PrimitiveValue != 0) { output.WriteRawTag(8); output.WriteInt32(PrimitiveValue); } primitiveArray_.WriteTo(output, _repeated_primitiveArray_codec); if (messageValue_ != null) { output.WriteRawTag(26); output.WriteMessage(MessageValue); } messageArray_.WriteTo(output, _repeated_messageArray_codec); if (EnumValue != 0) { output.WriteRawTag(40); output.WriteEnum((int) EnumValue); } enumArray_.WriteTo(output, _repeated_enumArray_codec); } public int CalculateSize() { int size = 0; if (PrimitiveValue != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(PrimitiveValue); } size += primitiveArray_.CalculateSize(_repeated_primitiveArray_codec); if (messageValue_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(MessageValue); } size += messageArray_.CalculateSize(_repeated_messageArray_codec); if (EnumValue != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) EnumValue); } size += enumArray_.CalculateSize(_repeated_enumArray_codec); return size; } public void MergeFrom(DeprecatedFieldsMessage other) { if (other == null) { return; } if (other.PrimitiveValue != 0) { PrimitiveValue = other.PrimitiveValue; } primitiveArray_.Add(other.primitiveArray_); if (other.messageValue_ != null) { if (messageValue_ == null) { messageValue_ = new global::UnitTest.Issues.TestProtos.DeprecatedChild(); } MessageValue.MergeFrom(other.MessageValue); } messageArray_.Add(other.messageArray_); if (other.EnumValue != 0) { EnumValue = other.EnumValue; } enumArray_.Add(other.enumArray_); } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { PrimitiveValue = input.ReadInt32(); break; } case 18: case 16: { primitiveArray_.AddEntriesFrom(input, _repeated_primitiveArray_codec); break; } case 26: { if (messageValue_ == null) { messageValue_ = new global::UnitTest.Issues.TestProtos.DeprecatedChild(); } input.ReadMessage(messageValue_); break; } case 34: { messageArray_.AddEntriesFrom(input, _repeated_messageArray_codec); break; } case 40: { enumValue_ = (global::UnitTest.Issues.TestProtos.DeprecatedEnum) input.ReadEnum(); break; } case 50: case 48: { enumArray_.AddEntriesFrom(input, _repeated_enumArray_codec); break; } } } } } /// <summary> /// Issue 45: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=45 /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ItemField : pb::IMessage<ItemField> { private static readonly pb::MessageParser<ItemField> _parser = new pb::MessageParser<ItemField>(() => new ItemField()); public static pb::MessageParser<ItemField> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[4]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public ItemField() { OnConstruction(); } partial void OnConstruction(); public ItemField(ItemField other) : this() { item_ = other.item_; } public ItemField Clone() { return new ItemField(this); } /// <summary>Field number for the "item" field.</summary> public const int ItemFieldNumber = 1; private int item_; public int Item { get { return item_; } set { item_ = value; } } public override bool Equals(object other) { return Equals(other as ItemField); } public bool Equals(ItemField other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Item != other.Item) return false; return true; } public override int GetHashCode() { int hash = 1; if (Item != 0) hash ^= Item.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Item != 0) { output.WriteRawTag(8); output.WriteInt32(Item); } } public int CalculateSize() { int size = 0; if (Item != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Item); } return size; } public void MergeFrom(ItemField other) { if (other == null) { return; } if (other.Item != 0) { Item = other.Item; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Item = input.ReadInt32(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ReservedNames : pb::IMessage<ReservedNames> { private static readonly pb::MessageParser<ReservedNames> _parser = new pb::MessageParser<ReservedNames>(() => new ReservedNames()); public static pb::MessageParser<ReservedNames> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[5]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public ReservedNames() { OnConstruction(); } partial void OnConstruction(); public ReservedNames(ReservedNames other) : this() { types_ = other.types_; descriptor_ = other.descriptor_; } public ReservedNames Clone() { return new ReservedNames(this); } /// <summary>Field number for the "types" field.</summary> public const int Types_FieldNumber = 1; private int types_; public int Types_ { get { return types_; } set { types_ = value; } } /// <summary>Field number for the "descriptor" field.</summary> public const int Descriptor_FieldNumber = 2; private int descriptor_; public int Descriptor_ { get { return descriptor_; } set { descriptor_ = value; } } public override bool Equals(object other) { return Equals(other as ReservedNames); } public bool Equals(ReservedNames other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Types_ != other.Types_) return false; if (Descriptor_ != other.Descriptor_) return false; return true; } public override int GetHashCode() { int hash = 1; if (Types_ != 0) hash ^= Types_.GetHashCode(); if (Descriptor_ != 0) hash ^= Descriptor_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Types_ != 0) { output.WriteRawTag(8); output.WriteInt32(Types_); } if (Descriptor_ != 0) { output.WriteRawTag(16); output.WriteInt32(Descriptor_); } } public int CalculateSize() { int size = 0; if (Types_ != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Types_); } if (Descriptor_ != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Descriptor_); } return size; } public void MergeFrom(ReservedNames other) { if (other == null) { return; } if (other.Types_ != 0) { Types_ = other.Types_; } if (other.Descriptor_ != 0) { Descriptor_ = other.Descriptor_; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Types_ = input.ReadInt32(); break; } case 16: { Descriptor_ = input.ReadInt32(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the ReservedNames message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { /// <summary> /// Force a nested type called Types /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class SomeNestedType : pb::IMessage<SomeNestedType> { private static readonly pb::MessageParser<SomeNestedType> _parser = new pb::MessageParser<SomeNestedType>(() => new SomeNestedType()); public static pb::MessageParser<SomeNestedType> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.ReservedNames.Descriptor.NestedTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public SomeNestedType() { OnConstruction(); } partial void OnConstruction(); public SomeNestedType(SomeNestedType other) : this() { } public SomeNestedType Clone() { return new SomeNestedType(this); } public override bool Equals(object other) { return Equals(other as SomeNestedType); } public bool Equals(SomeNestedType other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return true; } public override int GetHashCode() { int hash = 1; return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { int size = 0; return size; } public void MergeFrom(SomeNestedType other) { if (other == null) { return; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; } } } } } #endregion } /// <summary> /// These fields are deliberately not declared in numeric /// order, and the oneof fields aren't contiguous either. /// This allows for reasonably robust tests of JSON output /// ordering. /// TestFieldOrderings in unittest_proto3.proto is similar, /// but doesn't include oneofs. /// TODO: Consider adding oneofs to TestFieldOrderings, although /// that will require fixing other tests in multiple platforms. /// Alternatively, consider just adding this to /// unittest_proto3.proto if multiple platforms want it. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class TestJsonFieldOrdering : pb::IMessage<TestJsonFieldOrdering> { private static readonly pb::MessageParser<TestJsonFieldOrdering> _parser = new pb::MessageParser<TestJsonFieldOrdering>(() => new TestJsonFieldOrdering()); public static pb::MessageParser<TestJsonFieldOrdering> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[6]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public TestJsonFieldOrdering() { OnConstruction(); } partial void OnConstruction(); public TestJsonFieldOrdering(TestJsonFieldOrdering other) : this() { plainInt32_ = other.plainInt32_; plainString_ = other.plainString_; switch (other.O1Case) { case O1OneofCase.O1String: O1String = other.O1String; break; case O1OneofCase.O1Int32: O1Int32 = other.O1Int32; break; } switch (other.O2Case) { case O2OneofCase.O2Int32: O2Int32 = other.O2Int32; break; case O2OneofCase.O2String: O2String = other.O2String; break; } } public TestJsonFieldOrdering Clone() { return new TestJsonFieldOrdering(this); } /// <summary>Field number for the "plain_int32" field.</summary> public const int PlainInt32FieldNumber = 4; private int plainInt32_; public int PlainInt32 { get { return plainInt32_; } set { plainInt32_ = value; } } /// <summary>Field number for the "o1_string" field.</summary> public const int O1StringFieldNumber = 2; public string O1String { get { return o1Case_ == O1OneofCase.O1String ? (string) o1_ : ""; } set { o1_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); o1Case_ = O1OneofCase.O1String; } } /// <summary>Field number for the "o1_int32" field.</summary> public const int O1Int32FieldNumber = 5; public int O1Int32 { get { return o1Case_ == O1OneofCase.O1Int32 ? (int) o1_ : 0; } set { o1_ = value; o1Case_ = O1OneofCase.O1Int32; } } /// <summary>Field number for the "plain_string" field.</summary> public const int PlainStringFieldNumber = 1; private string plainString_ = ""; public string PlainString { get { return plainString_; } set { plainString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "o2_int32" field.</summary> public const int O2Int32FieldNumber = 6; public int O2Int32 { get { return o2Case_ == O2OneofCase.O2Int32 ? (int) o2_ : 0; } set { o2_ = value; o2Case_ = O2OneofCase.O2Int32; } } /// <summary>Field number for the "o2_string" field.</summary> public const int O2StringFieldNumber = 3; public string O2String { get { return o2Case_ == O2OneofCase.O2String ? (string) o2_ : ""; } set { o2_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); o2Case_ = O2OneofCase.O2String; } } private object o1_; /// <summary>Enum of possible cases for the "o1" oneof.</summary> public enum O1OneofCase { None = 0, O1String = 2, O1Int32 = 5, } private O1OneofCase o1Case_ = O1OneofCase.None; public O1OneofCase O1Case { get { return o1Case_; } } public void ClearO1() { o1Case_ = O1OneofCase.None; o1_ = null; } private object o2_; /// <summary>Enum of possible cases for the "o2" oneof.</summary> public enum O2OneofCase { None = 0, O2Int32 = 6, O2String = 3, } private O2OneofCase o2Case_ = O2OneofCase.None; public O2OneofCase O2Case { get { return o2Case_; } } public void ClearO2() { o2Case_ = O2OneofCase.None; o2_ = null; } public override bool Equals(object other) { return Equals(other as TestJsonFieldOrdering); } public bool Equals(TestJsonFieldOrdering other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (PlainInt32 != other.PlainInt32) return false; if (O1String != other.O1String) return false; if (O1Int32 != other.O1Int32) return false; if (PlainString != other.PlainString) return false; if (O2Int32 != other.O2Int32) return false; if (O2String != other.O2String) return false; if (O1Case != other.O1Case) return false; if (O2Case != other.O2Case) return false; return true; } public override int GetHashCode() { int hash = 1; if (PlainInt32 != 0) hash ^= PlainInt32.GetHashCode(); if (o1Case_ == O1OneofCase.O1String) hash ^= O1String.GetHashCode(); if (o1Case_ == O1OneofCase.O1Int32) hash ^= O1Int32.GetHashCode(); if (PlainString.Length != 0) hash ^= PlainString.GetHashCode(); if (o2Case_ == O2OneofCase.O2Int32) hash ^= O2Int32.GetHashCode(); if (o2Case_ == O2OneofCase.O2String) hash ^= O2String.GetHashCode(); hash ^= (int) o1Case_; hash ^= (int) o2Case_; return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (PlainString.Length != 0) { output.WriteRawTag(10); output.WriteString(PlainString); } if (o1Case_ == O1OneofCase.O1String) { output.WriteRawTag(18); output.WriteString(O1String); } if (o2Case_ == O2OneofCase.O2String) { output.WriteRawTag(26); output.WriteString(O2String); } if (PlainInt32 != 0) { output.WriteRawTag(32); output.WriteInt32(PlainInt32); } if (o1Case_ == O1OneofCase.O1Int32) { output.WriteRawTag(40); output.WriteInt32(O1Int32); } if (o2Case_ == O2OneofCase.O2Int32) { output.WriteRawTag(48); output.WriteInt32(O2Int32); } } public int CalculateSize() { int size = 0; if (PlainInt32 != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(PlainInt32); } if (o1Case_ == O1OneofCase.O1String) { size += 1 + pb::CodedOutputStream.ComputeStringSize(O1String); } if (o1Case_ == O1OneofCase.O1Int32) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(O1Int32); } if (PlainString.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PlainString); } if (o2Case_ == O2OneofCase.O2Int32) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(O2Int32); } if (o2Case_ == O2OneofCase.O2String) { size += 1 + pb::CodedOutputStream.ComputeStringSize(O2String); } return size; } public void MergeFrom(TestJsonFieldOrdering other) { if (other == null) { return; } if (other.PlainInt32 != 0) { PlainInt32 = other.PlainInt32; } if (other.PlainString.Length != 0) { PlainString = other.PlainString; } switch (other.O1Case) { case O1OneofCase.O1String: O1String = other.O1String; break; case O1OneofCase.O1Int32: O1Int32 = other.O1Int32; break; } switch (other.O2Case) { case O2OneofCase.O2Int32: O2Int32 = other.O2Int32; break; case O2OneofCase.O2String: O2String = other.O2String; break; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { PlainString = input.ReadString(); break; } case 18: { O1String = input.ReadString(); break; } case 26: { O2String = input.ReadString(); break; } case 32: { PlainInt32 = input.ReadInt32(); break; } case 40: { O1Int32 = input.ReadInt32(); break; } case 48: { O2Int32 = input.ReadInt32(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class TestJsonName : pb::IMessage<TestJsonName> { private static readonly pb::MessageParser<TestJsonName> _parser = new pb::MessageParser<TestJsonName>(() => new TestJsonName()); public static pb::MessageParser<TestJsonName> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[7]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public TestJsonName() { OnConstruction(); } partial void OnConstruction(); public TestJsonName(TestJsonName other) : this() { name_ = other.name_; description_ = other.description_; guid_ = other.guid_; } public TestJsonName Clone() { return new TestJsonName(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Message for testing the effects for of the json_name option /// </summary> public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "description" field.</summary> public const int DescriptionFieldNumber = 2; private string description_ = ""; public string Description { get { return description_; } set { description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "guid" field.</summary> public const int GuidFieldNumber = 3; private string guid_ = ""; public string Guid { get { return guid_; } set { guid_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as TestJsonName); } public bool Equals(TestJsonName other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Description != other.Description) return false; if (Guid != other.Guid) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Description.Length != 0) hash ^= Description.GetHashCode(); if (Guid.Length != 0) hash ^= Guid.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Description.Length != 0) { output.WriteRawTag(18); output.WriteString(Description); } if (Guid.Length != 0) { output.WriteRawTag(26); output.WriteString(Guid); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Description.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); } if (Guid.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Guid); } return size; } public void MergeFrom(TestJsonName other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Description.Length != 0) { Description = other.Description; } if (other.Guid.Length != 0) { Guid = other.Guid; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { Description = input.ReadString(); break; } case 26: { Guid = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections; using System.Collections.Generic; namespace WampSharp.Core.Utilities { internal class SwapHashSet<T> : ISet<T> { private HashSet<T> mHashSet; private readonly object mLock = new object(); public SwapHashSet() { mHashSet = new HashSet<T>(); } public SwapHashSet(IEqualityComparer<T> comparer) { mHashSet = new HashSet<T>(comparer); } public SwapHashSet(IEnumerable<T> collection) { mHashSet = new HashSet<T>(collection); } public SwapHashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer) { mHashSet = new HashSet<T>(collection, comparer); } void ICollection<T>.Add(T item) { Add(item); } public void Clear() { lock (mLock) { mHashSet = new HashSet<T>(mHashSet.Comparer); } } public bool Contains(T item) { return mHashSet.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { mHashSet.CopyTo(array, arrayIndex); } public bool Remove(T item) { lock (mLock) { HashSet<T> copy = GetCopy(); bool removed = copy.Remove(item); mHashSet = copy; return removed; } } private HashSet<T> GetCopy() { return new HashSet<T>(mHashSet, mHashSet.Comparer); } public IEnumerator<T> GetEnumerator() { return mHashSet.GetEnumerator(); } public void UnionWith(IEnumerable<T> other) { lock (mLock) { HashSet<T> copy = GetCopy(); copy.UnionWith(other); mHashSet = copy; } } public void IntersectWith(IEnumerable<T> other) { lock (mHashSet) { HashSet<T> copy = GetCopy(); copy.IntersectWith(other); mHashSet = copy; } } public void ExceptWith(IEnumerable<T> other) { lock (mHashSet) { HashSet<T> copy = GetCopy(); copy.ExceptWith(other); mHashSet = copy; } } public void SymmetricExceptWith(IEnumerable<T> other) { lock (mHashSet) { HashSet<T> copy = GetCopy(); copy.SymmetricExceptWith(other); mHashSet = copy; } } public bool IsSubsetOf(IEnumerable<T> other) { return mHashSet.IsSubsetOf(other); } public bool IsProperSubsetOf(IEnumerable<T> other) { return mHashSet.IsProperSubsetOf(other); } public bool IsSupersetOf(IEnumerable<T> other) { return mHashSet.IsSupersetOf(other); } public bool IsProperSupersetOf(IEnumerable<T> other) { return mHashSet.IsProperSupersetOf(other); } public bool Overlaps(IEnumerable<T> other) { return mHashSet.Overlaps(other); } public bool SetEquals(IEnumerable<T> other) { return mHashSet.SetEquals(other); } public void CopyTo(T[] array) { mHashSet.CopyTo(array); } public void CopyTo(T[] array, int arrayIndex, int count) { mHashSet.CopyTo(array, arrayIndex, count); } public int RemoveWhere(Predicate<T> match) { lock (mHashSet) { HashSet<T> copy = GetCopy(); int result = copy.RemoveWhere(match); mHashSet = copy; return result; } } public void TrimExcess() { lock (mHashSet) { HashSet<T> copy = GetCopy(); copy.TrimExcess(); mHashSet = copy; } } public int Count { get { return mHashSet.Count; } } public IEqualityComparer<T> Comparer { get { return mHashSet.Comparer; } } public bool Add(T item) { lock (mLock) { HashSet<T> copy = GetCopy(); var result = copy.Add(item); mHashSet = copy; return result; } } public bool IsReadOnly { get { ICollection<T> hashSet = mHashSet; return hashSet.IsReadOnly; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
#region License // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace RestSharp { using System; using System.Collections.Generic; using System.IO; using System.Net; using Serializers; public interface IRestRequest { /// <summary> /// Always send a multipart/form-data request - even when no Files are present. /// </summary> bool AlwaysMultipartFormData { get; set; } /// <summary> /// Serializer to use when writing JSON request bodies. Used if RequestFormat is Json. /// By default the included JsonSerializer is used (currently using JSON.NET default serialization). /// </summary> ISerializer JsonSerializer { get; set; } /// <summary> /// Serializer to use when writing XML request bodies. Used if RequestFormat is Xml. /// By default the included XmlSerializer is used. /// </summary> ISerializer XmlSerializer { get; set; } /// <summary> /// Set this to write response to Stream rather than reading into memory. /// </summary> Action<Stream> ResponseWriter { get; set; } /// <summary> /// Container of all HTTP parameters to be passed with the request. /// See AddParameter() for explanation of the types of parameters that can be passed /// </summary> IList<Parameter> Parameters { get; } /// <summary> /// Container of all the files to be uploaded with the request. /// </summary> IList<FileParameter> Files { get; } /// <summary> /// Determines what HTTP method to use for this request. Supported methods: GET, POST, PUT, DELETE, HEAD, OPTIONS /// Default is GET /// </summary> Method Method { get; set; } /// <summary> /// The Resource URL to make the request against. /// Tokens are substituted with UrlSegment parameters and match by name. /// Should not include the scheme or domain. Do not include leading slash. /// Combined with RestClient.BaseUrl to assemble final URL: /// {BaseUrl}/{Resource} (BaseUrl is scheme + domain, e.g. http://example.com) /// </summary> /// <example> /// // example for url token replacement /// request.Resource = "Products/{ProductId}"; /// request.AddParameter("ProductId", 123, ParameterType.UrlSegment); /// </example> string Resource { get; set; } /// <summary> /// Serializer to use when writing XML request bodies. Used if RequestFormat is Xml. /// By default XmlSerializer is used. /// </summary> DataFormat RequestFormat { get; set; } /// <summary> /// Used by the default deserializers to determine where to start deserializing from. /// Can be used to skip container or root elements that do not have corresponding deserialzation targets. /// </summary> string RootElement { get; set; } /// <summary> /// Used by the default deserializers to explicitly set which date format string to use when parsing dates. /// </summary> string DateFormat { get; set; } /// <summary> /// Used by XmlDeserializer. If not specified, XmlDeserializer will flatten response by removing namespaces from element names. /// </summary> string XmlNamespace { get; set; } /// <summary> /// In general you would not need to set this directly. Used by the NtlmAuthenticator. /// </summary> ICredentials Credentials { get; set; } /// <summary> /// Timeout in milliseconds to be used for the request. This timeout value overrides a timeout set on the RestClient. /// </summary> int Timeout { get; set; } /// <summary> /// The number of milliseconds before the writing or reading times out. This timeout value overrides a timeout set on the RestClient. /// </summary> int ReadWriteTimeout { get; set; } /// <summary> /// How many attempts were made to send this Request? /// </summary> /// <remarks> /// This Number is incremented each time the RestClient sends the request. /// Useful when using Asynchronous Execution with Callbacks /// </remarks> int Attempts { get; } /// <summary> /// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) /// will be sent along to the server. The default is false. /// </summary> bool UseDefaultCredentials { get; set; } Action<IRestResponse> OnBeforeDeserialization { get; set; } #if FRAMEWORK /// <summary> /// Adds a file to the Files collection to be included with a POST or PUT request /// (other methods do not support file uploads). /// </summary> /// <param name="name">The parameter name to use in the request</param> /// <param name="path">Full path to file to upload</param> /// <param name="contentType">The MIME type of the file to upload</param> /// <returns>This request</returns> IRestRequest AddFile(string name, string path, string contentType = null); /// <summary> /// Adds the bytes to the Files collection with the specified file name and content type /// </summary> /// <param name="name">The parameter name to use in the request</param> /// <param name="bytes">The file data</param> /// <param name="fileName">The file name to use for the uploaded file</param> /// <param name="contentType">The MIME type of the file to upload</param> /// <returns>This request</returns> IRestRequest AddFile(string name, byte[] bytes, string fileName, string contentType = null); /// <summary> /// Adds the bytes to the Files collection with the specified file name and content type /// </summary> /// <param name="name">The parameter name to use in the request</param> /// <param name="writer">A function that writes directly to the stream. Should NOT close the stream.</param> /// <param name="fileName">The file name to use for the uploaded file</param> /// <param name="contentType">The MIME type of the file to upload</param> /// <returns>This request</returns> IRestRequest AddFile(string name, Action<Stream> writer, string fileName, string contentType = null); #endif /// <summary> /// Serializes obj to format specified by RequestFormat, but passes xmlNamespace if using the default XmlSerializer /// The default format is XML. Change RequestFormat if you wish to use a different serialization format. /// </summary> /// <param name="obj">The object to serialize</param> /// <param name="xmlNamespace">The XML namespace to use when serializing</param> /// <returns>This request</returns> IRestRequest AddBody(object obj, string xmlNamespace); /// <summary> /// Serializes obj to data format specified by RequestFormat and adds it to the request body. /// The default format is XML. Change RequestFormat if you wish to use a different serialization format. /// </summary> /// <param name="obj">The object to serialize</param> /// <returns>This request</returns> IRestRequest AddBody(object obj); /// <summary> /// Serializes obj to JSON format and adds it to the request body. /// </summary> /// <param name="obj">The object to serialize</param> /// <returns>This request</returns> IRestRequest AddJsonBody(object obj); /// <summary> /// Serializes obj to XML format and adds it to the request body. /// </summary> /// <param name="obj">The object to serialize</param> /// <returns>This request</returns> IRestRequest AddXmlBody(object obj); /// <summary> /// Serializes obj to format specified by RequestFormat, but passes xmlNamespace if using the default XmlSerializer /// Serializes obj to XML format and passes xmlNamespace then adds it to the request body. /// </summary> /// <param name="obj">The object to serialize</param> /// <param name="xmlNamespace">The XML namespace to use when serializing</param> /// <returns>This request</returns> IRestRequest AddXmlBody(object obj, string xmlNamespace); /// <summary> /// Calls AddParameter() for all public, readable properties specified in the includedProperties list /// </summary> /// <example> /// request.AddObject(product, "ProductId", "Price", ...); /// </example> /// <param name="obj">The object with properties to add as parameters</param> /// <param name="includedProperties">The names of the properties to include</param> /// <returns>This request</returns> IRestRequest AddObject(object obj, params string[] includedProperties); /// <summary> /// Calls AddParameter() for all public, readable properties of obj /// </summary> /// <param name="obj">The object with properties to add as parameters</param> /// <returns>This request</returns> IRestRequest AddObject(object obj); /// <summary> /// Add the parameter to the request /// </summary> /// <param name="p">Parameter to add</param> /// <returns></returns> IRestRequest AddParameter(Parameter p); /// <summary> /// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT) /// </summary> /// <param name="name">Name of the parameter</param> /// <param name="value">Value of the parameter</param> /// <returns>This request</returns> IRestRequest AddParameter(string name, object value); /// <summary> /// Adds a parameter to the request. There are five types of parameters: /// - GetOrPost: Either a QueryString value or encoded form value based on method /// - HttpHeader: Adds the name/value pair to the HTTP request'value Headers collection /// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} /// - Cookie: Adds the name/value pair to the HTTP request'value Cookies collection /// - RequestBody: Used by AddBody() (not recommended to use directly) /// </summary> /// <param name="name">Name of the parameter</param> /// <param name="value">Value of the parameter</param> /// <param name="type">The type of parameter to add</param> /// <returns>This request</returns> IRestRequest AddParameter(string name, object value, ParameterType type); /// <summary> /// Shortcut to AddParameter(name, value, HttpHeader) overload /// </summary> /// <param name="name">Name of the header to add</param> /// <param name="value">Value of the header to add</param> /// <returns></returns> IRestRequest AddHeader(string name, string value); /// <summary> /// Shortcut to AddParameter(name, value, Cookie) overload /// </summary> /// <param name="name">Name of the cookie to add</param> /// <param name="value">Value of the cookie to add</param> /// <returns></returns> IRestRequest AddCookie(string name, string value); /// <summary> /// Shortcut to AddParameter(name, value, UrlSegment) overload /// </summary> /// <param name="name">Name of the segment to add</param> /// <param name="value">Value of the segment to add</param> /// <returns></returns> IRestRequest AddUrlSegment(string name, string value); /// <summary> /// Shortcut to AddParameter(name, value, QueryString) overload /// </summary> /// <param name="name">Name of the parameter to add</param> /// <param name="value">Value of the parameter to add</param> /// <returns></returns> IRestRequest AddQueryParameter(string name, string value); void IncreaseNumAttempts(); } }
// 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; /// <summary> /// System.Collections.Generic.List.IndexOf(T item) /// </summary> public class ListIndexOf1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int"); try { int[] iArray = new int[1000]; for (int i = 0; i < 1000; i++) { iArray[i] = i; } List<int> listObject = new List<int>(iArray); int ob = this.GetInt32(0, 1000); int result = listObject.IndexOf(ob); if (result != ob) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string"); try { string[] strArray = { "apple", "banana", "chocolate", "dog", "food" }; List<string> listObject = new List<string>(strArray); int result = listObject.IndexOf("dog"); if (result != 3) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is a custom type"); try { MyClass myclass1 = new MyClass(); MyClass myclass2 = new MyClass(); MyClass myclass3 = new MyClass(); MyClass[] mc = new MyClass[3] { myclass1, myclass2, myclass3 }; List<MyClass> listObject = new List<MyClass>(mc); int result = listObject.IndexOf(myclass3); if (result != 2) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: There are many element in the list with the same value"); try { string[] strArray = { "apple", "banana", "chocolate", "banana", "banana", "dog", "banana", "food" }; List<string> listObject = new List<string>(strArray); int result = listObject.IndexOf("banana"); if (result != 1) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Do not find the element "); try { int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); int result = listObject.IndexOf(-10000); if (result != -1) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases #endregion #endregion public static int Main() { ListIndexOf1 test = new ListIndexOf1(); TestLibrary.TestFramework.BeginTestCase("ListIndexOf1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } } public class MyClass { }
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Mozu.Api.Contracts.Inventory { /// <summary> /// /// </summary> [DataContract] public class OrderItemInformation : BaseResponse { /// <summary> /// Order Identifier /// </summary> /// <value>Order Identifier</value> [DataMember(Name="orderID", EmitDefaultValue=false)] [JsonProperty(PropertyName = "orderID")] public int? OrderID { get; set; } /// <summary> /// Order Item Identifier /// </summary> /// <value>Order Item Identifier</value> [DataMember(Name="orderItemID", EmitDefaultValue=false)] [JsonProperty(PropertyName = "orderItemID")] public int? OrderItemID { get; set; } /// <summary> /// Location Identifier /// </summary> /// <value>Location Identifier</value> [DataMember(Name="locationID", EmitDefaultValue=false)] [JsonProperty(PropertyName = "locationID")] public int? LocationID { get; set; } /// <summary> /// Flag for whether the location is active /// </summary> /// <value>Flag for whether the location is active</value> [DataMember(Name="locationActive", EmitDefaultValue=false)] [JsonProperty(PropertyName = "locationActive")] public bool? LocationActive { get; set; } /// <summary> /// External Store Identifier /// </summary> /// <value>External Store Identifier</value> [DataMember(Name="locationCode", EmitDefaultValue=false)] [JsonProperty(PropertyName = "locationCode")] public int? LocationCode { get; set; } /// <summary> /// Location Name /// </summary> /// <value>Location Name</value> [DataMember(Name="locationName", EmitDefaultValue=false)] [JsonProperty(PropertyName = "locationName")] public string LocationName { get; set; } /// <summary> /// Bin Identifier /// </summary> /// <value>Bin Identifier</value> [DataMember(Name="binID", EmitDefaultValue=false)] [JsonProperty(PropertyName = "binID")] public int? BinID { get; set; } /// <summary> /// Part/Product Number /// </summary> /// <value>Part/Product Number</value> [DataMember(Name="partNumber", EmitDefaultValue=false)] [JsonProperty(PropertyName = "partNumber")] public string PartNumber { get; set; } /// <summary> /// Universal Product Code /// </summary> /// <value>Universal Product Code</value> [DataMember(Name="upc", EmitDefaultValue=false)] [JsonProperty(PropertyName = "upc")] public string Upc { get; set; } /// <summary> /// Stock Keeping Unit /// </summary> /// <value>Stock Keeping Unit</value> [DataMember(Name="sku", EmitDefaultValue=false)] [JsonProperty(PropertyName = "sku")] public string Sku { get; set; } /// <summary> /// Custom field used for store prioritization /// </summary> /// <value>Custom field used for store prioritization</value> [DataMember(Name="ltd", EmitDefaultValue=false)] [JsonProperty(PropertyName = "ltd")] public string Ltd { get; set; } /// <summary> /// Absolute minimum quantity of this item that should be in stock at any time /// </summary> /// <value>Absolute minimum quantity of this item that should be in stock at any time</value> [DataMember(Name="floor", EmitDefaultValue=false)] [JsonProperty(PropertyName = "floor")] public int? Floor { get; set; } /// <summary> /// Quantity of this item the location wants to keep in stock to ensure stock isn't completely depleted /// </summary> /// <value>Quantity of this item the location wants to keep in stock to ensure stock isn't completely depleted</value> [DataMember(Name="safetyStock", EmitDefaultValue=false)] [JsonProperty(PropertyName = "safetyStock")] public int? SafetyStock { get; set; } /// <summary> /// The quantity the location has in its possession /// </summary> /// <value>The quantity the location has in its possession</value> [DataMember(Name="onHand", EmitDefaultValue=false)] [JsonProperty(PropertyName = "onHand")] public int? OnHand { get; set; } /// <summary> /// The quantity the location has that are available for purchase /// </summary> /// <value>The quantity the location has that are available for purchase</value> [DataMember(Name="available", EmitDefaultValue=false)] [JsonProperty(PropertyName = "available")] public int? Available { get; set; } /// <summary> /// The quantity the location has that are allocated /// </summary> /// <value>The quantity the location has that are allocated</value> [DataMember(Name="allocated", EmitDefaultValue=false)] [JsonProperty(PropertyName = "allocated")] public int? Allocated { get; set; } /// <summary> /// Total number of allocations /// </summary> /// <value>Total number of allocations</value> [DataMember(Name="allocates", EmitDefaultValue=false)] [JsonProperty(PropertyName = "allocates")] public int? Allocates { get; set; } /// <summary> /// Total number of deallocations /// </summary> /// <value>Total number of deallocations</value> [DataMember(Name="deallocates", EmitDefaultValue=false)] [JsonProperty(PropertyName = "deallocates")] public int? Deallocates { get; set; } /// <summary> /// Total number of fulfillments. Should never be greater than 1. /// </summary> /// <value>Total number of fulfillments. Should never be greater than 1.</value> [DataMember(Name="fulfills", EmitDefaultValue=false)] [JsonProperty(PropertyName = "fulfills")] public int? Fulfills { get; set; } /// <summary> /// Total number of picks (WMS only) /// </summary> /// <value>Total number of picks (WMS only)</value> [DataMember(Name="picks", EmitDefaultValue=false)] [JsonProperty(PropertyName = "picks")] public int? Picks { get; set; } /// <summary> /// Pending quantity (WMS only) /// </summary> /// <value>Pending quantity (WMS only)</value> [DataMember(Name="pendingQuantity", EmitDefaultValue=false)] [JsonProperty(PropertyName = "pendingQuantity")] public int? PendingQuantity { get; set; } /// <summary> /// Order Identifier /// </summary> /// <value>Order Identifier</value> [DataMember(Name="events", EmitDefaultValue=false)] [JsonProperty(PropertyName = "events")] public List<OrderItemInformationEvent> Events { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class OrderItemInformation {\n"); sb.Append(" OrderID: ").Append(OrderID).Append("\n"); sb.Append(" OrderItemID: ").Append(OrderItemID).Append("\n"); sb.Append(" LocationID: ").Append(LocationID).Append("\n"); sb.Append(" LocationActive: ").Append(LocationActive).Append("\n"); sb.Append(" LocationCode: ").Append(LocationCode).Append("\n"); sb.Append(" LocationName: ").Append(LocationName).Append("\n"); sb.Append(" BinID: ").Append(BinID).Append("\n"); sb.Append(" PartNumber: ").Append(PartNumber).Append("\n"); sb.Append(" Upc: ").Append(Upc).Append("\n"); sb.Append(" Sku: ").Append(Sku).Append("\n"); sb.Append(" Ltd: ").Append(Ltd).Append("\n"); sb.Append(" Floor: ").Append(Floor).Append("\n"); sb.Append(" SafetyStock: ").Append(SafetyStock).Append("\n"); sb.Append(" OnHand: ").Append(OnHand).Append("\n"); sb.Append(" Available: ").Append(Available).Append("\n"); sb.Append(" Allocated: ").Append(Allocated).Append("\n"); sb.Append(" Allocates: ").Append(Allocates).Append("\n"); sb.Append(" Deallocates: ").Append(Deallocates).Append("\n"); sb.Append(" Fulfills: ").Append(Fulfills).Append("\n"); sb.Append(" Picks: ").Append(Picks).Append("\n"); sb.Append(" PendingQuantity: ").Append(PendingQuantity).Append("\n"); sb.Append(" Events: ").Append(Events).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public new string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class FluidSimSwitch : MonoBehaviour { public float dt = 0.8f; public float visc = 0; public float volatilize = 0; public int iterations = 10; public Texture2D border; public Texture2D flow; //SWE private bool mBtnLeft; public Button fluidButton; private RectTransform buttonTransform; public GameObject fluidNavierStokes; private bool setOnce; Texture2D tex; int width, height; float[] u, v, u_prev, v_prev; float[] dens, dens_prev; float[] bndX, bndY; float[] velX, velY; int rowSize; int size; //SWE float randomVal; int counter; void Start() { // duplicate the original texture and assign to the material tex = Instantiate(GetComponent<Renderer>().material.mainTexture) as Texture2D; GetComponent<Renderer>().material.mainTexture = tex; // get grid dimensions from texture width = tex.width; height = tex.height; // initialize fluid arrays rowSize = width + 2; size = (width + 2) * (height + 2); dens = new float[size]; dens_prev = new float[size]; u = new float[size]; u_prev = new float[size]; v = new float[size]; v_prev = new float[size]; bndX = new float[size]; bndY = new float[size]; velX = new float[size]; velY = new float[size]; for (int i = 0; i < size; i++) { dens_prev[i] = u_prev[i] = v_prev[i] = dens[i] = u[i] = v[i] = 0; int y = i / rowSize; int x = i % rowSize; bndX[i] = border.GetPixel(x, y).grayscale - border.GetPixel(x + 1, y).grayscale; bndY[i] = border.GetPixel(x, y).grayscale - border.GetPixel(x, y + 1).grayscale; velX[i] = (flow.GetPixel(x, y).grayscale - flow.GetPixel(x + 1, y).grayscale) * 0.1f; velY[i] = (flow.GetPixel(x, y).grayscale - flow.GetPixel(x, y + 1).grayscale) * 0.1f; } //SWE counter = 0; buttonTransform = fluidButton.GetComponent<RectTransform>(); setOnce = true; } void Update() { //fluidNavierStokes.SetActive(true); // reset values //Debug.Log(buttonTransform.position.x - 80); if (Input.mousePosition.x >=buttonTransform.position.x-80 && Input.mousePosition.x<= buttonTransform.position.x + 80 && Input.mousePosition.y>= buttonTransform.position.y - 30 && Input.mousePosition.y<= buttonTransform.position.y + 30) { for (int i = 0; i < size; i++) { dens_prev[i] = 0; u_prev[i] = velX[i]; v_prev[i] = velY[i]; } // fluidNavierStokes.transform.rotation = new Quaternion(0, 0, transform.position.y); //Reset(); // if (setOnce) //{ // setOnce = false; //Reset(); // } mBtnLeft = true; // fluidNavierStokes.SetActive(true); } else { // fluidNavierStokes.transform.position = new Vector3(transform.position.x, 1, transform.position.y); Reset(); // fluidNavierStokes.SetActive(false); mBtnLeft = false; } UserInput(); vel_step(u, v, u_prev, v_prev, dt); dens_step(dens, dens_prev, u, v, dt); Draw(); // Reset(); } void addFields(float[] x, float[] s, float dt) { for (int i = 0; i < size; i++) { x[i] += dt * s[i]; } } void set_bnd(int b, float[] x) { // b/w texture as obstacles for (int j = 1; j <= height; j++) { for (int i = 1; i <= width; i++) { int p = i + j * width; if (bndX[p] < 0) { x[p] = (b == 1) ? -x[p + 1] : x[p + 1]; } if (bndX[p] > 0) { x[p] = (b == 1) ? -x[p - 1] : x[p - 1]; } if (bndY[p] < 0) { x[p] = (b == 2) ? -x[p + rowSize] : x[p + rowSize]; } if (bndY[p] > 0) { x[p] = (b == 2) ? -x[p - rowSize] : x[p - rowSize]; } } } // only rect borders as obstacles (but faster) float sign; // left/right: reflect if b is 1, else keep value before edge sign = (b == 1) ? -1 : 1; for (int j = 1; j <= height; j++) { x[j * rowSize] = sign * x[1 + j * rowSize]; x[(width + 1) + j * rowSize] = sign * x[width + j * rowSize]; } // bottom/top: reflect if b is 2, else keep value before edge sign = (b == 2) ? -1 : 1; for (int i = 1; i <= width; i++) { x[i] = sign * x[i + rowSize]; x[i + (height + 1) * rowSize] = sign * x[i + height * rowSize]; } // vertices int maxEdge = (height + 1) * rowSize; x[0] = 0.5f * (x[1] + x[rowSize]); x[maxEdge] = 0.5f * (x[1 + maxEdge] + x[height * rowSize]); x[(width + 1)] = 0.5f * (x[width] + x[(width + 1) + rowSize]); x[(width + 1) + maxEdge] = 0.5f * (x[width + maxEdge] + x[(width + 1) + height * rowSize]); } void lin_solve(float[] x, float[] x0, float a, float c) { if (a == 0 && c == 1) { for (int i = 0; i < size; i++) { x[i] = x0[i]; } set_bnd(0, x); } else { for (int k = 0; k < iterations; k++) { for (int j = 1; j <= height; j++) { int lastRow = (j - 1) * rowSize; int currentRow = j * rowSize; int nextRow = (j + 1) * rowSize; float lastX = x[currentRow]; ++currentRow; for (int i = 1; i <= width; i++) lastX = x[currentRow] = (x0[currentRow] + a * (lastX + x[++currentRow] + x[++lastRow] + x[++nextRow])) / c; } set_bnd(0, x); } } } void diffuse(float[] x, float[] x0) { lin_solve(x, x0, volatilize, 1 + 4 * volatilize); } void lin_solve2(float[] x, float[] x0, float[] y, float[] y0, float a, float c) { if (a == 0 && c == 1) { for (int i = 0; i < size; i++) { x[i] = x0[i]; y[i] = y0[i]; } set_bnd(1, x); set_bnd(2, y); } else { for (int k = 0; k < iterations; k++) { for (int j = 1; j <= height; j++) { int lastRow = (j - 1) * rowSize; int currentRow = j * rowSize; int nextRow = (j + 1) * rowSize; float lastX = x[currentRow]; float lastY = y[currentRow]; ++currentRow; for (int i = 1; i <= width; i++) { lastX = x[currentRow] = (x0[currentRow] + a * (lastX + x[currentRow] + x[lastRow] + x[nextRow])) / c; lastY = y[currentRow] = (y0[currentRow] + a * (lastY + y[++currentRow] + y[++lastRow] + y[++nextRow])) / c; } } set_bnd(1, x); set_bnd(2, y); } } } void diffuse2(float[] x, float[] x0, float[] y, float[] y0) { lin_solve2(x, x0, y, y0, visc, 1 + 4 * visc); } void advect(int b, float[] d, float[] d0, float[] u, float[] v, float dt) { float dt0 = dt * width; float Wp5 = width + 0.5f; float Hp5 = height + 0.5f; for (int j = 1; j <= height; j++) { int pos = j * rowSize; for (int i = 1; i <= width; i++) { float x = i - dt0 * u[++pos]; float y = j - dt0 * v[pos]; if (x < 0.5f) x = 0.5f; else if (x > Wp5) x = Wp5; int i0 = (int)x; int i1 = i0 + 1; if (y < 0.5f) y = 0.5f; else if (y > Hp5) y = Hp5; int j0 = (int)y; int j1 = j0 + 1; float s1 = x - i0; float s0 = 1 - s1; float t1 = y - j0; float t0 = 1 - t1; int row1 = j0 * rowSize; int row2 = j1 * rowSize; d[pos] = s0 * (t0 * d0[i0 + row1] + t1 * d0[i0 + row2]) + s1 * (t0 * d0[i1 + row1] + t1 * d0[i1 + row2]); } } set_bnd(b, d); } void project(float[] u, float[] v, float[] p, float[] div) { float h = -0.5f / Mathf.Sqrt(width * height); for (int j = 1; j <= height; j++) { int row = j * rowSize; int previousRow = (j - 1) * rowSize; int prevValue = row - 1; int currentRow = row; int nextValue = row + 1; int nextRow = (j + 1) * rowSize; for (int i = 1; i <= width; i++) { div[++currentRow] = h * (u[++nextValue] - u[++prevValue] + v[++nextRow] - v[++previousRow]); p[currentRow] = 0; } } set_bnd(0, div); set_bnd(0, p); lin_solve(p, div, 1, 4); float scale = 0.5f * width; for (int j = 1; j <= height; j++) { int prevPos = j * rowSize - 1; int currentPos = j * rowSize; int nextPos = j * rowSize + 1; int prevRow = (j - 1) * rowSize; int nextRow = (j + 1) * rowSize; for (int i = 1; i <= width; i++) { u[++currentPos] -= scale * (p[++nextPos] - p[++prevPos]); v[currentPos] -= scale * (p[++nextRow] - p[++prevRow]); } } set_bnd(1, u); set_bnd(2, v); } void dens_step(float[] x, float[] x0, float[] u, float[] v, float dt) { addFields(x, x0, dt); diffuse(x0, x); advect(0, x, x0, u, v, dt); } void vel_step(float[] u, float[] v, float[] u0, float[] v0, float dt) { float[] temp; addFields(u, u0, dt); addFields(v, v0, dt); temp = u0; u0 = u; u = temp; temp = v0; v0 = v; v = temp; diffuse2(u, u0, v, v0); project(u, v, u0, v0); temp = u0; u0 = u; u = temp; temp = v0; v0 = v; v = temp; advect(1, u, u0, u0, v0, dt); advect(2, v, v0, u0, v0, dt); project(u, v, u0, v0); } void UserInput() { //SWE randomVal = Random.Range(1f, 10f); counter++; setOnce = false; if (counter >= 70) { randomVal = Random.Range(1f, 10f); counter = 0; } // draw on the water // bool mBtnLeft = true;//Input.GetMouseButton(0); randomVal >= 5.0f; // bool mBtnRight = false;//Input.GetMouseButton(1);randomVal <= 5.0f; if (mBtnLeft)// || mBtnRight) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//new Vector2(Input.mousePosition.x + Random.Range(40f, 750f), Input.mousePosition.y+Random.Range(30, 250))); RaycastHit hit; //Physics.Raycast() if (Physics.Raycast(ray, out hit, 100)) { // Debug.Log(hit.point); // determine indices where the user clicked Vector3 hitpoint = Camera.main.WorldToScreenPoint(hit.point); int x = (int)(hit.point.x * width); int y = (int)(hit.point.z * width); int i = (x + 1) + (y + 1) * rowSize; if (x < 1 || x > width - 1 || y < 1 || y > height - 1) return; // add or dec density dens_prev[i] += mBtnLeft ? 3f : -3f; // add velocity u_prev[i] += Input.GetAxis("Mouse X") * 0.5f; v_prev[i] += Input.GetAxis("Mouse Y") * 0.5f; } else { int x = (int)(Random.Range(0.0f, 0.8f) * width); int y = (int)(Random.Range(0.0f, 0.2f) * width); int i = (x + 1) + (y + 1) * rowSize; if (x < 1 || x > width - 1 || y < 1 || y > height - 1) return; // add or dec density dens_prev[i] += mBtnLeft ? 3f : -3f; // add velocity u_prev[i] += Input.GetAxis("Mouse X") * 0.5f; v_prev[i] += Input.GetAxis("Mouse Y") * 0.5f; } } } void Draw() { // visualize water for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int i = (x + 1) + (y + 1) * rowSize; float d = 5f * dens[i]; tex.SetPixel(x, y, new Color(u[i] * 50 + 0f, v[i] * 50 + 0f + d * 0.5f, 0f + d));//u[i]*20 + bndX[i] + 0f, v[i]*20 + bndY[i] + 0f + d * 0.5f, 0f + d)); // float d = 5f * dens[(x + 1) + (y + 1) * rowSize]; // tex.SetPixel(x, y, new Color(0, d * 0.5f, d)); } } tex.Apply(false); } public void Reset() { rowSize = width + 2; size = (width + 2) * (height + 2); dens = new float[size]; dens_prev = new float[size]; u = new float[size]; u_prev = new float[size]; v = new float[size]; v_prev = new float[size]; bndX = new float[size]; bndY = new float[size]; velX = new float[size]; velY = new float[size]; for (int i = 0; i < size; i++) { dens_prev[i] = u_prev[i] = v_prev[i] = dens[i] = u[i] = v[i] = 0; int y = i / rowSize; int x = i % rowSize; bndX[i] = border.GetPixel(x, y).grayscale - border.GetPixel(x + 1, y).grayscale; bndY[i] = border.GetPixel(x, y).grayscale - border.GetPixel(x, y + 1).grayscale; velX[i] = (flow.GetPixel(x, y).grayscale - flow.GetPixel(x + 1, y).grayscale) * 0.1f; velY[i] = (flow.GetPixel(x, y).grayscale - flow.GetPixel(x, y + 1).grayscale) * 0.1f; } } }
using System; using System.Collections.Generic; using System.Xml.Serialization; namespace GPX { /// <summary> /// This represents a track - an ordered list of points describing a path. /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")] public class Track { #region Variables private string nameField; private string cmtField; private string descField; private string srcField; //private linkType[] linkField; private List<Link> linkField; private string numberField; private string typeField; private Extensions extensionsField; //private TrackSegment[] trksegField; private List<TrackSegment> trksegField; #endregion Variables public Track() { trksegField = new List<TrackSegment>(); } /// <summary> /// GPS name of track. /// </summary> [System.Xml.Serialization.XmlElementAttribute("name")] public string Name { get { return this.nameField; } set { this.nameField = value; } } /// <summary> /// GPS comment for track. /// </summary> [System.Xml.Serialization.XmlElementAttribute("cmt")] public string Comment { get { return this.cmtField; } set { this.cmtField = value; } } /// <summary> /// User description of track. /// </summary> [System.Xml.Serialization.XmlElementAttribute("desc")] public string Description { get { return this.descField; } set { this.descField = value; } } /// <summary> /// Source of data. Included to give user some idea of reliability and accuracy of data. /// </summary> [System.Xml.Serialization.XmlElementAttribute("src")] public string Source { get { return this.srcField; } set { this.srcField = value; } } /// <summary> /// Links to external information about track. /// </summary> [System.Xml.Serialization.XmlElementAttribute("link")] public List<Link> Link { get { return this.linkField; } set { this.linkField = value; } } /// <summary> /// GPS track number. /// </summary> [System.Xml.Serialization.XmlElementAttribute(DataType = "nonNegativeInteger", ElementName="number")] public string number { get { return this.numberField; } set { this.numberField = value; } } /// <summary> /// Type (classification) of track. /// </summary> [System.Xml.Serialization.XmlElementAttribute("type")] public string Classification { get { return this.typeField; } set { this.typeField = value; } } /// <summary> /// You can add extend GPX by adding your own elements from another schema here. /// </summary> public Extensions extensions { get { return this.extensionsField; } set { this.extensionsField = value; } } /// <summary> /// A Track Segment holds a list of Track Points which are logically connected in order. /// </summary> /// <remarks>To represent a single GPS track where GPS reception was lost, or the GPS receiver was turned off, start a new Track Segment for each continuous span of track data.</remarks> /// <example>A more modern use of this element may be for the representation of river branches or the creation of trail networks.</example> [System.Xml.Serialization.XmlElementAttribute("trkseg")] public List<TrackSegment> TrackSegments { get { return this.trksegField; } set { this.trksegField = value; } } /// <summary> /// Debbie: get all the waypoints from the track. /// </summary> /// <returns>list of waypoints</returns> public List<WayPoint> ToWayPoints() { List<WayPoint> points = new List<WayPoint>(); foreach (TrackSegment seg in trksegField) { points.AddRange(seg.WayPoints); } return points; } public Track(Gpx.GpxTrack oldtrk) : this() { Comment = oldtrk.Comment; Description = oldtrk.Description; Name = oldtrk.Name; number = oldtrk.Number.ToString(); srcField = oldtrk.Source; foreach (Gpx.GpxTrackSegment oldseg in oldtrk.Segments) { TrackSegment seg = new TrackSegment(); foreach (Gpx.GpxPoint pt in oldseg.TrackPoints) { seg.WayPoints.Add(new WayPoint(pt)); } TrackSegments.Add(seg); } } #region Extensions private BoundsEx _boundsField; [System.Xml.Serialization.XmlIgnore()] public BoundsEx TrackBounds { get { if (_boundsField == null) { CalculateBounds(); } return _boundsField; } } public void CalculateBounds() { _boundsField = trksegField[0].TrackBounds; for (int i = 1; i < trksegField.Count; i++) { BoundsEx bounds = trksegField[i].TrackBounds; if (_boundsField.ElevationMaximum < bounds.ElevationMaximum) _boundsField.ElevationMaximum = bounds.ElevationMaximum; if (_boundsField.ElevationMinimum > bounds.ElevationMinimum) _boundsField.ElevationMinimum = bounds.ElevationMinimum; if (_boundsField.EndTime < bounds.EndTime) _boundsField.EndTime = bounds.EndTime; if (_boundsField.LatitudeMaximum < bounds.LatitudeMaximum) _boundsField.LatitudeMaximum = bounds.LatitudeMaximum; if (_boundsField.LatitudeMinimum > bounds.LatitudeMinimum) _boundsField.LatitudeMinimum = bounds.LatitudeMinimum; if (_boundsField.LongitudeMaximum < bounds.LongitudeMaximum) _boundsField.LongitudeMaximum = bounds.LongitudeMaximum; if (_boundsField.LongitudeMinimum > bounds.LongitudeMinimum) _boundsField.LongitudeMinimum = bounds.LongitudeMinimum; if (_boundsField.StartTime > bounds.StartTime) _boundsField.StartTime = bounds.StartTime; } } private double _TrackLength; public double GetTrackLength() { return _TrackLength; } private double _MaximumSpeed; public double GetMaximumSpeed() { return _MaximumSpeed; } private TimeSpan _Duration; public TimeSpan GetDuration() { return _Duration; } public void Recalculate() { _TrackLength = 0; _MaximumSpeed = 0; _Duration = new TimeSpan(0); _boundsField = null; foreach (TrackSegment seg in trksegField) { seg.Recalculate(); _TrackLength += seg.GetSegmentLength(); _Duration += seg.GetDuration(); if (_MaximumSpeed < seg.GetMaximumSpeed()) _MaximumSpeed = seg.GetMaximumSpeed(); } } public static Track FromRoute(Route route) { Track retVal = new Track(); retVal.Classification = route.Classification; retVal.Comment = route.Comment; retVal.Description = route.Description; retVal.Link = route.Link; retVal.Name = route.Name; retVal.number = route.Number; retVal.Source = route.src; retVal.TrackSegments = new List<TrackSegment>(); TrackSegment segment = new TrackSegment(); segment.WayPoints = new List<WayPoint>(); foreach (WayPoint wp in route.rtept) { segment.WayPoints.Add(wp); } retVal.TrackSegments.Add(segment); return retVal; } #endregion Extensions } }
using System; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; using NUnit.Framework; namespace GitVersion.Core.Tests { [TestFixture] public class StringFormatWithExtensionTests { private IEnvironment environment; [SetUp] public void Setup() { environment = new TestEnvironment(); } [Test] public void FormatWithNoTokens() { var propertyObject = new { }; var target = "Some String without tokens"; var expected = target; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithSingleSimpleToken() { var propertyObject = new { SomeProperty = "SomeValue" }; var target = "{SomeProperty}"; var expected = "SomeValue"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithMultipleTokensAndVerbatimText() { var propertyObject = new { SomeProperty = "SomeValue", AnotherProperty = "Other Value" }; var target = "{SomeProperty} some text {AnotherProperty}"; var expected = "SomeValue some text Other Value"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithEnvVarToken() { environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value"); var propertyObject = new { }; var target = "{env:GIT_VERSION_TEST_VAR}"; var expected = "Env Var Value"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithEnvVarTokenWithFallback() { environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value"); var propertyObject = new { }; var target = "{env:GIT_VERSION_TEST_VAR ?? fallback}"; var expected = "Env Var Value"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithUnsetEnvVarToken_WithFallback() { environment.SetEnvironmentVariable("GIT_VERSION_UNSET_TEST_VAR", null); var propertyObject = new { }; var target = "{env:GIT_VERSION_UNSET_TEST_VAR ?? fallback}"; var expected = "fallback"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithUnsetEnvVarToken_WithoutFallback() { environment.SetEnvironmentVariable("GIT_VERSION_UNSET_TEST_VAR", null); var propertyObject = new { }; var target = "{env:GIT_VERSION_UNSET_TEST_VAR}"; Assert.Throws<ArgumentException>(() => target.FormatWith(propertyObject, environment)); } [Test] public void FormatWithMultipleEnvVars() { environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR_1", "Val-1"); environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR_2", "Val-2"); var propertyObject = new { }; var target = "{env:GIT_VERSION_TEST_VAR_1} and {env:GIT_VERSION_TEST_VAR_2}"; var expected = "Val-1 and Val-2"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithMultipleEnvChars() { var propertyObject = new { }; //Test the greediness of the regex in matching env: char var target = "{env:env:GIT_VERSION_TEST_VAR_1} and {env:DUMMY_VAR ?? fallback}"; var expected = "{env:env:GIT_VERSION_TEST_VAR_1} and fallback"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithMultipleFallbackChars() { var propertyObject = new { }; //Test the greediness of the regex in matching env: and ?? chars var target = "{env:env:GIT_VERSION_TEST_VAR_1} and {env:DUMMY_VAR ??? fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(target, actual); } [Test] public void FormatWithSingleFallbackChar() { environment.SetEnvironmentVariable("DUMMY_ENV_VAR", "Dummy-Val"); var propertyObject = new { }; //Test the sanity of the regex when there is a grammar mismatch var target = "{en:DUMMY_ENV_VAR} and {env:DUMMY_ENV_VAR??fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(target, actual); } [Test] public void FormatWIthNullPropagationWithMultipleSpaces() { var propertyObject = new { SomeProperty = "Some Value" }; var target = "{SomeProperty} and {env:DUMMY_ENV_VAR ?? fallback}"; var expected = "Some Value and fallback"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatEnvVar_WithFallback_QuotedAndEmpty() { environment.SetEnvironmentVariable("ENV_VAR", null); var propertyObject = new { }; var target = "{env:ENV_VAR ?? \"\"}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("")); } [Test] public void FormatProperty_String() { var propertyObject = new { Property = "Value" }; var target = "{Property}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("Value")); } [Test] public void FormatProperty_Integer() { var propertyObject = new { Property = 42 }; var target = "{Property}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("42")); } [Test] public void FormatProperty_NullObject() { var propertyObject = new { Property = (object)null }; var target = "{Property}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("")); } [Test] public void FormatProperty_NullInteger() { var propertyObject = new { Property = (int?)null }; var target = "{Property}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("")); } [Test] public void FormatProperty_String_WithFallback() { var propertyObject = new { Property = "Value" }; var target = "{Property ?? fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("Value")); } [Test] public void FormatProperty_Integer_WithFallback() { var propertyObject = new { Property = 42 }; var target = "{Property ?? fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("42")); } [Test] public void FormatProperty_NullObject_WithFallback() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("fallback")); } [Test] public void FormatProperty_NullInteger_WithFallback() { var propertyObject = new { Property = (int?)null }; var target = "{Property ?? fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("fallback")); } [Test] public void FormatProperty_NullObject_WithFallback_Quoted() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? \"fallback\"}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("fallback")); } [Test] public void FormatProperty_NullObject_WithFallback_QuotedAndPadded() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? \" fallback \"}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo(" fallback ")); } [Test] public void FormatProperty_NullObject_WithFallback_QuotedAndEmpty() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? \"\"}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("")); } } }
using UnityEngine; namespace HoloToolKit.Unity { // The easiest way to use this script is to drop in the HeadsUpDirectionIndicator prefab // from the HoloToolKit. If you're having issues with the prefab or can't find it, // you can simply create an empty GameObject and attach this script. You'll need to // create your own pointer object which can by any 3D game object. You'll need to adjust // the depth, margin and pivot variables to affect the right appearance. After that you // simply need to specify the "targetObject" and then you should be set. // // This script assumes your point object "aims" along its local up axis and orients the // object according to that assumption. public class HeadsUpDirectionIndicator : MonoBehaviour { // Use as a named indexer for Unity's frustum planes. The order follows that layed // out in the API documentation. DO NOT CHANGE ORDER unless a corresponding change // has been made in the Unity API. private enum FrustumPlanes { Left = 0, Right, Bottom, Top, Near, Far } [Tooltip("The object the direction indicator will point to.")] public GameObject TargetObject; [Tooltip("The camera depth at which the indicator rests.")] public float Depth; [Tooltip("The point around which the indicator pivots. Should be placed at the model's 'tip'.")] public Vector3 Pivot; [Tooltip("The object used to 'point' at the target.")] public GameObject PointerPrefab; [Tooltip("Determines what percentage of the visible field should be margin.")] [Range(0.0f, 1.0f)] public float IndicatorMarginPercent; [Tooltip("Debug draw the planes used to calculate the pointer lock location.")] public bool DebugDrawPointerOrientationPlanes; private GameObject pointer; private static int frustumLastUpdated = -1; private static Plane[] frustumPlanes; private static Vector3 cameraForward; private static Vector3 cameraPosition; private static Vector3 cameraRight; private static Vector3 cameraUp; private Plane[] indicatorVolume; private void Start() { Depth = Mathf.Clamp(Depth, Camera.main.nearClipPlane, Camera.main.farClipPlane); if (PointerPrefab == null) { this.gameObject.SetActive(false); return; } pointer = GameObject.Instantiate(PointerPrefab); // We create the effect of pivoting rotations by parenting the pointer and // offsetting its position. pointer.transform.parent = transform; pointer.transform.position = -Pivot; // Allocate the space to hold the indicator volume planes. Later portions of the algorithm take for // granted that these objects have been initialized. indicatorVolume = new Plane[] { new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane() }; } // Update the direction indicator's position and orientation every frame. private void Update() { // No object to track? if (TargetObject == null || pointer == null) { // bail out early. return; } else { int currentFrameCount = UnityEngine.Time.frameCount; if (currentFrameCount != frustumLastUpdated) { // Collect the updated camera information for the current frame CacheCameraTransform(Camera.main); frustumLastUpdated = currentFrameCount; } UpdatePointerTransform(Camera.main, indicatorVolume, TargetObject.transform.position); } } // Cache data from the camera state that are costly to retrieve. private void CacheCameraTransform(Camera camera) { cameraForward = camera.transform.forward; cameraPosition = camera.transform.position; cameraRight = camera.transform.right; cameraUp = camera.transform.up; frustumPlanes = GeometryUtility.CalculateFrustumPlanes(camera); } // Assuming the target object is outside the view which of the four "wall" planes should // the pointer snap to. private FrustumPlanes GetExitPlane(Vector3 targetPosition, Camera camera) { // To do this we first create two planes that diagonally bisect the frustum // These panes create four quadrants. We then infer the exit plane based on // which quadrant the target position is in. // Calculate a set of vectors that can be used to build the frustum corners in world // space. float aspect = camera.aspect; float fovy = 0.5f * camera.fieldOfView; float near = camera.nearClipPlane; float far = camera.farClipPlane; float tanFovy = Mathf.Tan(Mathf.Deg2Rad * fovy); float tanFovx = aspect * tanFovy; // Calculate the edges of the frustum as world space offsets from the middle of the // frustum in world space. Vector3 nearTop = near * tanFovy * cameraUp; Vector3 nearRight = near * tanFovx * cameraRight; Vector3 nearBottom = -nearTop; Vector3 nearLeft = -nearRight; Vector3 farTop = far * tanFovy * cameraUp; Vector3 farRight = far * tanFovx * cameraRight; Vector3 farLeft = -farRight; // Caclulate the center point of the near plane and the far plane as offsets from the // camera in world space. Vector3 nearBase = near * cameraForward; Vector3 farBase = far * cameraForward; // Calculate the frustum corners needed to create 'd' Vector3 nearUpperLeft = nearBase + nearTop + nearLeft; Vector3 nearLowerRight = nearBase + nearBottom + nearRight; Vector3 farUpperLeft = farBase + farTop + farLeft; Plane d = new Plane(nearUpperLeft, nearLowerRight, farUpperLeft); // Calculate the frustum corners needed to create 'e' Vector3 nearUpperRight = nearBase + nearTop + nearRight; Vector3 nearLowerLeft = nearBase + nearBottom + nearLeft; Vector3 farUpperRight = farBase + farTop + farRight; Plane e = new Plane(nearUpperRight, nearLowerLeft, farUpperRight); #if UNITY_EDITOR if (DebugDrawPointerOrientationPlanes) { // Debug draw a tringale coplanar with 'd' Debug.DrawLine(nearUpperLeft, nearLowerRight); Debug.DrawLine(nearLowerRight, farUpperLeft); Debug.DrawLine(farUpperLeft, nearUpperLeft); // Debug draw a triangle coplanar with 'e' Debug.DrawLine(nearUpperRight, nearLowerLeft); Debug.DrawLine(nearLowerLeft, farUpperRight); Debug.DrawLine(farUpperRight, nearUpperRight); } #endif // We're not actually interested in the "distance" to the planes. But the sign // of the distance tells us which quadrant the target position is in. float dDistance = d.GetDistanceToPoint(targetPosition); float eDistance = e.GetDistanceToPoint(targetPosition); // d e // +\- +/- // \ -d +e / // \ / // \ / // \ / // \ / // +d +e \/ // /\ -d -e // / \ // / \ // / \ // / \ // / +d -e \ // +/- +\- if (dDistance > 0.0f) { if (eDistance > 0.0f) { return FrustumPlanes.Left; } else { return FrustumPlanes.Bottom; } } else { if (eDistance > 0.0f) { return FrustumPlanes.Top; } else { return FrustumPlanes.Right; } } } // given a frustum wall we wish to snap the pointer to, this function returns a ray // along which the pointer should be placed to appear at the appropiate point along // the edge of the indicator field. private bool TryGetIndicatorPosition(Vector3 targetPosition, Plane frustumWall, out Ray r) { // Think of the pointer as pointing the shortest rotation a user must make to see a // target. The shortest rotation can be obtained by finding the great circle defined // be the target, the camera position and the center position of the view. The tangent // vector of the great circle points the direction of the shortest rotation. This // great circle and thus any of it's tangent vectors are coplanar with the plane // defined by these same three points. Vector3 cameraToTarget = targetPosition - cameraPosition; Vector3 normal = Vector3.Cross(cameraToTarget.normalized, cameraForward); // In the case that the three points are colinear we cannot form a plane but we'll // assume the target is directly behind us and we'll use a prechosen plane. if (normal == Vector3.zero) { normal = -Vector3.right; } Plane q = new Plane(normal, targetPosition); return TryIntersectPlanes(frustumWall, q, out r); } // Obtain the line of intersection of two planes. This is based on a method // described in the GPU Gems series. private bool TryIntersectPlanes(Plane p, Plane q, out Ray intersection) { Vector3 rNormal = Vector3.Cross(p.normal, q.normal); float det = rNormal.sqrMagnitude; if (det != 0.0f) { Vector3 rPoint = ((Vector3.Cross(rNormal, q.normal) * p.distance) + (Vector3.Cross(p.normal, rNormal) * q.distance)) / det; intersection = new Ray(rPoint, rNormal); return true; } else { intersection = new Ray(); return false; } } // Modify the pointer location and orientation to point along the shortest rotation, // toward tergetPosition, keeping the pointer confined inside the frustum defined by // planes. private void UpdatePointerTransform(Camera camera, Plane[] planes, Vector3 targetPosition) { // Use the camera information to create the new bounding volume UpdateIndicatorVolume(camera); // Start by assuming the pointer should be placed at the target position. Vector3 indicatorPosition = cameraPosition + Depth * (targetPosition - cameraPosition).normalized; // Test the target position with the frustum planes except the "far" plane since // far away objects should be considered in view. bool pointNotInsideIndicatorField = false; for (int i = 0; i < 5; ++i) { float dot = Vector3.Dot(planes[i].normal, (targetPosition - cameraPosition).normalized); if (dot <= 0.0f) { pointNotInsideIndicatorField = true; break; } } // if the target object appears outside the indicator area... if (pointNotInsideIndicatorField) { // ...then we need to do some geometry calculations to lock it to the edge. // used to determine which edge of the screen the indicator vector // would exit through. FrustumPlanes exitPlane = GetExitPlane(targetPosition, camera); Ray r; if (TryGetIndicatorPosition(targetPosition, planes[(int)exitPlane], out r)) { indicatorPosition = cameraPosition + Depth * r.direction.normalized; } } this.transform.position = indicatorPosition; // The pointer's direction should always appear pointing away from the user's center // of view. Thus we find the center point of the user's view in world space. // But the pointer should also appear perpendicular to the viewer so we find the // center position of the view that is on the same plane as the pointer position. // We do this by projecting the vector from the pointer to the camera onto the // the camera's forward vector. Vector3 indicatorFieldOffset = indicatorPosition - cameraPosition; indicatorFieldOffset = Vector3.Dot(indicatorFieldOffset, cameraForward) * cameraForward; Vector3 indicatorFieldCenter = cameraPosition + indicatorFieldOffset; Vector3 pointerDirection = (indicatorPosition - indicatorFieldCenter).normalized; // allign this object's up vector with the pointerDirection this.transform.rotation = Quaternion.LookRotation(cameraForward, pointerDirection); } // Here we adjust the Camera's frustum planes to place the cursor in a smaller // volume, thus creating the effect of a "margin" private void UpdateIndicatorVolume(Camera camera) { // The top, bottom and side frustum planes are used to restrict the movement // of the pointer. These reside at indices 0-3; for (int i = 0; i < 4; ++i) { // We can make the frustum smaller by rotating the walls "in" toward the // camera's forward vector. // First find the angle between the Camera's forward and the plane's normal float angle = Mathf.Acos(Vector3.Dot(frustumPlanes[i].normal.normalized, cameraForward)); // Then we calculate how much we should rotate the plane in based on the // user's setting. 90 degrees is our maximum as at that point we no longer // have a valid frustum. float angleStep = IndicatorMarginPercent * (0.5f * Mathf.PI - angle); // Because the frustum plane normals face in we must actually rotate away from the forward vector // to narrow the frustum. Vector3 normal = Vector3.RotateTowards(frustumPlanes[i].normal, cameraForward, -angleStep, 0.0f); indicatorVolume[i].normal = normal.normalized; indicatorVolume[i].distance = frustumPlanes[i].distance; } indicatorVolume[4] = frustumPlanes[4]; indicatorVolume[5] = frustumPlanes[5]; } } }
using System; using Avalonia.Logging; using Avalonia.VisualTree; #nullable enable namespace Avalonia.Layout { /// <summary> /// Defines how a control aligns itself horizontally in its parent control. /// </summary> public enum HorizontalAlignment { /// <summary> /// The control stretches to fill the width of the parent control. /// </summary> Stretch, /// <summary> /// The control aligns itself to the left of the parent control. /// </summary> Left, /// <summary> /// The control centers itself in the parent control. /// </summary> Center, /// <summary> /// The control aligns itself to the right of the parent control. /// </summary> Right, } /// <summary> /// Defines how a control aligns itself vertically in its parent control. /// </summary> public enum VerticalAlignment { /// <summary> /// The control stretches to fill the height of the parent control. /// </summary> Stretch, /// <summary> /// The control aligns itself to the top of the parent control. /// </summary> Top, /// <summary> /// The control centers itself within the parent control. /// </summary> Center, /// <summary> /// The control aligns itself to the bottom of the parent control. /// </summary> Bottom, } /// <summary> /// Implements layout-related functionality for a control. /// </summary> public class Layoutable : Visual, ILayoutable { /// <summary> /// Defines the <see cref="DesiredSize"/> property. /// </summary> public static readonly DirectProperty<Layoutable, Size> DesiredSizeProperty = AvaloniaProperty.RegisterDirect<Layoutable, Size>(nameof(DesiredSize), o => o.DesiredSize); /// <summary> /// Defines the <see cref="Width"/> property. /// </summary> public static readonly StyledProperty<double> WidthProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(Width), double.NaN); /// <summary> /// Defines the <see cref="Height"/> property. /// </summary> public static readonly StyledProperty<double> HeightProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(Height), double.NaN); /// <summary> /// Defines the <see cref="MinWidth"/> property. /// </summary> public static readonly StyledProperty<double> MinWidthProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(MinWidth)); /// <summary> /// Defines the <see cref="MaxWidth"/> property. /// </summary> public static readonly StyledProperty<double> MaxWidthProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(MaxWidth), double.PositiveInfinity); /// <summary> /// Defines the <see cref="MinHeight"/> property. /// </summary> public static readonly StyledProperty<double> MinHeightProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(MinHeight)); /// <summary> /// Defines the <see cref="MaxHeight"/> property. /// </summary> public static readonly StyledProperty<double> MaxHeightProperty = AvaloniaProperty.Register<Layoutable, double>(nameof(MaxHeight), double.PositiveInfinity); /// <summary> /// Defines the <see cref="Margin"/> property. /// </summary> public static readonly StyledProperty<Thickness> MarginProperty = AvaloniaProperty.Register<Layoutable, Thickness>(nameof(Margin)); /// <summary> /// Defines the <see cref="HorizontalAlignment"/> property. /// </summary> public static readonly StyledProperty<HorizontalAlignment> HorizontalAlignmentProperty = AvaloniaProperty.Register<Layoutable, HorizontalAlignment>(nameof(HorizontalAlignment)); /// <summary> /// Defines the <see cref="VerticalAlignment"/> property. /// </summary> public static readonly StyledProperty<VerticalAlignment> VerticalAlignmentProperty = AvaloniaProperty.Register<Layoutable, VerticalAlignment>(nameof(VerticalAlignment)); /// <summary> /// Defines the <see cref="UseLayoutRoundingProperty"/> property. /// </summary> public static readonly StyledProperty<bool> UseLayoutRoundingProperty = AvaloniaProperty.Register<Layoutable, bool>(nameof(UseLayoutRounding), defaultValue: true, inherits: true); private bool _measuring; private Size? _previousMeasure; private Rect? _previousArrange; private EventHandler<EffectiveViewportChangedEventArgs>? _effectiveViewportChanged; private EventHandler? _layoutUpdated; /// <summary> /// Initializes static members of the <see cref="Layoutable"/> class. /// </summary> static Layoutable() { AffectsMeasure<Layoutable>( IsVisibleProperty, WidthProperty, HeightProperty, MinWidthProperty, MaxWidthProperty, MinHeightProperty, MaxHeightProperty, MarginProperty, HorizontalAlignmentProperty, VerticalAlignmentProperty); } /// <summary> /// Occurs when the element's effective viewport changes. /// </summary> public event EventHandler<EffectiveViewportChangedEventArgs>? EffectiveViewportChanged { add { if (_effectiveViewportChanged is null && VisualRoot is ILayoutRoot r) { r.LayoutManager.RegisterEffectiveViewportListener(this); } _effectiveViewportChanged += value; } remove { _effectiveViewportChanged -= value; if (_effectiveViewportChanged is null && VisualRoot is ILayoutRoot r) { r.LayoutManager.UnregisterEffectiveViewportListener(this); } } } /// <summary> /// Occurs when a layout pass completes for the control. /// </summary> public event EventHandler? LayoutUpdated { add { if (_layoutUpdated is null && VisualRoot is ILayoutRoot r) { r.LayoutManager.LayoutUpdated += LayoutManagedLayoutUpdated; } _layoutUpdated += value; } remove { _layoutUpdated -= value; if (_layoutUpdated is null && VisualRoot is ILayoutRoot r) { r.LayoutManager.LayoutUpdated -= LayoutManagedLayoutUpdated; } } } /// <summary> /// Gets or sets the width of the element. /// </summary> public double Width { get { return GetValue(WidthProperty); } set { SetValue(WidthProperty, value); } } /// <summary> /// Gets or sets the height of the element. /// </summary> public double Height { get { return GetValue(HeightProperty); } set { SetValue(HeightProperty, value); } } /// <summary> /// Gets or sets the minimum width of the element. /// </summary> public double MinWidth { get { return GetValue(MinWidthProperty); } set { SetValue(MinWidthProperty, value); } } /// <summary> /// Gets or sets the maximum width of the element. /// </summary> public double MaxWidth { get { return GetValue(MaxWidthProperty); } set { SetValue(MaxWidthProperty, value); } } /// <summary> /// Gets or sets the minimum height of the element. /// </summary> public double MinHeight { get { return GetValue(MinHeightProperty); } set { SetValue(MinHeightProperty, value); } } /// <summary> /// Gets or sets the maximum height of the element. /// </summary> public double MaxHeight { get { return GetValue(MaxHeightProperty); } set { SetValue(MaxHeightProperty, value); } } /// <summary> /// Gets or sets the margin around the element. /// </summary> public Thickness Margin { get { return GetValue(MarginProperty); } set { SetValue(MarginProperty, value); } } /// <summary> /// Gets or sets the element's preferred horizontal alignment in its parent. /// </summary> public HorizontalAlignment HorizontalAlignment { get { return GetValue(HorizontalAlignmentProperty); } set { SetValue(HorizontalAlignmentProperty, value); } } /// <summary> /// Gets or sets the element's preferred vertical alignment in its parent. /// </summary> public VerticalAlignment VerticalAlignment { get { return GetValue(VerticalAlignmentProperty); } set { SetValue(VerticalAlignmentProperty, value); } } /// <summary> /// Gets the size that this element computed during the measure pass of the layout process. /// </summary> public Size DesiredSize { get; private set; } /// <summary> /// Gets a value indicating whether the control's layout measure is valid. /// </summary> public bool IsMeasureValid { get; private set; } /// <summary> /// Gets a value indicating whether the control's layouts arrange is valid. /// </summary> public bool IsArrangeValid { get; private set; } /// <summary> /// Gets or sets a value that determines whether the element should be snapped to pixel /// boundaries at layout time. /// </summary> public bool UseLayoutRounding { get { return GetValue(UseLayoutRoundingProperty); } set { SetValue(UseLayoutRoundingProperty, value); } } /// <summary> /// Gets the available size passed in the previous layout pass, if any. /// </summary> Size? ILayoutable.PreviousMeasure => _previousMeasure; /// <summary> /// Gets the layout rect passed in the previous layout pass, if any. /// </summary> Rect? ILayoutable.PreviousArrange => _previousArrange; /// <summary> /// Creates the visual children of the control, if necessary /// </summary> public virtual void ApplyTemplate() { } /// <summary> /// Carries out a measure of the control. /// </summary> /// <param name="availableSize">The available size for the control.</param> public void Measure(Size availableSize) { if (double.IsNaN(availableSize.Width) || double.IsNaN(availableSize.Height)) { throw new InvalidOperationException("Cannot call Measure using a size with NaN values."); } if (!IsMeasureValid || _previousMeasure != availableSize) { var previousDesiredSize = DesiredSize; var desiredSize = default(Size); IsMeasureValid = true; try { _measuring = true; desiredSize = MeasureCore(availableSize); } finally { _measuring = false; } if (IsInvalidSize(desiredSize)) { throw new InvalidOperationException("Invalid size returned for Measure."); } DesiredSize = desiredSize; _previousMeasure = availableSize; Logger.TryGet(LogEventLevel.Verbose, LogArea.Layout)?.Log(this, "Measure requested {DesiredSize}", DesiredSize); if (DesiredSize != previousDesiredSize) { this.GetVisualParent<ILayoutable>()?.ChildDesiredSizeChanged(this); } } } /// <summary> /// Arranges the control and its children. /// </summary> /// <param name="rect">The control's new bounds.</param> public void Arrange(Rect rect) { if (IsInvalidRect(rect)) { throw new InvalidOperationException("Invalid Arrange rectangle."); } if (!IsMeasureValid) { Measure(_previousMeasure ?? rect.Size); } if (!IsArrangeValid || _previousArrange != rect) { Logger.TryGet(LogEventLevel.Verbose, LogArea.Layout)?.Log(this, "Arrange to {Rect} ", rect); IsArrangeValid = true; ArrangeCore(rect); _previousArrange = rect; } } /// <summary> /// Invalidates the measurement of the control and queues a new layout pass. /// </summary> public void InvalidateMeasure() { if (IsMeasureValid) { Logger.TryGet(LogEventLevel.Verbose, LogArea.Layout)?.Log(this, "Invalidated measure"); IsMeasureValid = false; IsArrangeValid = false; if (((ILayoutable)this).IsAttachedToVisualTree) { (VisualRoot as ILayoutRoot)?.LayoutManager.InvalidateMeasure(this); InvalidateVisual(); } OnMeasureInvalidated(); } } /// <summary> /// Invalidates the arrangement of the control and queues a new layout pass. /// </summary> public void InvalidateArrange() { if (IsArrangeValid) { Logger.TryGet(LogEventLevel.Verbose, LogArea.Layout)?.Log(this, "Invalidated arrange"); IsArrangeValid = false; (VisualRoot as ILayoutRoot)?.LayoutManager?.InvalidateArrange(this); InvalidateVisual(); } } /// <inheritdoc/> void ILayoutable.ChildDesiredSizeChanged(ILayoutable control) { if (!_measuring) { InvalidateMeasure(); } } void ILayoutable.EffectiveViewportChanged(EffectiveViewportChangedEventArgs e) { _effectiveViewportChanged?.Invoke(this, e); } /// <summary> /// Marks a property as affecting the control's measurement. /// </summary> /// <param name="properties">The properties.</param> /// <remarks> /// After a call to this method in a control's static constructor, any change to the /// property will cause <see cref="InvalidateMeasure"/> to be called on the element. /// </remarks> [Obsolete("Use AffectsMeasure<T> and specify the control type.")] protected static void AffectsMeasure(params AvaloniaProperty[] properties) { AffectsMeasure<Layoutable>(properties); } /// <summary> /// Marks a property as affecting the control's measurement. /// </summary> /// <typeparam name="T">The control which the property affects.</typeparam> /// <param name="properties">The properties.</param> /// <remarks> /// After a call to this method in a control's static constructor, any change to the /// property will cause <see cref="InvalidateMeasure"/> to be called on the element. /// </remarks> protected static void AffectsMeasure<T>(params AvaloniaProperty[] properties) where T : class, ILayoutable { void Invalidate(AvaloniaPropertyChangedEventArgs e) { (e.Sender as T)?.InvalidateMeasure(); } foreach (var property in properties) { property.Changed.Subscribe(Invalidate); } } /// <summary> /// Marks a property as affecting the control's arrangement. /// </summary> /// <param name="properties">The properties.</param> /// <remarks> /// After a call to this method in a control's static constructor, any change to the /// property will cause <see cref="InvalidateArrange"/> to be called on the element. /// </remarks> [Obsolete("Use AffectsArrange<T> and specify the control type.")] protected static void AffectsArrange(params AvaloniaProperty[] properties) { AffectsArrange<Layoutable>(properties); } /// <summary> /// Marks a property as affecting the control's arrangement. /// </summary> /// <typeparam name="T">The control which the property affects.</typeparam> /// <param name="properties">The properties.</param> /// <remarks> /// After a call to this method in a control's static constructor, any change to the /// property will cause <see cref="InvalidateArrange"/> to be called on the element. /// </remarks> protected static void AffectsArrange<T>(params AvaloniaProperty[] properties) where T : class, ILayoutable { void Invalidate(AvaloniaPropertyChangedEventArgs e) { (e.Sender as T)?.InvalidateArrange(); } foreach (var property in properties) { property.Changed.Subscribe(Invalidate); } } /// <summary> /// The default implementation of the control's measure pass. /// </summary> /// <param name="availableSize">The size available to the control.</param> /// <returns>The desired size for the control.</returns> /// <remarks> /// This method calls <see cref="MeasureOverride(Size)"/> which is probably the method you /// want to override in order to modify a control's arrangement. /// </remarks> protected virtual Size MeasureCore(Size availableSize) { if (IsVisible) { var margin = Margin; ApplyStyling(); ApplyTemplate(); var constrained = LayoutHelper.ApplyLayoutConstraints( this, availableSize.Deflate(margin)); var measured = MeasureOverride(constrained); var width = measured.Width; var height = measured.Height; { double widthCache = Width; if (!double.IsNaN(widthCache)) { width = widthCache; } } width = Math.Min(width, MaxWidth); width = Math.Max(width, MinWidth); { double heightCache = Height; if (!double.IsNaN(heightCache)) { height = heightCache; } } height = Math.Min(height, MaxHeight); height = Math.Max(height, MinHeight); width = Math.Min(width, availableSize.Width); height = Math.Min(height, availableSize.Height); if (UseLayoutRounding) { var scale = LayoutHelper.GetLayoutScale(this); width = LayoutHelper.RoundLayoutValue(width, scale); height = LayoutHelper.RoundLayoutValue(height, scale); } return NonNegative(new Size(width, height).Inflate(margin)); } else { return new Size(); } } /// <summary> /// Measures the control and its child elements as part of a layout pass. /// </summary> /// <param name="availableSize">The size available to the control.</param> /// <returns>The desired size for the control.</returns> protected virtual Size MeasureOverride(Size availableSize) { double width = 0; double height = 0; var visualChildren = VisualChildren; var visualCount = visualChildren.Count; for (var i = 0; i < visualCount; i++) { IVisual visual = visualChildren[i]; if (visual is ILayoutable layoutable) { layoutable.Measure(availableSize); width = Math.Max(width, layoutable.DesiredSize.Width); height = Math.Max(height, layoutable.DesiredSize.Height); } } return new Size(width, height); } /// <summary> /// The default implementation of the control's arrange pass. /// </summary> /// <param name="finalRect">The control's new bounds.</param> /// <remarks> /// This method calls <see cref="ArrangeOverride(Size)"/> which is probably the method you /// want to override in order to modify a control's arrangement. /// </remarks> protected virtual void ArrangeCore(Rect finalRect) { if (IsVisible) { var margin = Margin; var originX = finalRect.X + margin.Left; var originY = finalRect.Y + margin.Top; var availableSizeMinusMargins = new Size( Math.Max(0, finalRect.Width - margin.Left - margin.Right), Math.Max(0, finalRect.Height - margin.Top - margin.Bottom)); var horizontalAlignment = HorizontalAlignment; var verticalAlignment = VerticalAlignment; var size = availableSizeMinusMargins; var scale = LayoutHelper.GetLayoutScale(this); var useLayoutRounding = UseLayoutRounding; if (horizontalAlignment != HorizontalAlignment.Stretch) { size = size.WithWidth(Math.Min(size.Width, DesiredSize.Width - margin.Left - margin.Right)); } if (verticalAlignment != VerticalAlignment.Stretch) { size = size.WithHeight(Math.Min(size.Height, DesiredSize.Height - margin.Top - margin.Bottom)); } size = LayoutHelper.ApplyLayoutConstraints(this, size); if (useLayoutRounding) { size = LayoutHelper.RoundLayoutSize(size, scale, scale); availableSizeMinusMargins = LayoutHelper.RoundLayoutSize(availableSizeMinusMargins, scale, scale); } size = ArrangeOverride(size).Constrain(size); switch (horizontalAlignment) { case HorizontalAlignment.Center: case HorizontalAlignment.Stretch: originX += (availableSizeMinusMargins.Width - size.Width) / 2; break; case HorizontalAlignment.Right: originX += availableSizeMinusMargins.Width - size.Width; break; } switch (verticalAlignment) { case VerticalAlignment.Center: case VerticalAlignment.Stretch: originY += (availableSizeMinusMargins.Height - size.Height) / 2; break; case VerticalAlignment.Bottom: originY += availableSizeMinusMargins.Height - size.Height; break; } if (useLayoutRounding) { originX = LayoutHelper.RoundLayoutValue(originX, scale); originY = LayoutHelper.RoundLayoutValue(originY, scale); } Bounds = new Rect(originX, originY, size.Width, size.Height); } } /// <summary> /// Positions child elements as part of a layout pass. /// </summary> /// <param name="finalSize">The size available to the control.</param> /// <returns>The actual size used.</returns> protected virtual Size ArrangeOverride(Size finalSize) { var arrangeRect = new Rect(finalSize); var visualChildren = VisualChildren; var visualCount = visualChildren.Count; for (var i = 0; i < visualCount; i++) { IVisual visual = visualChildren[i]; if (visual is ILayoutable layoutable) { layoutable.Arrange(arrangeRect); } } return finalSize; } protected sealed override void InvalidateStyles() { base.InvalidateStyles(); InvalidateMeasure(); } protected override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTreeCore(e); if (e.Root is ILayoutRoot r) { if (_layoutUpdated is object) { r.LayoutManager.LayoutUpdated += LayoutManagedLayoutUpdated; } if (_effectiveViewportChanged is object) { r.LayoutManager.RegisterEffectiveViewportListener(this); } } } protected override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e) { if (e.Root is ILayoutRoot r) { if (_layoutUpdated is object) { r.LayoutManager.LayoutUpdated -= LayoutManagedLayoutUpdated; } if (_effectiveViewportChanged is object) { r.LayoutManager.UnregisterEffectiveViewportListener(this); } } base.OnDetachedFromVisualTreeCore(e); } /// <summary> /// Called by InvalidateMeasure /// </summary> protected virtual void OnMeasureInvalidated() { } /// <inheritdoc/> protected sealed override void OnVisualParentChanged(IVisual? oldParent, IVisual? newParent) { LayoutHelper.InvalidateSelfAndChildrenMeasure(this); base.OnVisualParentChanged(oldParent, newParent); } /// <summary> /// Called when the layout manager raises a LayoutUpdated event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private void LayoutManagedLayoutUpdated(object? sender, EventArgs e) => _layoutUpdated?.Invoke(this, e); /// <summary> /// Tests whether any of a <see cref="Rect"/>'s properties include negative values, /// a NaN or Infinity. /// </summary> /// <param name="rect">The rect.</param> /// <returns>True if the rect is invalid; otherwise false.</returns> private static bool IsInvalidRect(Rect rect) { return rect.Width < 0 || rect.Height < 0 || double.IsInfinity(rect.X) || double.IsInfinity(rect.Y) || double.IsInfinity(rect.Width) || double.IsInfinity(rect.Height) || double.IsNaN(rect.X) || double.IsNaN(rect.Y) || double.IsNaN(rect.Width) || double.IsNaN(rect.Height); } /// <summary> /// Tests whether any of a <see cref="Size"/>'s properties include negative values, /// a NaN or Infinity. /// </summary> /// <param name="size">The size.</param> /// <returns>True if the size is invalid; otherwise false.</returns> private static bool IsInvalidSize(Size size) { return size.Width < 0 || size.Height < 0 || double.IsInfinity(size.Width) || double.IsInfinity(size.Height) || double.IsNaN(size.Width) || double.IsNaN(size.Height); } /// <summary> /// Ensures neither component of a <see cref="Size"/> is negative. /// </summary> /// <param name="size">The size.</param> /// <returns>The non-negative size.</returns> private static Size NonNegative(Size size) { return new Size(Math.Max(size.Width, 0), Math.Max(size.Height, 0)); } } }
/* Licensed under the MIT/X11 license. * Copyright (c) 2011 Xamarin Inc. * Copyright 2013 Xamarin Inc * This notice may not be removed from any source distribution. * See license.txt for licensing detailed licensing details. */ using System; using System.ComponentModel; using System.Drawing; using System.Timers; using OpenTK; using OpenTK.Graphics; using OpenTK.Platform; using OpenTK.Platform.Android; using Android.Content; using Android.Util; using Android.Views; using Android.Runtime; using Java.Util; using OpenTK.Input; namespace OpenTK { [Register ("opentk_1_1/GameViewBase")] public abstract class GameViewBase : SurfaceView, IGameWindow { private IGraphicsContext graphicsContext; [Register (".ctor", "(Landroid/content/Context;)V", "")] public GameViewBase (Context context) : base (context) { } [Register (".ctor", "(Landroid/content/Context;Landroid/util/AttributeSet;)V", "")] public GameViewBase (Context context, IAttributeSet attrs) : base (context, attrs) { } public GameViewBase (IntPtr handle, global::Android.Runtime.JniHandleOwnership transfer) : base (handle, transfer) { } /// <summary> /// Gets the <see cref="T:OpenTK.Graphics.IGraphicsContext" /> instance /// bound to this /// <see cref="T:OpenTK.Platform.Android.AndroidGameView" /> instance. /// </summary> /// <value> /// A <see cref="T:OpenTK.Graphics.IGraphicsContext" /> instance bound /// to this <see cref="T:OpenTK.Platform.Android.AndroidGameView" /> /// instance. /// </value> public IGraphicsContext GraphicsContext { get { return graphicsContext; } protected set { graphicsContext = value; OnContextSet (null); } } /// <summary> /// Controls whether the graphics context is recreated when the display /// size changes. /// </summary> /// <remarks> /// </remarks> public bool AutoResize { get; set; } protected virtual void CreateFrameBuffer () { } Point INativeWindow.PointToClient (Point point) { return point; } Point INativeWindow.PointToScreen (Point point) { return point; } /// <summary> /// Occurs before the run loop starts. /// </summary> /// <remarks> /// <para> /// When using the run-loop processing architecture, events happen in /// the following order: /// </para> /// <list type="number"> /// <item> /// <term> /// <c>Load</c> /// </term> /// </item> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" /> /// </term> /// </item> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// </term> /// </item> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Unload" /> /// </term> /// </item> /// </list> /// <para> /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Run" /> and /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Run(System.Double)" />, /// invoke /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Load" /> /// before starting the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" />/<see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// loop which is invoked for every rendered frame. /// </para> /// <para> /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Stop" /> /// ends the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" />/<see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// loop processing, then invokes the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Unload" /> /// event. /// </para> /// </remarks> public event EventHandler<EventArgs> Load; /// <param name="e"> /// An <see cref="T:System.EventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Load" /> /// event. /// </summary> protected virtual void OnLoad (EventArgs e) { if (Load != null) Load (this, e); } /// <summary> /// Occurs when the run-loop is terminated. /// </summary> /// <remarks> /// <para> /// When using the run-loop processing architecture, events happen in /// the following order: /// </para> /// <list type="number"> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Load" /> /// </term> /// </item> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" /> /// </term> /// </item> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// </term> /// </item> /// <item> /// <term> /// <c>Unload</c> /// </term> /// </item> /// </list> /// <para> /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Run" /> and /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Run(System.Double)" />, /// invoke /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Load" /> /// before starting the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" />/<see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// loop which is invoked for every rendered frame. /// </para> /// <para> /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Stop" /> /// ends the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" />/<see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// loop processing, then invokes the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Unload" /> /// event. /// </para> /// </remarks> public event EventHandler<EventArgs> Unload; /// <param name="e"> /// An <see cref="T:System.EventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Unload" /> /// event. /// </summary> /// <remarks> /// <para> /// The <c>OnUnload</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnUnload</c> in a derived class, be sure to /// call the base class's <c>OnUnload</c> method so that registered /// delegates receive the event. /// </block> /// </remarks> protected virtual void OnUnload (EventArgs e) { if (Unload != null) Unload (this, e); } /// <summary> /// Occurs part of run-loop processing when a frame should be updated prior to rendering. /// </summary> /// <remarks> /// <para> /// When using the run-loop processing architecture, events happen in /// the following order: /// </para> /// <list type="number"> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Load" /> /// </term> /// </item> /// <item> /// <term> /// <c>UpdateFrame</c> /// </term> /// </item> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// </term> /// </item> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Unload" /> /// </term> /// </item> /// </list> /// <para> /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Run" /> and /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Run(System.Double)" />, /// invoke /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Load" /> /// before starting the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" />/<see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// loop which is invoked for every rendered frame. /// </para> /// <para> /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Stop" /> /// ends the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" />/<see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// loop processing, then invokes the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Unload" /> /// event. /// </para> /// </remarks> public event EventHandler<FrameEventArgs> UpdateFrame; /// <param name="e"> /// An <see cref="T:OpenTK.FrameEventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" /> /// event. /// </summary> /// <remarks> /// <para> /// The <c>OnUpdateFrame</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnUpdateFrame</c> in a derived class, be sure to /// call the base class's <c>OnUpdateFrame</c> method so that registered /// delegates receive the event. /// </block> /// </remarks> protected virtual void OnUpdateFrame (FrameEventArgs e) { if (UpdateFrame != null) UpdateFrame (this, e); } /// <summary> /// Occurs part of run-loop processing when a frame should be rendered. /// </summary> /// <remarks> /// <para> /// When using the run-loop processing architecture, events happen in /// the following order: /// </para> /// <list type="number"> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Load" /> /// </term> /// </item> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" /> /// </term> /// </item> /// <item> /// <term> /// <c>RenderFrame</c> /// </term> /// </item> /// <item> /// <term> /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Unload" /> /// </term> /// </item> /// </list> /// <para> /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Run" /> and /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Run(System.Double)" />, /// invoke /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Load" /> /// before starting the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" />/<see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// loop which is invoked for every rendered frame. /// </para> /// <para> /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Stop" /> /// ends the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" />/<see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// loop processing, then invokes the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Unload" /> /// event. /// </para> /// </remarks> public event EventHandler<FrameEventArgs> RenderFrame; /// <param name="e"> /// An <see cref="T:OpenTK.FrameEventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// event. /// </summary> /// <remarks> /// <para> /// The <c>OnRenderFrame</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnRenderFrame</c> in a derived class, be sure to /// call the base class's <c>OnRenderFrame</c> method so that registered /// delegates receive the event. /// </block> /// </remarks> protected virtual void OnRenderFrame (FrameEventArgs e) { if (RenderFrame != null) RenderFrame (this, e); } /// <summary> /// Starts as-fast-as-possible run-loop processing. /// </summary> /// <remarks> /// <para> /// In this <c>Run</c> overload, there is no delay between raising of the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderFrame" /> /// event and the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.UpdateFrame" /> /// of the following frame; everything is executed as quickly as /// possible. This may not be desirable. /// </para> /// </remarks> /// <exception cref="T:System.ObjectDisposedException"> /// The instance has had /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Dispose" /> /// invoked on it. /// </exception> public abstract void Run (); /// <param name="updateRate"> /// A <see cref="T:System.Double" /> containing the number of frames per /// second that should be updated and rendered. /// </param> /// <summary> /// Starts run-loop processing at a rate of <paramref name="updateRate" /> /// frames per second. /// </summary> /// <exception cref="T:System.ObjectDisposedException"> /// The instance has had /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Dispose" /> /// invoked on it. /// </exception> public abstract void Run (double updateRate); /// <summary> /// Makes the /// <see cref="P:OpenTK.Platform.Android.AndroidGameView.GraphicsContext" /> /// current on the calling thread. /// </summary> /// <remarks> /// <para> /// This method is equivalent to calling: /// <c>GraphicsContext.MakeCurrent(WindowInfo)</c>. /// </para> /// </remarks> /// <exception cref="T:System.ObjectDisposedException"> /// The instance has had /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Dispose" /> /// invoked on it. /// </exception> public abstract void MakeCurrent (); /// <summary> /// Swaps the front and back buffers of the current GraphicsContext, /// presenting the rendered scene to the user. /// </summary> /// <remarks> /// <para> /// This method rebinds /// <see cref="P:OpenTK.Platform.Android.AndroidGameView.Renderbuffer" /> /// to the OpenGL context's <c>RenderbufferOes</c> property, then /// invokes <see cref="M:OpenTK.Graphics.IGraphicsContext.SwapBuffers" />. /// </para> /// </remarks> /// <exception cref="T:System.ObjectDisposedException"> /// The instance has had /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Dispose" /> /// invoked on it. /// </exception> public abstract void SwapBuffers (); /// <summary>This member is not supported.</summary> /// <value>To be added.</value> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public event EventHandler<EventArgs> Move; /// <summary> /// Occurs when the view's /// <see cref="P:OpenTK.Platform.Android.AndroidGameView.Size" /> /// changes. /// </summary> /// <remarks> /// </remarks> public event EventHandler<EventArgs> Resize; /// <param name="e"> /// An <see cref="T:System.EventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Resize" /> /// event. /// </summary> /// <remarks> /// <para> /// The <c>OnResize</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnResize</c> in a derived class, be sure to /// call the base class's <c>OnResize</c> method so that registered /// delegates receive the event. /// </block> /// </remarks> protected virtual void OnResize (EventArgs e) { if (Resize != null) Resize (this, e); } /// <summary>This member is not supported.</summary> /// <value>To be added.</value> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public event EventHandler<CancelEventArgs> Closing; /// <summary> /// Occurs when the view has been closed. /// </summary> /// <remarks> /// </remarks> public event EventHandler<EventArgs> Closed; /// <param name="e"> /// An <see cref="T:System.EventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Closed" /> /// event. /// </summary> /// <remarks> /// <para> /// The <c>OnClosed</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnClosed</c> in a derived class, be sure to /// call the base class's <c>OnClosed</c> method so that registered /// delegates receive the event. /// </block> /// </remarks> protected virtual void OnClosed (EventArgs e) { if (Closed != null) Closed (this, e); } /// <summary> /// Occurs when the view is disposed /// </summary> /// <remarks> /// </remarks> public event EventHandler<EventArgs> Disposed; /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.Disposed" /> /// event. /// </summary> /// <param name="e"> /// An <see cref="T:System.EventArgs" /> that contains the event data. /// </param> /// <remarks> /// <para> /// The <c>OnDisposed</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnDisposed</c> in a derived class, be sure to /// call the base class's <c>OnDisposed</c> method so that registered /// delegates receive the event. /// </block> /// </remarks> protected virtual void OnDisposed (EventArgs e) { if (Disposed != null) Disposed (this, e); } /// <summary> /// Occurs when the /// <see cref="T:OpenTK.Platform.Android.AndroidGameView" /> /// detects that the <see cref="P:OpenTK.Platform.Android.AndroidGameView.GraphicsContext"> was lost. /// </summary> /// <remarks> /// </remarks> public event EventHandler<EventArgs> ContextLost; /// <param name="e"> /// An <see cref="T:System.EventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.ContextLost" /> /// event. /// </summary> /// <remarks> /// <para> /// The <c>OnContextLost</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnContextLost</c> in a derived class, be sure to /// call the base class's <c>OnContextLost</c> method so that registered /// delegates receive the event. /// </block> /// </remarks> protected virtual void OnContextLost (EventArgs e) { if (ContextLost != null) ContextLost (this, e); } /// <summary> /// Occurs when the /// <see cref="P:OpenTK.Platform.Android.AndroidGameView.GraphicsContext" /> /// is created. /// </summary> /// <remarks> /// </remarks> public event EventHandler<EventArgs> ContextSet; /// <param name="e"> /// An <see cref="T:System.EventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.ContextSet" /> /// event. /// </summary> /// <remarks> /// <para> /// The <c>OnContextSet</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnContextSet</c> in a derived class, be sure to /// call the base class's <c>OnContextSet</c> method so that registered /// delegates receive the event. /// </block> /// <block> /// It is convenient place to create context related data, ie. load textures. /// </block> /// </remarks> protected virtual void OnContextSet (EventArgs e) { if (ContextSet != null) ContextSet (this, e); } /// <summary> /// Occurs when the separate rendering thread exits without cancelation request. /// </summary> /// <remarks> /// </remarks> public event EventHandler<EventArgs> RenderThreadExited; /// <param name="e"> /// An <see cref="T:System.EventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.RenderThreadExited" /> /// event. /// </summary> /// <remarks> /// <para> /// The <c>OnRenderThreadExited</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnRenderThreadExited</c> in a derived class, be sure to /// call the base class's <c>OnRenderThreadExited</c> method so that registered /// delegates receive the event. /// </block> /// <block> /// It is convenient place to handle errors. /// </block> /// </remarks> protected virtual void OnRenderThreadExited (EventArgs e) { if (RenderThreadExited != null) RenderThreadExited (this, e); } /// <summary> /// Occurs when the value of /// <see cref="P:OpenTK.Platform.Android.AndroidGameView.Title" /> /// changes. /// </summary> /// <remarks> /// </remarks> public event EventHandler<EventArgs> TitleChanged; /// <param name="e"> /// An <see cref="T:System.EventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.TitleChanged" /> /// event. /// </summary> /// <remarks> /// <para> /// The <c>OnTitleChanged</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnTitleChanged</c> in a derived class, be sure to /// call the base class's <c>OnTitleChanged</c> method so that registered /// delegates receive the event. /// </block> /// </remarks> protected virtual void OnTitleChanged (EventArgs e) { if (TitleChanged != null) TitleChanged (this, EventArgs.Empty); } /// <summary> /// Occurs when the value of /// <see cref="P:OpenTK.Platform.Android.AndroidGameView.Visible" /> /// changes. /// </summary> /// <remarks> /// </remarks> public event EventHandler<EventArgs> VisibleChanged; /// <param name="e"> /// An <see cref="T:System.EventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.VisibleChanged" /> /// event. /// </summary> /// <remarks> /// <para> /// The <c>OnVisibleChanged</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnVisibleChanged</c> in a derived class, be sure to /// call the base class's <c>OnVisibleChanged</c> method so that registered /// delegates receive the event. /// </block> /// </remarks> protected virtual void OnVisibleChanged (EventArgs e) { if (VisibleChanged != null) VisibleChanged (this, EventArgs.Empty); } /// <summary>This member is not supported.</summary> /// <value>To be added.</value> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public event EventHandler<EventArgs> FocusedChanged; /// <summary>This member is not supported.</summary> /// <value>To be added.</value> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public event EventHandler<EventArgs> WindowBorderChanged; /// <summary> /// Occurs when the value of /// <see cref="P:OpenTK.Platform.Android.AndroidGameView.WindowState" /> /// changes. /// </summary> /// <remarks> /// </remarks> public event EventHandler<EventArgs> WindowStateChanged; /// <param name="e"> /// An <see cref="T:System.EventArgs" /> that contains the event data. /// </param> /// <summary> /// Raises the /// <see cref="E:OpenTK.Platform.Android.AndroidGameView.WindowStateChanged" /> /// event. /// </summary> /// <remarks> /// <para> /// The <c>OnWindowStateChanged</c> method also allows derived classes to handle /// the event without attaching a delegate. This is the preferred /// technique for handling the event in a derived class. /// </para> /// <block subset="none" type="overrides"> /// When overriding <c>OnWindowStateChanged</c> in a derived class, be sure to /// call the base class's <c>OnWindowStateChanged</c> method so that registered /// delegates receive the event. /// </block> /// </remarks> protected virtual void OnWindowStateChanged (EventArgs e) { if (WindowStateChanged != null) WindowStateChanged (this, EventArgs.Empty); } /// <summary> /// Invokes the /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.OnClosed(System.EventArgs)" /> /// event. /// </summary> /// <remarks> /// This method only invokes the /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.OnClosed(System.EventArgs)" /> /// method. /// </remarks> /// <exception cref="T:System.ObjectDisposedException"> /// The instance has had /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Dispose" /> /// invoked on it. /// </exception> public virtual void Close () { OnClosed (EventArgs.Empty); } /// <summary>This member is not supported.</summary> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> event EventHandler<KeyPressEventArgs> INativeWindow.KeyPress { add { throw new NotSupportedException (); } remove { throw new NotSupportedException (); } } public virtual int Width { get; set; } public virtual int Height { get; set; } /// <summary>This member is not supported.</summary> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public event EventHandler<EventArgs> MouseEnter { add { throw new NotSupportedException (); } remove { throw new NotSupportedException (); } } /// <summary>This member is not supported.</summary> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public event EventHandler<EventArgs> MouseLeave { add { throw new NotSupportedException (); } remove { throw new NotSupportedException (); } } /// <summary>This member is not supported.</summary> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public void ProcessEvents () { throw new NotImplementedException (); } public Point PointToClient (Point point) { throw new NotImplementedException (); } public Point PointToScreen (Point point) { throw new NotImplementedException (); } public string Title { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } /// <summary>This member is not supported.</summary> /// <value>To be added.</value> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public bool Focused { get { throw new NotSupportedException (); } } /// <summary> /// Gets or sets a value specifying whether the view is visible. /// </summary> /// <value> /// A <see cref="T:System.Boolean" /> specifying whether the view is /// visible. /// </value> /// <remarks> /// </remarks> /// <exception cref="T:System.ObjectDisposedException"> /// The instance has had /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Dispose" /> /// invoked on it. /// </exception> public bool Visible { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } /// <summary>This member is not supported.</summary> /// <value>To be added.</value> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotImplementedException" />. /// </para> /// </remarks> public bool Exists { get { throw new NotImplementedException (); } } /// <summary> /// Gets information about the containing window. /// </summary> /// <value> /// A <see cref="T:OpenTK.Platform.IWindowInfo" /> which provides /// information about the containing window. /// </value> /// <exception cref="T:System.ObjectDisposedException"> /// The instance has had /// <see cref="M:OpenTK.Platform.Android.AndroidGameView.Dispose" /> /// invoked on it. /// </exception> public virtual IWindowInfo WindowInfo { get { throw new NotImplementedException (); } } /// <summary> /// Gets or states the state of the view. /// </summary> /// <value> /// A <see cref="T:OpenTK.WindowState" /> value specifying the state of /// the window. /// </value> /// <remarks> /// <para> /// <see cref="F:OpenTK.WindowState.Normal" /> is always returned. /// </para> /// </remarks> /// <exception cref="T:System.NotImplementedException"> /// </exception> public virtual WindowState WindowState { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } /// <summary> /// Always returns <see cref="F:OpenTK.WindowBorder.Hidden" />. /// </summary> /// <value> /// A <see cref="T:OpenTK.WindowBorder" /> value controlling the border /// of the view. /// </value> /// <remarks> /// <para> /// Always returns <see cref="F:OpenTK.WindowBorder.Hidden" />. /// </para> /// <para> /// The setter is ignored. /// </para> /// </remarks> /// <exception cref="T:System.NotImplementedException"> /// </exception> public virtual WindowBorder WindowBorder { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } /// <summary>This member is not supported.</summary> /// <value>To be added.</value> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotImplementedException" />. /// </para> /// </remarks> public virtual Rectangle Bounds { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } /// <summary>This member is not supported.</summary> /// <value>To be added.</value> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotImplementedException" />. /// </para> /// </remarks> public virtual Point Location { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } /// <summary> /// The size of the current view. /// </summary> /// <value> /// A <see cref="T:System.Drawing.Size" /> which is the size of the /// current view. /// </value> /// <exception cref="T:System.NotImplementedException"> /// </exception> public virtual Size Size { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } /// <summary>This member is not supported.</summary> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public int X { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } /// <summary>This member is not supported.</summary> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public int Y { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } /// <summary>This member is not supported.</summary> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public Rectangle ClientRectangle { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } /// <summary>This member is not supported.</summary> /// <value>To be added.</value> /// <remarks> /// <para> /// Throws a <see cref="T:System.NotSupportedException" />. /// </para> /// </remarks> public Size ClientSize { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } MouseCursor INativeWindow.Cursor { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } bool INativeWindow.CursorVisible { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } Icon INativeWindow.Icon { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } event EventHandler<EventArgs> INativeWindow.IconChanged { add { throw new NotSupportedException(); } remove { throw new NotSupportedException(); } } event EventHandler<KeyboardKeyEventArgs> INativeWindow.KeyDown { add { throw new NotSupportedException(); } remove { throw new NotSupportedException(); } } event EventHandler<KeyboardKeyEventArgs> INativeWindow.KeyUp { add { throw new NotSupportedException(); } remove { throw new NotSupportedException(); } } event EventHandler<MouseButtonEventArgs> INativeWindow.MouseDown { add { throw new NotSupportedException(); } remove { throw new NotSupportedException(); } } event EventHandler<MouseMoveEventArgs> INativeWindow.MouseMove { add { throw new NotSupportedException(); } remove { throw new NotSupportedException(); } } event EventHandler<MouseButtonEventArgs> INativeWindow.MouseUp { add { throw new NotSupportedException(); } remove { throw new NotSupportedException(); } } event EventHandler<MouseWheelEventArgs> INativeWindow.MouseWheel { add { throw new NotSupportedException(); } remove { throw new NotSupportedException(); } } event EventHandler<FileDropEventArgs> INativeWindow.FileDrop { add { throw new NotSupportedException(); } remove { throw new NotSupportedException(); } } } }
/* * 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.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications.Cache; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory { public class AvatarFactoryModule : IAvatarFactory, IRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene = null; private static readonly AvatarAppearance def = new AvatarAppearance(); public bool TryGetAvatarAppearance(UUID avatarId, out AvatarAppearance appearance) { CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(avatarId); //if ((profile != null) && (profile.RootFolder != null)) if (profile != null) { appearance = m_scene.CommsManager.AvatarService.GetUserAppearance(avatarId); if (appearance != null) { //SetAppearanceAssets(profile, ref appearance); //m_log.DebugFormat("[APPEARANCE]: Found : {0}", appearance.ToString()); return true; } } appearance = CreateDefault(avatarId); m_log.ErrorFormat("[APPEARANCE]: Appearance not found for {0}, creating default", avatarId); return false; } private AvatarAppearance CreateDefault(UUID avatarId) { AvatarAppearance appearance = null; AvatarWearable[] wearables; byte[] visualParams; GetDefaultAvatarAppearance(out wearables, out visualParams); appearance = new AvatarAppearance(avatarId, wearables, visualParams); return appearance; } public void Initialise(Scene scene, IConfigSource source) { scene.RegisterModuleInterface<IAvatarFactory>(this); scene.EventManager.OnNewClient += NewClient; if (m_scene == null) { m_scene = scene; } } public void PostInitialise() { } public void Close() { } public string Name { get { return "Default Avatar Factory"; } } public bool IsSharedModule { get { return false; } } public void NewClient(IClientAPI client) { client.OnAvatarNowWearing += AvatarIsWearing; } public void RemoveClient(IClientAPI client) { // client.OnAvatarNowWearing -= AvatarIsWearing; } public void SetAppearanceAssets(UUID userID, ref AvatarAppearance appearance) { IInventoryService invService = m_scene.InventoryService; if (invService.GetRootFolder(userID) != null) { for (int i = 0; i < 13; i++) { if (appearance.Wearables[i].ItemID == UUID.Zero) { appearance.Wearables[i].AssetID = UUID.Zero; } else { InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i].ItemID, userID); baseItem = invService.GetItem(baseItem); if (baseItem != null) { appearance.Wearables[i].AssetID = baseItem.AssetID; } else { m_log.ErrorFormat("[APPEARANCE]: Can't find inventory item {0}, setting to default", appearance.Wearables[i].ItemID); appearance.Wearables[i].AssetID = def.Wearables[i].AssetID; } } } } else { m_log.WarnFormat("[APPEARANCE]: user {0} has no inventory, appearance isn't going to work", userID); } } /// <summary> /// Update what the avatar is wearing using an item from their inventory. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void AvatarIsWearing(Object sender, AvatarWearingArgs e) { IClientAPI clientView = (IClientAPI)sender; ScenePresence avatar = m_scene.GetScenePresence(clientView.AgentId); if (avatar == null) { m_log.Error("[APPEARANCE]: Avatar is child agent, ignoring AvatarIsWearing event"); return; } AvatarAppearance avatAppearance = null; if (!TryGetAvatarAppearance(clientView.AgentId, out avatAppearance)) { m_log.Warn("[APPEARANCE]: We didn't seem to find the appearance, falling back to ScenePresence"); avatAppearance = avatar.Appearance; } //m_log.DebugFormat("[APPEARANCE]: Received wearables for {0}", clientView.Name); foreach (AvatarWearingArgs.Wearable wear in e.NowWearing) { if (wear.Type < 13) { avatAppearance.Wearables[wear.Type].ItemID = wear.ItemID; } } SetAppearanceAssets(avatar.UUID, ref avatAppearance); m_scene.CommsManager.AvatarService.UpdateUserAppearance(clientView.AgentId, avatAppearance); avatar.Appearance = avatAppearance; } public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams) { visualParams = GetDefaultVisualParams(); wearables = AvatarWearable.DefaultWearables; } public void UpdateDatabase(UUID user, AvatarAppearance appearance) { m_scene.CommsManager.AvatarService.UpdateUserAppearance(user, appearance); } private static byte[] GetDefaultVisualParams() { byte[] visualParams; visualParams = new byte[218]; for (int i = 0; i < 218; i++) { visualParams[i] = 100; } return visualParams; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Sockets; namespace System.Net.NetworkInformation { internal enum IcmpV6StatType { DestinationUnreachable = 1, PacketTooBig = 2, TimeExceeded = 3, ParameterProblem = 4, EchoRequest = 128, EchoReply = 129, MembershipQuery = 130, MembershipReport = 131, MembershipReduction = 132, RouterSolicit = 133, RouterAdvertisement = 134, NeighborSolict = 135, NeighborAdvertisement = 136, Redirect = 137, } // ICMP statistics for Ipv6. internal class SystemIcmpV6Statistics : IcmpV6Statistics { private readonly Interop.IpHlpApi.MibIcmpInfoEx _stats; internal SystemIcmpV6Statistics() { uint result = Interop.IpHlpApi.GetIcmpStatisticsEx(out _stats, AddressFamily.InterNetworkV6); if (result != Interop.IpHlpApi.ERROR_SUCCESS) { throw new NetworkInformationException((int)result); } } public override long MessagesSent { get { return (long)_stats.outStats.dwMsgs; } } public override long MessagesReceived { get { return (long)_stats.inStats.dwMsgs; } } public override long ErrorsSent { get { return (long)_stats.outStats.dwErrors; } } public override long ErrorsReceived { get { return (long)_stats.inStats.dwErrors; } } public override long DestinationUnreachableMessagesSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.DestinationUnreachable]; } } public override long DestinationUnreachableMessagesReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.DestinationUnreachable]; } } public override long PacketTooBigMessagesSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.PacketTooBig]; } } public override long PacketTooBigMessagesReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.PacketTooBig]; } } public override long TimeExceededMessagesSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.TimeExceeded]; } } public override long TimeExceededMessagesReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.TimeExceeded]; } } public override long ParameterProblemsSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.ParameterProblem]; } } public override long ParameterProblemsReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.ParameterProblem]; } } public override long EchoRequestsSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.EchoRequest]; } } public override long EchoRequestsReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.EchoRequest]; } } public override long EchoRepliesSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.EchoReply]; } } public override long EchoRepliesReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.EchoReply]; } } public override long MembershipQueriesSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.MembershipQuery]; } } public override long MembershipQueriesReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.MembershipQuery]; } } public override long MembershipReportsSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.MembershipReport]; } } public override long MembershipReportsReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.MembershipReport]; } } public override long MembershipReductionsSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.MembershipReduction]; } } public override long MembershipReductionsReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.MembershipReduction]; } } public override long RouterAdvertisementsSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.RouterAdvertisement]; } } public override long RouterAdvertisementsReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.RouterAdvertisement]; } } public override long RouterSolicitsSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.RouterSolicit]; } } public override long RouterSolicitsReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.RouterSolicit]; } } public override long NeighborAdvertisementsSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.NeighborAdvertisement]; } } public override long NeighborAdvertisementsReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.NeighborAdvertisement]; } } public override long NeighborSolicitsSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.NeighborSolict]; } } public override long NeighborSolicitsReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.NeighborSolict]; } } public override long RedirectsSent { get { return _stats.outStats.rgdwTypeCount[(long)IcmpV6StatType.Redirect]; } } public override long RedirectsReceived { get { return _stats.inStats.rgdwTypeCount[(long)IcmpV6StatType.Redirect]; } } } }
/* * 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 Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; /***************************************************** * * ScriptsHttpRequests * * Implements the llHttpRequest and http_response * callback. * * Some stuff was already in LSLLongCmdHandler, and then * there was this file with a stub class in it. So, * I am moving some of the objects and functions out of * LSLLongCmdHandler, such as the HttpRequestClass, the * start and stop methods, and setting up pending and * completed queues. These are processed in the * LSLLongCmdHandler polling loop. Similiar to the * XMLRPCModule, since that seems to work. * * //TODO * * This probably needs some throttling mechanism but * it's wide open right now. This applies to both * number of requests and data volume. * * Linden puts all kinds of header fields in the requests. * Not doing any of that: * User-Agent * X-SecondLife-Shard * X-SecondLife-Object-Name * X-SecondLife-Object-Key * X-SecondLife-Region * X-SecondLife-Local-Position * X-SecondLife-Local-Velocity * X-SecondLife-Local-Rotation * X-SecondLife-Owner-Name * X-SecondLife-Owner-Key * * HTTPS support * * Configurable timeout? * Configurable max response size? * Configurable * * **************************************************/ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HttpRequestModule")] public class HttpRequestModule : ISharedRegionModule, IHttpRequestModule { private int httpTimeout = 30000; private string m_name = "HttpScriptRequests"; private string m_proxyurl = ""; private string m_proxyexcepts = ""; // <request id, HttpRequestClass> private ThreadedClasses.RwLockedDictionary<UUID, HttpRequestClass> m_pendingRequests = new ThreadedClasses.RwLockedDictionary<UUID, HttpRequestClass>(); private Scene m_scene; // private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>(); public HttpRequestModule() { ServicePointManager.ServerCertificateValidationCallback +=ValidateServerCertificate; } public static bool ValidateServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // If this is a web request we need to check the headers first // We may want to ignore SSL if (sender is HttpWebRequest) { HttpWebRequest Request = (HttpWebRequest)sender; ServicePoint sp = Request.ServicePoint; // We don't case about encryption, get out of here if (Request.Headers.Get("NoVerifyCert") != null) { return true; } // If there was an upstream cert verification error, bail if ((((int)sslPolicyErrors) & ~4) != 0) return false; // Check for policy and execute it if defined if (ServicePointManager.CertificatePolicy != null) { return ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, Request, 0); } return true; } // If it's not HTTP, trust .NET to check it if ((((int)sslPolicyErrors) & ~4) != 0) return false; return true; } #region IHttpRequestModule Members public UUID MakeHttpRequest(string url, string parameters, string body) { return UUID.Zero; } public UUID StartHttpRequest(uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body) { UUID reqID = UUID.Random(); HttpRequestClass htc = new HttpRequestClass(); // Partial implementation: support for parameter flags needed // see http://wiki.secondlife.com/wiki/LlHTTPRequest // // Parameters are expected in {key, value, ... , key, value} if (parameters != null) { string[] parms = parameters.ToArray(); for (int i = 0; i < parms.Length; i += 2) { switch (Int32.Parse(parms[i])) { case (int)HttpRequestConstants.HTTP_METHOD: htc.HttpMethod = parms[i + 1]; break; case (int)HttpRequestConstants.HTTP_MIMETYPE: htc.HttpMIMEType = parms[i + 1]; break; case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH: // TODO implement me break; case (int)HttpRequestConstants.HTTP_VERIFY_CERT: htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0); break; case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE: // TODO implement me break; case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER: //Parameters are in pairs and custom header takes //arguments in pairs so adjust for header marker. ++i; //Maximum of 8 headers are allowed based on the //Second Life documentation for llHTTPRequest. for (int count = 1; count <= 8; ++count) { //Not enough parameters remaining for a header? if (parms.Length - i < 2) break; //Have we reached the end of the list of headers? //End is marked by a string with a single digit. //We already know we have at least one parameter //so it is safe to do this check at top of loop. if (Char.IsDigit(parms[i][0])) break; if (htc.HttpCustomHeaders == null) htc.HttpCustomHeaders = new List<string>(); htc.HttpCustomHeaders.Add(parms[i]); htc.HttpCustomHeaders.Add(parms[i+1]); i += 2; } break; case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE: htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0); break; } } } htc.LocalID = localID; htc.ItemID = itemID; htc.Url = url; htc.ReqID = reqID; htc.HttpTimeout = httpTimeout; htc.OutboundBody = body; htc.ResponseHeaders = headers; htc.proxyurl = m_proxyurl; htc.proxyexcepts = m_proxyexcepts; m_pendingRequests.Add(reqID, htc); htc.Process(); return reqID; } public void StopHttpRequestsForScript(UUID id) { List<UUID> keysToRemove = new List<UUID>(); m_pendingRequests.ForEach(delegate(HttpRequestClass req) { if (req.ItemID == id) { req.Stop(); keysToRemove.Add(req.ReqID); } }); keysToRemove.ForEach(keyToRemove => m_pendingRequests.Remove(keyToRemove)); } /* * TODO * Not sure how important ordering is is here - the next first * one completed in the list is returned, based soley on its list * position, not the order in which the request was started or * finished. I thought about setting up a queue for this, but * it will need some refactoring and this works 'enough' right now */ public IServiceRequest GetNextCompletedRequest() { try { m_pendingRequests.ForEach(delegate(HttpRequestClass req) { if (req.Finished) throw new ThreadedClasses.ReturnValueException<HttpRequestClass>(req); }); } catch(ThreadedClasses.ReturnValueException<HttpRequestClass> e) { return e.Value; } return null; } public void RemoveCompletedRequest(UUID id) { HttpRequestClass tmpReq; if (m_pendingRequests.TryGetValue(id, out tmpReq)) { tmpReq.Stop(); tmpReq = null; m_pendingRequests.Remove(id); } } #endregion #region ISharedRegionModule Members public void Initialise(IConfigSource config) { m_proxyurl = config.Configs["Startup"].GetString("HttpProxy"); m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions"); } public void AddRegion(Scene scene) { m_scene = scene; m_scene.RegisterModuleInterface<IHttpRequestModule>(this); } public void RemoveRegion(Scene scene) { scene.UnregisterModuleInterface<IHttpRequestModule>(this); if (scene == m_scene) m_scene = null; } public void PostInitialise() { } public void RegionLoaded(Scene scene) { } public void Close() { } public string Name { get { return m_name; } } public Type ReplaceableInterface { get { return null; } } #endregion } public class HttpRequestClass: IServiceRequest { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // Constants for parameters // public const int HTTP_BODY_MAXLENGTH = 2; // public const int HTTP_METHOD = 0; // public const int HTTP_MIMETYPE = 1; // public const int HTTP_VERIFY_CERT = 3; // public const int HTTP_VERBOSE_THROTTLE = 4; // public const int HTTP_CUSTOM_HEADER = 5; // public const int HTTP_PRAGMA_NO_CACHE = 6; private bool _finished; public bool Finished { get { return _finished; } } // public int HttpBodyMaxLen = 2048; // not implemented // Parameter members and default values public string HttpMethod = "GET"; public string HttpMIMEType = "text/plain;charset=utf-8"; public int HttpTimeout; public bool HttpVerifyCert = true; //public bool HttpVerboseThrottle = true; // not implemented public List<string> HttpCustomHeaders = null; public bool HttpPragmaNoCache = true; // Request info private UUID _itemID; public UUID ItemID { get { return _itemID; } set { _itemID = value; } } private uint _localID; public uint LocalID { get { return _localID; } set { _localID = value; } } public DateTime Next; public string proxyurl; public string proxyexcepts; public string OutboundBody; private UUID _reqID; public UUID ReqID { get { return _reqID; } set { _reqID = value; } } public WebRequest Request; public string ResponseBody; public List<string> ResponseMetadata; public Dictionary<string, string> ResponseHeaders; public int Status; public string Url; public void Process() { SendRequest(); } public void SendRequest() { try { ServicePointManagerTimeoutSupport.ResetHosts(); Request = WebRequest.Create(Url); Request.Method = HttpMethod; Request.ContentType = HttpMIMEType; if (!HttpVerifyCert) { // We could hijack Connection Group Name to identify // a desired security exception. But at the moment we'll use a dummy header instead. // Request.ConnectionGroupName = "NoVerify"; Request.Headers.Add("NoVerifyCert", "true"); } // else // { // Request.ConnectionGroupName="Verify"; // } if (!HttpPragmaNoCache) { Request.Headers.Add("Pragma", "no-cache"); } if (HttpCustomHeaders != null) { for (int i = 0; i < HttpCustomHeaders.Count; i += 2) Request.Headers.Add(HttpCustomHeaders[i], HttpCustomHeaders[i+1]); } if (!string.IsNullOrEmpty(proxyurl)) { if (!string.IsNullOrEmpty(proxyexcepts)) { string[] elist = proxyexcepts.Split(';'); Request.Proxy = new WebProxy(proxyurl, true, elist); } else { Request.Proxy = new WebProxy(proxyurl, true); } } if (ResponseHeaders != null) { foreach (KeyValuePair<string, string> entry in ResponseHeaders) if (entry.Key.ToLower().Equals("user-agent") && Request is HttpWebRequest) ((HttpWebRequest)Request).UserAgent = entry.Value; else Request.Headers[entry.Key] = entry.Value; } // Encode outbound data if (!string.IsNullOrEmpty(OutboundBody)) { byte[] data = Util.UTF8.GetBytes(OutboundBody); Request.ContentLength = data.Length; using (Stream bstream = Request.GetRequestStream()) bstream.Write(data, 0, data.Length); } try { IAsyncResult result = (IAsyncResult)Request.BeginGetResponse(ResponseCallback, null); ThreadPool.RegisterWaitForSingleObject( result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), null, HttpTimeout, true); } catch (WebException e) { if (e.Status != WebExceptionStatus.ProtocolError) { throw; } HttpWebResponse response = (HttpWebResponse)e.Response; Status = (int)response.StatusCode; ResponseBody = response.StatusDescription; _finished = true; } } catch (Exception e) { // m_log.Debug( // string.Format("[SCRIPTS HTTP REQUESTS]: Exception on request to {0} for {1} ", Url, ItemID), e); Status = (int)OSHttpStatusCode.ClientErrorJoker; ResponseBody = e.Message; _finished = true; } } private void ResponseCallback(IAsyncResult ar) { HttpWebResponse response = null; try { try { response = (HttpWebResponse)Request.EndGetResponse(ar); } catch (WebException e) { if (e.Status != WebExceptionStatus.ProtocolError) { throw; } response = (HttpWebResponse)e.Response; } Status = (int)response.StatusCode; using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); ResponseBody = reader.ReadToEnd(); } } catch (Exception e) { Status = (int)OSHttpStatusCode.ClientErrorJoker; ResponseBody = e.Message; // m_log.Debug( // string.Format("[SCRIPTS HTTP REQUESTS]: Exception on response to {0} for {1} ", Url, ItemID), e); } finally { if (response != null) response.Close(); _finished = true; } } private void TimeoutCallback(object state, bool timedOut) { if (timedOut) Request.Abort(); } public void Stop() { // m_log.DebugFormat("[SCRIPTS HTTP REQUESTS]: Stopping request to {0} for {1} ", Url, ItemID); if (Request != null) Request.Abort(); } } }
/* * Copyright (c) 2007-2007 Citrix Systems, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * 'Software'), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Configuration; using System.Diagnostics; using System.IO; using System.Reflection; using Citrix.Configuration; namespace Citrix.Diagnostics { /// <summary> /// Control run-time diagnostics /// </summary> public class CtxTrace { /// <summary> /// This is the default switch that will trace errors only. It gets used if you can't be bothered /// to call the Initialize or InitializeDLL methods to configure a specific switch. /// </summary> private static CtxSwitch _CtxSwitch = CtxSwitch.Create ("ctx-trace"); private static bool _TraceThreads = false; public static TraceLevel Level { get { return _CtxSwitch.Level; } } public static bool Initialized { get; private set; } #region Initialization for App and SnapIn /// <summary> /// Initialize tracing for an application (web or windows). The config file has been loaded automatically so /// it just remains to create the appropriate switch /// </summary> /// <param name="traceClass"></param> public static void Initialize (string traceClass) { _CtxSwitch = CtxSwitch.Create (traceClass); CheckListeners (traceClass); } public static void Initialize (string traceClass, bool TraceThreads) { _CtxSwitch = CtxSwitch.Create (traceClass); CheckListeners (traceClass); _TraceThreads = TraceThreads; } public static void Initialize (string traceClass, TraceLevel traceLevel) { _CtxSwitch = CtxSwitch.Create (traceClass); _CtxSwitch.Level = traceLevel; CheckListeners (traceClass); } /// <summary> /// Intialize tracing for a snap-in loaded into MMC. /// </summary> /// <param name="traceClass"></param> public static void InitializeDLL (string traceClass) { ConfigurationSection section = ConfigurationService.GetSection ("system.diagnostics"); ConfigureListeners (section); CtxSwitch configSwitch = CtxSwitch.Create (traceClass, section); if (configSwitch != null) { _CtxSwitch = configSwitch; } } // Write only errors to event log private class ErrorsOnlyFilter : TraceFilter { public override bool ShouldTrace (TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data) { return ((eventType == TraceEventType.Critical) || (eventType == TraceEventType.Error)); } } // Ensure there is at least one useful listener private static void CheckListeners (string traceClass) { Initialized = true; foreach (TraceListener traceListener in Trace.Listeners) { if ((traceListener is TextWriterTraceListener) || (traceListener is LogWriterTraceListener)) { TraceInformation("Working listener called " + traceListener.Name); return; } } string path = GetDefaultLogFileLocation (); TraceListener listener; if (path != null) { string logfile = Path.Combine (path, traceClass + ".log"); listener = new TextWriterTraceListener (logfile); TraceInformation ("Added listener writing to " + logfile); } else { listener = new EventLogTraceListener (traceClass); listener.Filter = new ErrorsOnlyFilter (); TraceInformation ("Added listener writing to event log"); } Trace.Listeners.Add (listener); Trace.AutoFlush = true; } private static string GetDefaultLogFileLocation () { string path = @"C:\Temp"; if (Directory.Exists (path)) { return path; } path = Environment.GetEnvironmentVariable ("TEMP"); if (Directory.Exists (path)) { return path; } path = Environment.GetEnvironmentVariable ("TMP"); if (Directory.Exists (path)) { return path; } return null; } // process each listener in the app.config private static void ConfigureListeners (ConfigurationSection section) { Trace.AutoFlush = true; ConfigurationElement trace = section.ElementInformation.Properties["trace"].Value as ConfigurationElement; ConfigurationElementCollection listeners = trace.ElementInformation.Properties["listeners"].Value as ConfigurationElementCollection; foreach (ConfigurationElement ce in listeners) { ConfigureListener (ListenerElement.Create (ce.ElementInformation)); } } private static void ConfigureListener (ListenerElement configElement) { foreach (TraceListener traceListener in Trace.Listeners) { if (configElement.Describes (traceListener)) { return; } } Add (configElement); } private static void Add (ListenerElement configElement) { Type type = configElement.GetTraceListenerType (); if (type != null) { ConstructorInfo ci = type.GetConstructor (new Type[] { typeof (string) }); if (ci != null) { TraceListener tl = ci.Invoke (new object[] { configElement.initializeData }) as TraceListener; Trace.Listeners.Add (tl); } } } #endregion #region Trace Errors public static void TraceError (Exception e) { if (_CtxSwitch.TraceError) { InternalWriteLine (TraceLevel.Error, e); } } public static void TraceError (Exception e, string msg) { if (_CtxSwitch.TraceError) { InternalWriteLine (TraceLevel.Error, msg); InternalWriteLine (TraceLevel.Error, e); } } public static void TraceError (string msg) { if (_CtxSwitch.TraceError) { InternalWriteLine (TraceLevel.Error, msg); } } public static void TraceError (string Format, params object[] args) { if (_CtxSwitch.TraceError) { InternalWriteLine (TraceLevel.Error, String.Format (Format, args)); } } #endregion #region Trace Warnings public static void TraceWarning (object obj) { if (_CtxSwitch.TraceWarning) { InternalWriteLine (TraceLevel.Warning, obj); } } public static void TraceWarning (string Format, params object[] args) { if (_CtxSwitch.TraceWarning) { InternalWriteLine (TraceLevel.Warning, String.Format (Format, args)); } } #endregion #region Trace Information public static void TraceInformation () { if (_CtxSwitch.TraceInfo) { InternalWriteLine (TraceLevel.Info, null); } } public static void TraceInformation (object obj) { if (_CtxSwitch.TraceInfo) { InternalWriteLine (TraceLevel.Info, obj); } } public static void TraceInformation (string Format, params object[] args) { if (_CtxSwitch.TraceInfo) { InternalWriteLine (TraceLevel.Info, String.Format (Format, args)); } } #endregion #region Trace Verbose public static void TraceVerbose () { if (_CtxSwitch.TraceVerbose) { InternalWriteLine (TraceLevel.Verbose, null); } } public static void TraceVerbose (object obj) { if (_CtxSwitch.TraceVerbose) { InternalWriteLine (TraceLevel.Verbose, obj); } } public static void TraceVerbose (string Format, params object[] args) { if (_CtxSwitch.TraceVerbose) { InternalWriteLine (TraceLevel.Verbose, String.Format (Format, args)); } } #endregion private static string LevelString (TraceLevel level) { switch (level) { case TraceLevel.Error: return " [E]"; case TraceLevel.Warning: return " [W]"; case TraceLevel.Info: return " [I]"; case TraceLevel.Verbose: return " [V]"; default: return ""; } } private static string ThreadId { get { return (_TraceThreads) ? " [thread:" + System.Threading.Thread.CurrentThread.GetHashCode ().ToString () + "]" : ""; } } private static void InternalWriteLine (TraceLevel level, object obj) { StackFrame frame = new StackFrame (2, true); MethodBase method = frame.GetMethod (); string name = "Unknown"; if (method != null) { var typeName = method.DeclaringType == null ? "UnknownType" : method.DeclaringType.Name; name = " " + typeName + "." + method.Name; } string msg = (obj == null) ? "" : ": " + obj.ToString(); string timestamp = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString(); Trace.WriteLine(timestamp + LevelString(level) + ThreadId + name + msg); } } }
// 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: Define HResult constants. Every exception has one of these. // // //===========================================================================*/ using System; namespace System { // Note: FACILITY_URT is defined as 0x13 (0x8013xxxx). Within that // range, 0x1yyy is for Runtime errors (used for Security, Metadata, etc). // In that subrange, 0x15zz and 0x16zz have been allocated for classlib-type // HResults. Also note that some of our HResults have to map to certain // COM HR's, etc. // Another arbitrary decision... Feel free to change this, as long as you // renumber the HResults yourself (and update rexcep.h). // Reflection will use 0x1600 -> 0x161f. IO will use 0x1620 -> 0x163f. // Security will use 0x1640 -> 0x165f // There are __HResults files in the IO, Remoting, Reflection & // Security/Util directories as well, so choose your HResults carefully. internal static class __HResults { internal const int APPMODEL_ERROR_NO_PACKAGE = unchecked((int)0x80073D54); internal const int CLDB_E_FILE_CORRUPT = unchecked((int)0x8013110e); internal const int CLDB_E_FILE_OLDVER = unchecked((int)0x80131107); internal const int CLDB_E_INDEX_NOTFOUND = unchecked((int)0x80131124); internal const int CLR_E_BIND_ASSEMBLY_NOT_FOUND = unchecked((int)0x80132004); internal const int CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH = unchecked((int)0x80132001); internal const int CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW = unchecked((int)0x80132000); internal const int CLR_E_BIND_TYPE_NOT_FOUND = unchecked((int)0x80132005); internal const int CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT = unchecked((int)0x80132003); internal const int COR_E_ABANDONEDMUTEX = unchecked((int)0x8013152D); internal const int COR_E_AMBIGUOUSMATCH = unchecked((int)0x8000211D); internal const int COR_E_APPDOMAINUNLOADED = unchecked((int)0x80131014); internal const int COR_E_APPLICATION = unchecked((int)0x80131600); internal const int COR_E_ARGUMENT = unchecked((int)0x80070057); internal const int COR_E_ARGUMENTOUTOFRANGE = unchecked((int)0x80131502); internal const int COR_E_ARITHMETIC = unchecked((int)0x80070216); internal const int COR_E_ARRAYTYPEMISMATCH = unchecked((int)0x80131503); internal const int COR_E_ASSEMBLYEXPECTED = unchecked((int)0x80131018); internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B); internal const int COR_E_CANNOTUNLOADAPPDOMAIN = unchecked((int)0x80131015); internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); internal const int COR_E_CONTEXTMARSHAL = unchecked((int)0x80131504); internal const int COR_E_CUSTOMATTRIBUTEFORMAT = unchecked((int)0x80131605); internal const int COR_E_DATAMISALIGNED = unchecked((int)0x80131541); internal const int COR_E_DIVIDEBYZERO = unchecked((int)0x80020012); // DISP_E_DIVBYZERO internal const int COR_E_DLLNOTFOUND = unchecked((int)0x80131524); internal const int COR_E_DUPLICATEWAITOBJECT = unchecked((int)0x80131529); internal const int COR_E_ENTRYPOINTNOTFOUND = unchecked((int)0x80131523); internal const int COR_E_EXCEPTION = unchecked((int)0x80131500); internal const int COR_E_EXECUTIONENGINE = unchecked((int)0x80131506); internal const int COR_E_FIELDACCESS = unchecked((int)0x80131507); internal const int COR_E_FIXUPSINEXE = unchecked((int)0x80131019); internal const int COR_E_FORMAT = unchecked((int)0x80131537); internal const int COR_E_INDEXOUTOFRANGE = unchecked((int)0x80131508); internal const int COR_E_INSUFFICIENTEXECUTIONSTACK = unchecked((int)0x80131578); internal const int COR_E_INSUFFICIENTMEMORY = unchecked((int)0x8013153d); internal const int COR_E_INVALIDCAST = unchecked((int)0x80004002); internal const int COR_E_INVALIDCOMOBJECT = unchecked((int)0x80131527); internal const int COR_E_INVALIDFILTERCRITERIA = unchecked((int)0x80131601); internal const int COR_E_INVALIDOLEVARIANTTYPE = unchecked((int)0x80131531); internal const int COR_E_INVALIDOPERATION = unchecked((int)0x80131509); internal const int COR_E_INVALIDPROGRAM = unchecked((int)0x8013153a); internal const int COR_E_KEYNOTFOUND = unchecked((int)0x80131577); internal const int COR_E_LOADING_REFERENCE_ASSEMBLY = unchecked((int)0x80131058); internal const int COR_E_MARSHALDIRECTIVE = unchecked((int)0x80131535); internal const int COR_E_MEMBERACCESS = unchecked((int)0x8013151A); internal const int COR_E_METHODACCESS = unchecked((int)0x80131510); internal const int COR_E_MISSINGFIELD = unchecked((int)0x80131511); internal const int COR_E_MISSINGMANIFESTRESOURCE = unchecked((int)0x80131532); internal const int COR_E_MISSINGMEMBER = unchecked((int)0x80131512); internal const int COR_E_MISSINGMETHOD = unchecked((int)0x80131513); internal const int COR_E_MISSINGSATELLITEASSEMBLY = unchecked((int)0x80131536); internal const int COR_E_MODULE_HASH_CHECK_FAILED = unchecked((int)0x80131039); internal const int COR_E_MULTICASTNOTSUPPORTED = unchecked((int)0x80131514); internal const int COR_E_NEWER_RUNTIME = unchecked((int)0x8013101b); internal const int COR_E_NOTFINITENUMBER = unchecked((int)0x80131528); internal const int COR_E_NOTSUPPORTED = unchecked((int)0x80131515); internal const int COR_E_NULLREFERENCE = unchecked((int)0x80004003); internal const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622); internal const int COR_E_OPERATIONCANCELED = unchecked((int)0x8013153B); internal const int COR_E_OUTOFMEMORY = unchecked((int)0x8007000E); internal const int COR_E_OVERFLOW = unchecked((int)0x80131516); internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539); internal const int COR_E_RANK = unchecked((int)0x80131517); internal const int COR_E_REFLECTIONTYPELOAD = unchecked((int)0x80131602); internal const int COR_E_REMOTING = unchecked((int)0x8013150b); internal const int COR_E_RUNTIMEWRAPPED = unchecked((int)0x8013153e); internal const int COR_E_SAFEARRAYRANKMISMATCH = unchecked((int)0x80131538); internal const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked((int)0x80131533); internal const int COR_E_SECURITY = unchecked((int)0x8013150A); internal const int COR_E_SERIALIZATION = unchecked((int)0x8013150C); internal const int COR_E_SERVER = unchecked((int)0x8013150e); internal const int COR_E_STACKOVERFLOW = unchecked((int)0x800703E9); internal const int COR_E_SYNCHRONIZATIONLOCK = unchecked((int)0x80131518); internal const int COR_E_SYSTEM = unchecked((int)0x80131501); internal const int COR_E_TARGET = unchecked((int)0x80131603); internal const int COR_E_TARGETINVOCATION = unchecked((int)0x80131604); internal const int COR_E_TARGETPARAMCOUNT = unchecked((int)0x8002000e); internal const int COR_E_THREADABORTED = unchecked((int)0x80131530); internal const int COR_E_THREADINTERRUPTED = unchecked((int)0x80131519); internal const int COR_E_THREADSTART = unchecked((int)0x80131525); internal const int COR_E_THREADSTATE = unchecked((int)0x80131520); internal const int COR_E_TIMEOUT = unchecked((int)0x80131505); internal const int COR_E_TYPEACCESS = unchecked((int)0x80131543); internal const int COR_E_TYPEINITIALIZATION = unchecked((int)0x80131534); internal const int COR_E_TYPELOAD = unchecked((int)0x80131522); internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013); internal const int COR_E_UNAUTHORIZEDACCESS = unchecked((int)0x80070005); internal const int COR_E_VERIFICATION = unchecked((int)0x8013150D); internal const int COR_E_WAITHANDLECANNOTBEOPENED = unchecked((int)0x8013152C); internal const int CORSEC_E_CRYPTO = unchecked((int)0x80131430); internal const int CORSEC_E_CRYPTO_UNEX_OPER = unchecked((int)0x80131431); internal const int CORSEC_E_INVALID_IMAGE_FORMAT = unchecked((int)0x8013141d); internal const int CORSEC_E_INVALID_PUBLICKEY = unchecked((int)0x8013141e); internal const int CORSEC_E_INVALID_STRONGNAME = unchecked((int)0x8013141a); internal const int CORSEC_E_MIN_GRANT_FAIL = unchecked((int)0x80131417); internal const int CORSEC_E_MISSING_STRONGNAME = unchecked((int)0x8013141b); internal const int CORSEC_E_NO_EXEC_PERM = unchecked((int)0x80131418); internal const int CORSEC_E_POLICY_EXCEPTION = unchecked((int)0x80131416); internal const int CORSEC_E_SIGNATURE_MISMATCH = unchecked((int)0x80131420); internal const int CORSEC_E_XMLSYNTAX = unchecked((int)0x80131419); internal const int CTL_E_DEVICEIOERROR = unchecked((int)0x800A0039); internal const int CTL_E_DIVISIONBYZERO = unchecked((int)0x800A000B); internal const int CTL_E_FILENOTFOUND = unchecked((int)0x800A0035); internal const int CTL_E_OUTOFMEMORY = unchecked((int)0x800A0007); internal const int CTL_E_OUTOFSTACKSPACE = unchecked((int)0x800A001C); internal const int CTL_E_OVERFLOW = unchecked((int)0x800A0006); internal const int CTL_E_PATHFILEACCESSERROR = unchecked((int)0x800A004B); internal const int CTL_E_PATHNOTFOUND = unchecked((int)0x800A004C); internal const int CTL_E_PERMISSIONDENIED = unchecked((int)0x800A0046); internal const int E_ELEMENTNOTAVAILABLE = unchecked((int)0x802B001F); internal const int E_ELEMENTNOTENABLED = unchecked((int)0x802B001E); internal const int E_FAIL = unchecked((int)0x80004005); internal const int E_ILLEGAL_DELEGATE_ASSIGNMENT = unchecked((int)0x80000018); internal const int E_ILLEGAL_METHOD_CALL = unchecked((int)0x8000000E); internal const int E_ILLEGAL_STATE_CHANGE = unchecked((int)0x8000000D); internal const int E_LAYOUTCYCLE = unchecked((int)0x802B0014); internal const int E_NOTIMPL = unchecked((int)0x80004001); internal const int E_OUTOFMEMORY = unchecked((int)0x8007000E); internal const int E_POINTER = unchecked((int)0x80004003L); internal const int E_XAMLPARSEFAILED = unchecked((int)0x802B000A); internal const int ERROR_BAD_EXE_FORMAT = unchecked((int)0x800700C1); internal const int ERROR_BAD_NET_NAME = unchecked((int)0x80070043); internal const int ERROR_BAD_NETPATH = unchecked((int)0x80070035); internal const int ERROR_DISK_CORRUPT = unchecked((int)0x80070571); internal const int ERROR_DLL_INIT_FAILED = unchecked((int)0x8007045A); internal const int ERROR_DLL_NOT_FOUND = unchecked((int)0x80070485); internal const int ERROR_EXE_MARKED_INVALID = unchecked((int)0x800700C0); internal const int ERROR_FILE_CORRUPT = unchecked((int)0x80070570); internal const int ERROR_FILE_INVALID = unchecked((int)0x800703EE); internal const int ERROR_FILE_NOT_FOUND = unchecked((int)0x80070002); internal const int ERROR_INVALID_DLL = unchecked((int)0x80070482); internal const int ERROR_INVALID_NAME = unchecked((int)0x8007007B); internal const int ERROR_INVALID_ORDINAL = unchecked((int)0x800700B6); internal const int ERROR_INVALID_PARAMETER = unchecked((int)0x80070057); internal const int ERROR_LOCK_VIOLATION = unchecked((int)0x80070021); internal const int ERROR_MOD_NOT_FOUND = unchecked((int)0x8007007E); internal const int ERROR_MRM_MAP_NOT_FOUND = unchecked((int)0x80073b1f); internal const int ERROR_NO_UNICODE_TRANSLATION = unchecked((int)0x80070459); internal const int ERROR_NOACCESS = unchecked((int)0x800703E6); internal const int ERROR_NOT_READY = unchecked((int)0x80070015); internal const int ERROR_OPEN_FAILED = unchecked((int)0x8007006E); internal const int ERROR_PATH_NOT_FOUND = unchecked((int)0x80070003); internal const int ERROR_SHARING_VIOLATION = unchecked((int)0x80070020); internal const int ERROR_TOO_MANY_OPEN_FILES = unchecked((int)0x80070004); internal const int ERROR_INVALID_HANDLE = unchecked((int)0x80070006); internal const int ERROR_UNRECOGNIZED_VOLUME = unchecked((int)0x800703ED); internal const int ERROR_WRONG_TARGET_NAME = unchecked((int)0x80070574); internal const int FUSION_E_ASM_MODULE_MISSING = unchecked((int)0x80131042); internal const int FUSION_E_CACHEFILE_FAILED = unchecked((int)0x80131052); internal const int FUSION_E_CODE_DOWNLOAD_DISABLED = unchecked((int)0x80131048); internal const int FUSION_E_HOST_GAC_ASM_MISMATCH = unchecked((int)0x80131050); internal const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047); internal const int FUSION_E_INVALID_PRIVATE_ASM_LOCATION = unchecked((int)0x80131041); internal const int FUSION_E_LOADFROM_BLOCKED = unchecked((int)0x80131051); internal const int FUSION_E_PRIVATE_ASM_DISALLOWED = unchecked((int)0x80131044); internal const int FUSION_E_REF_DEF_MISMATCH = unchecked((int)0x80131040); internal const int FUSION_E_SIGNATURE_CHECK_FAILED = unchecked((int)0x80131045); internal const int INET_E_CANNOT_CONNECT = unchecked((int)0x800C0004); internal const int INET_E_CONNECTION_TIMEOUT = unchecked((int)0x800C000B); internal const int INET_E_DATA_NOT_AVAILABLE = unchecked((int)0x800C0007); internal const int INET_E_DOWNLOAD_FAILURE = unchecked((int)0x800C0008); internal const int INET_E_OBJECT_NOT_FOUND = unchecked((int)0x800C0006); internal const int INET_E_RESOURCE_NOT_FOUND = unchecked((int)0x800C0005); internal const int INET_E_UNKNOWN_PROTOCOL = unchecked((int)0x800C000D); internal const int ISS_E_ALLOC_TOO_LARGE = unchecked((int)0x80131484); internal const int ISS_E_BLOCK_SIZE_TOO_SMALL = unchecked((int)0x80131483); internal const int ISS_E_CALLER = unchecked((int)0x801314A1); internal const int ISS_E_CORRUPTED_STORE_FILE = unchecked((int)0x80131480); internal const int ISS_E_CREATE_DIR = unchecked((int)0x80131468); internal const int ISS_E_CREATE_MUTEX = unchecked((int)0x80131464); internal const int ISS_E_DEPRECATE = unchecked((int)0x801314A0); internal const int ISS_E_FILE_NOT_MAPPED = unchecked((int)0x80131482); internal const int ISS_E_FILE_WRITE = unchecked((int)0x80131466); internal const int ISS_E_GET_FILE_SIZE = unchecked((int)0x80131463); internal const int ISS_E_ISOSTORE = unchecked((int)0x80131450); internal const int ISS_E_LOCK_FAILED = unchecked((int)0x80131465); internal const int ISS_E_MACHINE = unchecked((int)0x801314A3); internal const int ISS_E_MACHINE_DACL = unchecked((int)0x801314A4); internal const int ISS_E_MAP_VIEW_OF_FILE = unchecked((int)0x80131462); internal const int ISS_E_OPEN_FILE_MAPPING = unchecked((int)0x80131461); internal const int ISS_E_OPEN_STORE_FILE = unchecked((int)0x80131460); internal const int ISS_E_PATH_LENGTH = unchecked((int)0x801314A2); internal const int ISS_E_SET_FILE_POINTER = unchecked((int)0x80131467); internal const int ISS_E_STORE_NOT_OPEN = unchecked((int)0x80131469); internal const int ISS_E_STORE_VERSION = unchecked((int)0x80131481); internal const int ISS_E_TABLE_ROW_NOT_FOUND = unchecked((int)0x80131486); internal const int ISS_E_USAGE_WILL_EXCEED_QUOTA = unchecked((int)0x80131485); internal const int META_E_BAD_SIGNATURE = unchecked((int)0x80131192); internal const int META_E_CA_FRIENDS_SN_REQUIRED = unchecked((int)0x801311e6); internal const int MSEE_E_ASSEMBLYLOADINPROGRESS = unchecked((int)0x80131016); internal const int RO_E_CLOSED = unchecked((int)0x80000013); internal const int E_BOUNDS = unchecked((int)0x8000000B); internal const int RO_E_METADATA_NAME_NOT_FOUND = unchecked((int)0x8000000F); internal const int SECURITY_E_INCOMPATIBLE_EVIDENCE = unchecked((int)0x80131403); internal const int SECURITY_E_INCOMPATIBLE_SHARE = unchecked((int)0x80131401); internal const int SECURITY_E_UNVERIFIABLE = unchecked((int)0x80131402); internal const int STG_E_PATHNOTFOUND = unchecked((int)0x80030003); public const int COR_E_DIRECTORYNOTFOUND = unchecked((int)0x80070003); public const int COR_E_ENDOFSTREAM = unchecked((int)0x80070026); // OS defined public const int COR_E_FILELOAD = unchecked((int)0x80131621); public const int COR_E_FILENOTFOUND = unchecked((int)0x80070002); public const int COR_E_IO = unchecked((int)0x80131620); public const int COR_E_PATHTOOLONG = unchecked((int)0x800700CE); } }
using Orleans.Serialization.Buffers; using Orleans.Serialization.Cloning; using Orleans.Serialization.WireProtocol; using System; using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Orleans.Serialization.Codecs { [RegisterSerializer] public sealed class FloatCodec : TypedCodecBase<float, FloatCodec>, IFieldCodec<float> { private static readonly Type CodecFieldType = typeof(float); void IFieldCodec<float>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, float value) => WriteField(ref writer, fieldIdDelta, expectedType, value); public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, float value) where TBufferWriter : IBufferWriter<byte> { ReferenceCodec.MarkValueField(writer.Session); writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.Fixed32); // TODO: Optimize writer.WriteUInt32((uint)BitConverter.ToInt32(BitConverter.GetBytes(value), 0)); } float IFieldCodec<float>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field); public static float ReadValue<TInput>(ref Reader<TInput> reader, Field field) { ReferenceCodec.MarkValueField(reader.Session); switch (field.WireType) { case WireType.Fixed32: return ReadFloatRaw(ref reader); case WireType.Fixed64: { var value = DoubleCodec.ReadDoubleRaw(ref reader); if ((value > float.MaxValue || value < float.MinValue) && !double.IsInfinity(value) && !double.IsNaN(value)) { ThrowValueOutOfRange(value); } return (float)value; } case WireType.LengthPrefixed: return (float)DecimalCodec.ReadDecimalRaw(ref reader); default: ThrowWireTypeOutOfRange(field.WireType); return 0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] #if NETCOREAPP public static float ReadFloatRaw<TInput>(ref Reader<TInput> reader) => BitConverter.Int32BitsToSingle(reader.ReadInt32()); #else public static float ReadFloatRaw<TInput>(ref Reader<TInput> reader) => BitConverter.ToSingle(BitConverter.GetBytes(reader.ReadInt32()), 0); #endif [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowWireTypeOutOfRange(WireType wireType) => throw new ArgumentOutOfRangeException( $"{nameof(wireType)} {wireType} is not supported by this codec."); [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowValueOutOfRange<T>(T value) => throw new ArgumentOutOfRangeException( $"The {typeof(T)} value has a magnitude too high {value} to be converted to {typeof(float)}."); } [RegisterCopier] public sealed class FloatCopier : IDeepCopier<float> { public float DeepCopy(float input, CopyContext _) => input; } [RegisterSerializer] public sealed class DoubleCodec : TypedCodecBase<double, DoubleCodec>, IFieldCodec<double> { private static readonly Type CodecFieldType = typeof(double); void IFieldCodec<double>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, double value) => WriteField(ref writer, fieldIdDelta, expectedType, value); public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, double value) where TBufferWriter : IBufferWriter<byte> { ReferenceCodec.MarkValueField(writer.Session); writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.Fixed64); // TODO: Optimize writer.WriteUInt64((ulong)BitConverter.ToInt64(BitConverter.GetBytes(value), 0)); } double IFieldCodec<double>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field); public static double ReadValue<TInput>(ref Reader<TInput> reader, Field field) { ReferenceCodec.MarkValueField(reader.Session); switch (field.WireType) { case WireType.Fixed32: return FloatCodec.ReadFloatRaw(ref reader); case WireType.Fixed64: return ReadDoubleRaw(ref reader); case WireType.LengthPrefixed: return (double)DecimalCodec.ReadDecimalRaw(ref reader); default: ThrowWireTypeOutOfRange(field.WireType); return 0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] #if NETCOREAPP public static double ReadDoubleRaw<TInput>(ref Reader<TInput> reader) => BitConverter.Int64BitsToDouble(reader.ReadInt64()); #else public static double ReadDoubleRaw<TInput>(ref Reader<TInput> reader) => BitConverter.ToDouble(BitConverter.GetBytes(reader.ReadInt64()), 0); #endif [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowWireTypeOutOfRange(WireType wireType) => throw new ArgumentOutOfRangeException( $"{nameof(wireType)} {wireType} is not supported by this codec."); } [RegisterCopier] public sealed class DoubleCopier : IDeepCopier<double> { public double DeepCopy(double input, CopyContext _) => input; } [RegisterSerializer] public sealed class DecimalCodec : TypedCodecBase<decimal, DecimalCodec>, IFieldCodec<decimal> { private const int Width = 16; private static readonly Type CodecFieldType = typeof(decimal); void IFieldCodec<decimal>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, decimal value) => WriteField(ref writer, fieldIdDelta, expectedType, value); public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, decimal value) where TBufferWriter : IBufferWriter<byte> { ReferenceCodec.MarkValueField(writer.Session); writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.LengthPrefixed); writer.WriteVarUInt32(Width); var holder = new DecimalConverter { Value = value }; writer.WriteUInt64(holder.First); writer.WriteUInt64(holder.Second); } decimal IFieldCodec<decimal>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field); public static decimal ReadValue<TInput>(ref Reader<TInput> reader, Field field) { ReferenceCodec.MarkValueField(reader.Session); switch (field.WireType) { case WireType.Fixed32: { var value = FloatCodec.ReadFloatRaw(ref reader); if (value > (float)decimal.MaxValue || value < (float)decimal.MinValue) { ThrowValueOutOfRange(value); } return (decimal)value; } case WireType.Fixed64: { var value = DoubleCodec.ReadDoubleRaw(ref reader); if (value > (double)decimal.MaxValue || value < (double)decimal.MinValue) { ThrowValueOutOfRange(value); } return (decimal)value; } case WireType.LengthPrefixed: return ReadDecimalRaw(ref reader); default: ThrowWireTypeOutOfRange(field.WireType); return 0; } } public static decimal ReadDecimalRaw<TInput>(ref Reader<TInput> reader) { var length = reader.ReadVarUInt32(); if (length != Width) { throw new UnexpectedLengthPrefixValueException("decimal", Width, length); } var first = reader.ReadUInt64(); var second = reader.ReadUInt64(); var holder = new DecimalConverter { First = first, Second = second, }; // This could be retrieved from the Value property of the holder, but it is safer to go through the constructor to ensure that validation occurs early. return new decimal(holder.Lo, holder.Mid, holder.Hi, holder.IsNegative, holder.Scale); } [StructLayout(LayoutKind.Explicit)] private struct DecimalConverter { [FieldOffset(0)] public decimal Value; [FieldOffset(0)] public ulong First; [FieldOffset(8)] public ulong Second; [FieldOffset(0)] private int Flags; [FieldOffset(4)] public int Hi; [FieldOffset(8)] public int Lo; [FieldOffset(12)] public int Mid; public byte Scale => (byte)(Flags >> 16); public bool IsNegative => (Flags & unchecked((int)0x80000000)) != 0; } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowWireTypeOutOfRange(WireType wireType) => throw new ArgumentOutOfRangeException( $"{nameof(wireType)} {wireType} is not supported by this codec."); [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowValueOutOfRange<T>(T value) => throw new ArgumentOutOfRangeException( $"The {typeof(T)} value has a magnitude too high {value} to be converted to {typeof(decimal)}."); } [RegisterCopier] public sealed class DecimalCopier : IDeepCopier<decimal> { public decimal DeepCopy(decimal input, CopyContext _) => input; } }
/* * 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.Compute { using System; using System.Collections.Generic; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Portable; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Tests task result. /// </summary> public class TaskResultTest : AbstractTaskTest { /** Grid name. */ private static volatile string _gridName; /// <summary> /// Constructor. /// </summary> public TaskResultTest() : base(false) { } /// <summary> /// Constructor. /// </summary> /// <param name="forked">Fork flag.</param> protected TaskResultTest(bool forked) : base(forked) { } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultInt() { TestTask<int> task = new TestTask<int>(); int res = Grid1.Compute().Execute(task, new Tuple<bool, int>(true, 10)); Assert.AreEqual(10, res); res = Grid1.Compute().Execute(task, new Tuple<bool, int>(false, 11)); Assert.AreEqual(11, res); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultLong() { TestTask<long> task = new TestTask<long>(); long res = Grid1.Compute().Execute(task, new Tuple<bool, long>(true, 10000000000)); Assert.AreEqual(10000000000, res); res = Grid1.Compute().Execute(task, new Tuple<bool, long>(false, 10000000001)); Assert.AreEqual(10000000001, res); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultFloat() { TestTask<float> task = new TestTask<float>(); float res = Grid1.Compute().Execute(task, new Tuple<bool, float>(true, 1.1f)); Assert.AreEqual(1.1f, res); res = Grid1.Compute().Execute(task, new Tuple<bool, float>(false, -1.1f)); Assert.AreEqual(-1.1f, res); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultPortable() { TestTask<PortableResult> task = new TestTask<PortableResult>(); PortableResult val = new PortableResult(100); PortableResult res = Grid1.Compute().Execute(task, new Tuple<bool, PortableResult>(true, val)); Assert.AreEqual(val.Val, res.Val); val.Val = 101; res = Grid1.Compute().Execute(task, new Tuple<bool, PortableResult>(false, val)); Assert.AreEqual(val.Val, res.Val); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultSerializable() { TestTask<SerializableResult> task = new TestTask<SerializableResult>(); SerializableResult val = new SerializableResult(100); SerializableResult res = Grid1.Compute().Execute(task, new Tuple<bool, SerializableResult>(true, val)); Assert.AreEqual(val.Val, res.Val); val.Val = 101; res = Grid1.Compute().Execute(task, new Tuple<bool, SerializableResult>(false, val)); Assert.AreEqual(val.Val, res.Val); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultLarge() { TestTask<byte[]> task = new TestTask<byte[]>(); byte[] res = Grid1.Compute().Execute(task, new Tuple<bool, byte[]>(true, new byte[100 * 1024])); Assert.AreEqual(100 * 1024, res.Length); res = Grid1.Compute().Execute(task, new Tuple<bool, byte[]>(false, new byte[101 * 1024])); Assert.AreEqual(101 * 1024, res.Length); } /** <inheritDoc /> */ override protected void PortableTypeConfigurations(ICollection<PortableTypeConfiguration> portTypeCfgs) { portTypeCfgs.Add(new PortableTypeConfiguration(typeof(PortableResult))); portTypeCfgs.Add(new PortableTypeConfiguration(typeof(TestPortableJob))); portTypeCfgs.Add(new PortableTypeConfiguration(typeof(PortableOutFunc))); portTypeCfgs.Add(new PortableTypeConfiguration(typeof(PortableFunc))); } [Test] public void TestOutFuncResultPrimitive1() { ICollection<int> res = Grid1.Compute().Broadcast(new PortableOutFunc()); Assert.AreEqual(3, res.Count); foreach (int r in res) Assert.AreEqual(10, r); } [Test] public void TestOutFuncResultPrimitive2() { ICollection<int> res = Grid1.Compute().Broadcast(new SerializableOutFunc()); Assert.AreEqual(3, res.Count); foreach (int r in res) Assert.AreEqual(10, r); } [Test] public void TestFuncResultPrimitive1() { ICollection<int> res = Grid1.Compute().Broadcast(new PortableFunc(), 10); Assert.AreEqual(3, res.Count); foreach (int r in res) Assert.AreEqual(11, r); } [Test] public void TestFuncResultPrimitive2() { ICollection<int> res = Grid1.Compute().Broadcast(new SerializableFunc(), 10); Assert.AreEqual(3, res.Count); foreach (int r in res) Assert.AreEqual(11, r); } interface IUserInterface<in T, out TR> { TR Invoke(T arg); } /// <summary> /// Test function. /// </summary> public class PortableFunc : IComputeFunc<int, int>, IUserInterface<int, int> { int IComputeFunc<int, int>.Invoke(int arg) { return arg + 1; } int IUserInterface<int, int>.Invoke(int arg) { // Same signature as IComputeFunc<int, int>, but from different interface throw new Exception("Invalid method"); } public int Invoke(int arg) { // Same signature as IComputeFunc<int, int>, // but due to explicit interface implementation this is a wrong method throw new Exception("Invalid method"); } } /// <summary> /// Test function. /// </summary> [Serializable] public class SerializableFunc : IComputeFunc<int, int> { public int Invoke(int arg) { return arg + 1; } } /// <summary> /// Test function. /// </summary> public class PortableOutFunc : IComputeFunc<int> { public int Invoke() { return 10; } } /// <summary> /// Test function. /// </summary> [Serializable] public class SerializableOutFunc : IComputeFunc<int> { public int Invoke() { return 10; } } /// <summary> /// Test task. /// </summary> public class TestTask<T> : ComputeTaskAdapter<Tuple<bool, T>, T, T> { /** <inheritDoc /> */ override public IDictionary<IComputeJob<T>, IClusterNode> Map(IList<IClusterNode> subgrid, Tuple<bool, T> arg) { _gridName = null; Assert.AreEqual(3, subgrid.Count); bool local = arg.Item1; T res = arg.Item2; var jobs = new Dictionary<IComputeJob<T>, IClusterNode>(); IComputeJob<T> job; if (res is PortableResult) { TestPortableJob job0 = new TestPortableJob(); job0.SetArguments(res); job = (IComputeJob<T>) job0; } else { TestJob<T> job0 = new TestJob<T>(); job0.SetArguments(res); job = job0; } foreach (IClusterNode node in subgrid) { bool add = local ? node.IsLocal : !node.IsLocal; if (add) { jobs.Add(job, node); break; } } Assert.AreEqual(1, jobs.Count); return jobs; } /** <inheritDoc /> */ override public T Reduce(IList<IComputeJobResult<T>> results) { Assert.AreEqual(1, results.Count); var res = results[0]; Assert.IsNull(res.Exception()); Assert.IsFalse(res.Cancelled); Assert.IsNotNull(_gridName); Assert.AreEqual(GridId(_gridName), res.NodeId); var job = res.Job(); Assert.IsNotNull(job); return res.Data(); } } private static Guid GridId(string gridName) { if (gridName.Equals(Grid1Name)) return Ignition.GetIgnite(Grid1Name).Cluster.LocalNode.Id; if (gridName.Equals(Grid2Name)) return Ignition.GetIgnite(Grid2Name).Cluster.LocalNode.Id; if (gridName.Equals(Grid3Name)) return Ignition.GetIgnite(Grid3Name).Cluster.LocalNode.Id; Assert.Fail("Failed to find grid " + gridName); return new Guid(); } /// <summary> /// /// </summary> class PortableResult { /** */ public int Val; public PortableResult(int val) { Val = val; } } /// <summary> /// /// </summary> [Serializable] class SerializableResult { /** */ public int Val; public SerializableResult(int val) { Val = val; } } /// <summary> /// /// </summary> [Serializable] class TestJob<T> : ComputeJobAdapter<T> { [InstanceResource] private IIgnite _grid = null; /** <inheritDoc /> */ override public T Execute() { Assert.IsNotNull(_grid); _gridName = _grid.Name; T res = Argument<T>(0); return res; } } /// <summary> /// /// </summary> class TestPortableJob : ComputeJobAdapter<PortableResult> { [InstanceResource] private IIgnite _grid = null; /** <inheritDoc /> */ override public PortableResult Execute() { Assert.IsNotNull(_grid); _gridName = _grid.Name; PortableResult res = Argument<PortableResult>(0); return res; } } } }
// <copyright file="FirefoxOptions.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 OpenQA.Selenium.Remote; namespace OpenQA.Selenium.Firefox { /// <summary> /// Class to manage options specific to <see cref="FirefoxDriver"/> /// </summary> /// <remarks> /// Used with the marionette executable wires.exe. /// </remarks> /// <example> /// <code> /// FirefoxOptions options = new FirefoxOptions(); /// </code> /// <para></para> /// <para>For use with FirefoxDriver:</para> /// <para></para> /// <code> /// FirefoxDriver driver = new FirefoxDriver(options); /// </code> /// <para></para> /// <para>For use with RemoteWebDriver:</para> /// <para></para> /// <code> /// RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities()); /// </code> /// </example> public class FirefoxOptions : DriverOptions { private const string BrowserNameValue = "firefox"; private const string IsMarionetteCapability = "marionette"; private const string FirefoxLegacyProfileCapability = "firefox_profile"; private const string FirefoxLegacyBinaryCapability = "firefox_binary"; private const string FirefoxProfileCapability = "profile"; private const string FirefoxBinaryCapability = "binary"; private const string FirefoxArgumentsCapability = "args"; private const string FirefoxLogCapability = "log"; private const string FirefoxPrefsCapability = "prefs"; private const string FirefoxEnvCapability = "env"; private const string FirefoxOptionsCapability = "moz:firefoxOptions"; private const string FirefoxEnableDevToolsProtocolCapability = "moz:debuggerAddress"; private bool enableDevToolsProtocol; private string browserBinaryLocation; private FirefoxDriverLogLevel logLevel = FirefoxDriverLogLevel.Default; private FirefoxProfile profile; private List<string> firefoxArguments = new List<string>(); private Dictionary<string, object> profilePreferences = new Dictionary<string, object>(); private Dictionary<string, object> additionalFirefoxOptions = new Dictionary<string, object>(); private Dictionary<string, object> environmentVariables = new Dictionary<string, object>(); private FirefoxAndroidOptions androidOptions; /// <summary> /// Initializes a new instance of the <see cref="FirefoxOptions"/> class. /// </summary> public FirefoxOptions() : base() { this.BrowserName = BrowserNameValue; this.AddKnownCapabilityName(FirefoxOptions.FirefoxOptionsCapability, "current FirefoxOptions class instance"); this.AddKnownCapabilityName(FirefoxOptions.IsMarionetteCapability, "UseLegacyImplementation property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxProfileCapability, "Profile property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxBinaryCapability, "BrowserExecutableLocation property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxArgumentsCapability, "AddArguments method"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxPrefsCapability, "SetPreference method"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxEnvCapability, "SetEnvironmentVariable method"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxLogCapability, "LogLevel property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxLegacyProfileCapability, "Profile property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxLegacyBinaryCapability, "BrowserExecutableLocation property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxEnableDevToolsProtocolCapability, "EnableDevToolsProtocol property"); } /// <summary> /// Gets or sets a value indicating whether to use the legacy driver implementation. /// </summary> [Obsolete(".NET bindings no longer support the legacy driver implementation. Setting this property no longer has any effect. .NET users should always be using geckodriver.")] public bool UseLegacyImplementation { get { return false; } set { } } /// <summary> /// Gets or sets the <see cref="FirefoxProfile"/> object to be used with this instance. /// </summary> public FirefoxProfile Profile { get { return this.profile; } set { this.profile = value; } } /// <summary> /// Gets or sets the path and file name of the Firefox browser executable. /// </summary> public string BrowserExecutableLocation { get { return this.browserBinaryLocation; } set { this.browserBinaryLocation = value; } } /// <summary> /// Gets or sets the logging level of the Firefox driver. /// </summary> public FirefoxDriverLogLevel LogLevel { get { return this.logLevel; } set { this.logLevel = value; } } public bool EnableDevToolsProtocol { get { return this.enableDevToolsProtocol; } set { this.enableDevToolsProtocol = value; } } /// <summary> /// Gets or sets the options for automating Firefox on Android. /// </summary> public FirefoxAndroidOptions AndroidOptions { get { return this.androidOptions; } set { this.androidOptions = value; } } /// <summary> /// Adds an argument to be used in launching the Firefox browser. /// </summary> /// <param name="argumentName">The argument to add.</param> /// <remarks>Arguments must be preceeded by two dashes ("--").</remarks> public void AddArgument(string argumentName) { if (string.IsNullOrEmpty(argumentName)) { throw new ArgumentException("argumentName must not be null or empty", nameof(argumentName)); } this.AddArguments(argumentName); } /// <summary> /// Adds a list arguments to be used in launching the Firefox browser. /// </summary> /// <param name="argumentsToAdd">An array of arguments to add.</param> /// <remarks>Each argument must be preceeded by two dashes ("--").</remarks> public void AddArguments(params string[] argumentsToAdd) { this.AddArguments(new List<string>(argumentsToAdd)); } /// <summary> /// Adds a list arguments to be used in launching the Firefox browser. /// </summary> /// <param name="argumentsToAdd">An array of arguments to add.</param> public void AddArguments(IEnumerable<string> argumentsToAdd) { if (argumentsToAdd == null) { throw new ArgumentNullException(nameof(argumentsToAdd), "argumentsToAdd must not be null"); } this.firefoxArguments.AddRange(argumentsToAdd); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, bool preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, int preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, long preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, double preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, string preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets an environment variable to be set in the operating system's environment under which the Firerox browser is launched. /// </summary> /// <param name="variableName">The name of the environment variable.</param> /// <param name="variableValue">The value of the environment variable.</param> public void SetEnvironmentVariable(string variableName, string variableValue) { if (string.IsNullOrEmpty(variableName)) { throw new ArgumentException("Environment variable name cannot be null or an empty string"); } if (variableValue == null) { variableValue = string.Empty; } this.environmentVariables[variableName] = variableValue; } /// <summary> /// Provides a means to add additional capabilities not yet added as type safe options /// for the Firefox driver. /// </summary> /// <param name="optionName">The name of the capability to add.</param> /// <param name="optionValue">The value of the capability to add.</param> /// <exception cref="ArgumentException"> /// thrown when attempting to add a capability for which there is already a type safe option, or /// when <paramref name="optionName"/> is <see langword="null"/> or the empty string. /// </exception> /// <remarks>Calling <see cref="AddAdditionalFirefoxOption(string, object)"/> /// where <paramref name="optionName"/> has already been added will overwrite the /// existing value with the new value in <paramref name="optionValue"/>. /// Calling this method adds capabilities to the Firefox-specific options object passed to /// geckodriver.exe (property name 'moz:firefoxOptions').</remarks> public void AddAdditionalFirefoxOption(string optionName, object optionValue) { this.ValidateCapabilityName(optionName); this.additionalFirefoxOptions[optionName] = optionValue; } /// <summary> /// Provides a means to add additional capabilities not yet added as type safe options /// for the Firefox driver. /// </summary> /// <param name="capabilityName">The name of the capability to add.</param> /// <param name="capabilityValue">The value of the capability to add.</param> /// <exception cref="ArgumentException"> /// thrown when attempting to add a capability for which there is already a type safe option, or /// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string. /// </exception> /// <remarks>Calling <see cref="AddAdditionalCapability(string, object)"/> /// where <paramref name="capabilityName"/> has already been added will overwrite the /// existing value with the new value in <paramref name="capabilityValue"/>. /// Also, by default, calling this method adds capabilities to the options object passed to /// geckodriver.exe.</remarks> [Obsolete("Use the temporary AddAdditionalOption method or the AddAdditionalFirefoxOption method for adding additional options")] public override void AddAdditionalCapability(string capabilityName, object capabilityValue) { // Add the capability to the FirefoxOptions object by default. This is to handle // the 80% case where the geckodriver team adds a new option in geckodriver.exe // and the bindings have not yet had a type safe option added. this.AddAdditionalFirefoxOption(capabilityName, capabilityValue); } /// <summary> /// Provides a means to add additional capabilities not yet added as type safe options /// for the Firefox driver. /// </summary> /// <param name="capabilityName">The name of the capability to add.</param> /// <param name="capabilityValue">The value of the capability to add.</param> /// <param name="isGlobalCapability">Indicates whether the capability is to be set as a global /// capability for the driver instead of a Firefox-specific option.</param> /// <exception cref="ArgumentException"> /// thrown when attempting to add a capability for which there is already a type safe option, or /// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string. /// </exception> /// <remarks>Calling <see cref="AddAdditionalCapability(string, object, bool)"/> /// where <paramref name="capabilityName"/> has already been added will overwrite the /// existing value with the new value in <paramref name="capabilityValue"/></remarks> [Obsolete("Use the temporary AddAdditionalOption method or the AddAdditionalFirefoxOption method for adding additional options")] public void AddAdditionalCapability(string capabilityName, object capabilityValue, bool isGlobalCapability) { if (isGlobalCapability) { this.AddAdditionalOption(capabilityName, capabilityValue); } else { this.AddAdditionalFirefoxOption(capabilityName, capabilityValue); } } /// <summary> /// Returns DesiredCapabilities for Firefox with these options included as /// capabilities. This does not copy the options. Further changes will be /// reflected in the returned capabilities. /// </summary> /// <returns>The DesiredCapabilities for Firefox with these options.</returns> public override ICapabilities ToCapabilities() { IWritableCapabilities capabilities = GenerateDesiredCapabilities(true); Dictionary<string, object> firefoxOptions = this.GenerateFirefoxOptionsDictionary(); capabilities.SetCapability(FirefoxOptionsCapability, firefoxOptions); if (this.enableDevToolsProtocol) { capabilities.SetCapability(FirefoxEnableDevToolsProtocolCapability, true); } return capabilities.AsReadOnly(); } private Dictionary<string, object> GenerateFirefoxOptionsDictionary() { Dictionary<string, object> firefoxOptions = new Dictionary<string, object>(); if (this.profile != null) { firefoxOptions[FirefoxProfileCapability] = this.profile.ToBase64String(); } if (!string.IsNullOrEmpty(this.browserBinaryLocation)) { firefoxOptions[FirefoxBinaryCapability] = this.browserBinaryLocation; } if (this.logLevel != FirefoxDriverLogLevel.Default) { Dictionary<string, object> logObject = new Dictionary<string, object>(); logObject["level"] = this.logLevel.ToString().ToLowerInvariant(); firefoxOptions[FirefoxLogCapability] = logObject; } if (this.firefoxArguments.Count > 0) { List<object> args = new List<object>(); foreach (string argument in this.firefoxArguments) { args.Add(argument); } firefoxOptions[FirefoxArgumentsCapability] = args; } if (this.profilePreferences.Count > 0) { firefoxOptions[FirefoxPrefsCapability] = this.profilePreferences; } if (this.environmentVariables.Count > 0) { firefoxOptions[FirefoxEnvCapability] = this.environmentVariables; } if (this.androidOptions != null) { this.AddAndroidOptions(firefoxOptions); } foreach (KeyValuePair<string, object> pair in this.additionalFirefoxOptions) { firefoxOptions.Add(pair.Key, pair.Value); } return firefoxOptions; } private void SetPreferenceValue(string preferenceName, object preferenceValue) { if (string.IsNullOrEmpty(preferenceName)) { throw new ArgumentException("Preference name may not be null an empty string.", nameof(preferenceName)); } this.profilePreferences[preferenceName] = preferenceValue; } private void AddAndroidOptions(Dictionary<string, object> firefoxOptions) { firefoxOptions["androidPackage"] = this.androidOptions.AndroidPackage; if (!string.IsNullOrEmpty(this.androidOptions.AndroidDeviceSerial)) { firefoxOptions["androidDeviceSerial"] = this.androidOptions.AndroidDeviceSerial; } if (!string.IsNullOrEmpty(this.androidOptions.AndroidActivity)) { firefoxOptions["androidActivity"] = this.androidOptions.AndroidActivity; } if (this.androidOptions.AndroidIntentArguments.Count > 0) { List<object> args = new List<object>(); foreach (string argument in this.androidOptions.AndroidIntentArguments) { args.Add(argument); } firefoxOptions["androidIntentArguments"] = args; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace Internal.Runtime.Augments { using Interop = global::Interop; /// due to the existence of <see cref="Internal.Interop"/> using OSThreadPriority = Interop.mincore.ThreadPriority; public sealed partial class RuntimeThread { [ThreadStatic] private static int t_reentrantWaitSuppressionCount; [ThreadStatic] private static ApartmentType t_apartmentType; private SafeWaitHandle _osHandle; /// <summary> /// Used by <see cref="WaitHandle"/>'s multi-wait functions /// </summary> private WaitHandleArray<IntPtr> _waitedHandles; private void PlatformSpecificInitialize() { _waitedHandles = new WaitHandleArray<IntPtr>(elementInitializer: null); } // Platform-specific initialization of foreign threads, i.e. threads not created by Thread.Start private void PlatformSpecificInitializeExistingThread() { _osHandle = GetOSHandleForCurrentThread(); } /// <summary> /// Callers must ensure to clear and return the array after use /// </summary> internal SafeWaitHandle[] RentWaitedSafeWaitHandleArray(int requiredCapacity) { Debug.Assert(this == CurrentThread); if (_waitedSafeWaitHandles.Items == null) { return null; } _waitedSafeWaitHandles.VerifyElementsAreDefault(); _waitedSafeWaitHandles.EnsureCapacity(requiredCapacity); return _waitedSafeWaitHandles.RentItems(); } internal void ReturnWaitedSafeWaitHandleArray(SafeWaitHandle[] waitedSafeWaitHandles) { Debug.Assert(this == CurrentThread); _waitedSafeWaitHandles.ReturnItems(waitedSafeWaitHandles); } /// <summary> /// Callers must ensure to return the array after use /// </summary> internal IntPtr[] RentWaitedHandleArray(int requiredCapacity) { Debug.Assert(this == CurrentThread); if (_waitedHandles.Items == null) { return null; } _waitedHandles.EnsureCapacity(requiredCapacity); return _waitedHandles.RentItems(); } internal void ReturnWaitedHandleArray(IntPtr[] waitedHandles) { Debug.Assert(this == CurrentThread); _waitedHandles.ReturnItems(waitedHandles); } private static SafeWaitHandle GetOSHandleForCurrentThread() { IntPtr currentProcHandle = Interop.mincore.GetCurrentProcess(); IntPtr currentThreadHandle = Interop.mincore.GetCurrentThread(); SafeWaitHandle threadHandle; if (Interop.mincore.DuplicateHandle(currentProcHandle, currentThreadHandle, currentProcHandle, out threadHandle, 0, false, (uint)Interop.Constants.DuplicateSameAccess)) { return threadHandle; } // Throw an ApplicationException for compatibility with CoreCLR. First save the error code. int errorCode = Marshal.GetLastWin32Error(); var ex = new ApplicationException(); ex.SetErrorCode(errorCode); throw ex; } private static ThreadPriority MapFromOSPriority(OSThreadPriority priority) { if (priority <= OSThreadPriority.Lowest) { // OS thread priorities in the [Idle,Lowest] range are mapped to ThreadPriority.Lowest return ThreadPriority.Lowest; } switch (priority) { case OSThreadPriority.BelowNormal: return ThreadPriority.BelowNormal; case OSThreadPriority.Normal: return ThreadPriority.Normal; case OSThreadPriority.AboveNormal: return ThreadPriority.AboveNormal; case OSThreadPriority.ErrorReturn: Debug.Fail("GetThreadPriority failed"); return ThreadPriority.Normal; } // Handle OSThreadPriority.ErrorReturn value before this check! if (priority >= OSThreadPriority.Highest) { // OS thread priorities in the [Highest,TimeCritical] range are mapped to ThreadPriority.Highest return ThreadPriority.Highest; } Debug.Fail("Unreachable"); return ThreadPriority.Normal; } private static OSThreadPriority MapToOSPriority(ThreadPriority priority) { switch (priority) { case ThreadPriority.Lowest: return OSThreadPriority.Lowest; case ThreadPriority.BelowNormal: return OSThreadPriority.BelowNormal; case ThreadPriority.Normal: return OSThreadPriority.Normal; case ThreadPriority.AboveNormal: return OSThreadPriority.AboveNormal; case ThreadPriority.Highest: return OSThreadPriority.Highest; default: Debug.Fail("Unreachable"); return OSThreadPriority.Normal; } } private ThreadPriority GetPriorityLive() { Debug.Assert(!_osHandle.IsInvalid); return MapFromOSPriority(Interop.mincore.GetThreadPriority(_osHandle)); } private bool SetPriorityLive(ThreadPriority priority) { Debug.Assert(!_osHandle.IsInvalid); return Interop.mincore.SetThreadPriority(_osHandle, (int)MapToOSPriority(priority)); } private ThreadState GetThreadState() { int state = _threadState; // If the thread is marked as alive, check if it has finished execution if ((state & (int)(ThreadState.Unstarted | ThreadState.Stopped | ThreadState.Aborted)) == 0) { if (JoinInternal(0)) { state = _threadState; if ((state & (int)(ThreadState.Stopped | ThreadState.Aborted)) == 0) { SetThreadStateBit(ThreadState.Stopped); state = _threadState; } } } return (ThreadState)state; } private bool JoinInternal(int millisecondsTimeout) { // This method assumes the thread has been started Debug.Assert(!GetThreadStateBit(ThreadState.Unstarted) || (millisecondsTimeout == 0)); SafeWaitHandle waitHandle = _osHandle; // If an OS thread is terminated and its Thread object is resurrected, _osHandle may be finalized and closed if (waitHandle.IsClosed) { return true; } // Handle race condition with the finalizer try { waitHandle.DangerousAddRef(); } catch (ObjectDisposedException) { return true; } try { int result; if (millisecondsTimeout == 0) { result = (int)Interop.mincore.WaitForSingleObject(waitHandle.DangerousGetHandle(), 0); } else { result = WaitHandle.WaitForSingleObject(waitHandle.DangerousGetHandle(), millisecondsTimeout, true); } return result == (int)Interop.Constants.WaitObject0; } finally { waitHandle.DangerousRelease(); } } private bool CreateThread(GCHandle thisThreadHandle) { const int AllocationGranularity = 0x10000; // 64 KiB int stackSize = _maxStackSize; if ((0 < stackSize) && (stackSize < AllocationGranularity)) { // If StackSizeParamIsAReservation flag is set and the reserve size specified by CreateThread's // dwStackSize parameter is less than or equal to the initially committed stack size specified in // the executable header, the reserve size will be set to the initially committed size rounded up // to the nearest multiple of 1 MiB. In all cases the reserve size is rounded up to the nearest // multiple of the system's allocation granularity (typically 64 KiB). // // To prevent overreservation of stack memory for small stackSize values, we increase stackSize to // the allocation granularity. We assume that the SizeOfStackCommit field of IMAGE_OPTIONAL_HEADER // is strictly smaller than the allocation granularity (the field's default value is 4 KiB); // otherwise, at least 1 MiB of memory will be reserved. Note that the desktop CLR increases // stackSize to 256 KiB if it is smaller than that. stackSize = AllocationGranularity; } uint threadId; _osHandle = Interop.mincore.CreateThread(IntPtr.Zero, (IntPtr)stackSize, AddrofIntrinsics.AddrOf<Interop.mincore.ThreadProc>(ThreadEntryPoint), (IntPtr)thisThreadHandle, (uint)(Interop.Constants.CreateSuspended | Interop.Constants.StackSizeParamIsAReservation), out threadId); if (_osHandle.IsInvalid) { return false; } // CoreCLR ignores OS errors while setting the priority, so do we SetPriorityLive(_priority); Interop.mincore.ResumeThread(_osHandle); return true; } /// <summary> /// This is an entry point for managed threads created by application /// </summary> [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static uint ThreadEntryPoint(IntPtr parameter) { StartThread(parameter); return 0; } public ApartmentState GetApartmentState() { throw null; } public bool TrySetApartmentState(ApartmentState state) { throw null; } public void DisableComObjectEagerCleanup() { throw null; } public void Interrupt() { throw null; } internal static void UninterruptibleSleep0() { Interop.mincore.Sleep(0); } private static void SleepInternal(int millisecondsTimeout) { Debug.Assert(millisecondsTimeout >= -1); Interop.mincore.Sleep((uint)millisecondsTimeout); } // // Suppresses reentrant waits on the current thread, until a matching call to RestoreReentrantWaits. // This should be used by code that's expected to be called inside the STA message pump, so that it won't // reenter itself. In an ASTA, this should only be the CCW implementations of IUnknown and IInspectable. // internal static void SuppressReentrantWaits() { t_reentrantWaitSuppressionCount++; } internal static void RestoreReentrantWaits() { Debug.Assert(t_reentrantWaitSuppressionCount > 0); t_reentrantWaitSuppressionCount--; } internal static bool ReentrantWaitsEnabled => GetCurrentApartmentType() == ApartmentType.STA && t_reentrantWaitSuppressionCount == 0; internal static ApartmentType GetCurrentApartmentType() { ApartmentType currentThreadType = t_apartmentType; if (currentThreadType != ApartmentType.Unknown) return currentThreadType; Interop._APTTYPE aptType; Interop._APTTYPEQUALIFIER aptTypeQualifier; int result = Interop.mincore.CoGetApartmentType(out aptType, out aptTypeQualifier); ApartmentType type = ApartmentType.Unknown; switch ((Interop.Constants)result) { case Interop.Constants.CoENotInitialized: type = ApartmentType.None; break; case Interop.Constants.SOk: switch (aptType) { case Interop._APTTYPE.APTTYPE_STA: case Interop._APTTYPE.APTTYPE_MAINSTA: type = ApartmentType.STA; break; case Interop._APTTYPE.APTTYPE_MTA: type = ApartmentType.MTA; break; case Interop._APTTYPE.APTTYPE_NA: switch (aptTypeQualifier) { case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_MTA: case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_IMPLICIT_MTA: type = ApartmentType.MTA; break; case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_STA: case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_MAINSTA: type = ApartmentType.STA; break; default: Debug.Assert(false, "NA apartment without NA qualifier"); break; } break; } break; default: Debug.Assert(false, "bad return from CoGetApartmentType"); break; } if (type != ApartmentType.Unknown) t_apartmentType = type; return type; } internal enum ApartmentType { Unknown = 0, None, STA, MTA } } }
/* * 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 OpenMetaverse; using OpenSim.Region.Physics.Manager; using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; namespace OpenSim.Region.Physics.Meshing { public class Mesh : IMesh { public float[] m_normals; private int m_indexCount = 0; private IntPtr m_indicesPtr = IntPtr.Zero; private GCHandle m_pinnedIndex; private GCHandle m_pinnedVertexes; private List<Triangle> m_triangles; private int m_vertexCount = 0; private Dictionary<Vertex, int> m_vertices; private IntPtr m_verticesPtr = IntPtr.Zero; public Mesh() { m_vertices = new Dictionary<Vertex, int>(); m_triangles = new List<Triangle>(); } public void Add(Triangle triangle) { if (m_pinnedIndex.IsAllocated || m_pinnedVertexes.IsAllocated || m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero) throw new NotSupportedException("Attempt to Add to a pinned Mesh"); // If a vertex of the triangle is not yet in the vertices list, // add it and set its index to the current index count if (!m_vertices.ContainsKey(triangle.v1)) m_vertices[triangle.v1] = m_vertices.Count; if (!m_vertices.ContainsKey(triangle.v2)) m_vertices[triangle.v2] = m_vertices.Count; if (!m_vertices.ContainsKey(triangle.v3)) m_vertices[triangle.v3] = m_vertices.Count; m_triangles.Add(triangle); } public void Append(IMesh newMesh) { if (m_pinnedIndex.IsAllocated || m_pinnedVertexes.IsAllocated || m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero) throw new NotSupportedException("Attempt to Append to a pinned Mesh"); if (!(newMesh is Mesh)) return; foreach (Triangle t in ((Mesh)newMesh).m_triangles) Add(t); } public void CalcNormals() { int iTriangles = m_triangles.Count; this.m_normals = new float[iTriangles * 3]; int i = 0; foreach (Triangle t in m_triangles) { float ux, uy, uz; float vx, vy, vz; float wx, wy, wz; ux = t.v1.X; uy = t.v1.Y; uz = t.v1.Z; vx = t.v2.X; vy = t.v2.Y; vz = t.v2.Z; wx = t.v3.X; wy = t.v3.Y; wz = t.v3.Z; // Vectors for edges float e1x, e1y, e1z; float e2x, e2y, e2z; e1x = ux - vx; e1y = uy - vy; e1z = uz - vz; e2x = ux - wx; e2y = uy - wy; e2z = uz - wz; // Cross product for normal float nx, ny, nz; nx = e1y * e2z - e1z * e2y; ny = e1z * e2x - e1x * e2z; nz = e1x * e2y - e1y * e2x; // Length float l = (float)Math.Sqrt(nx * nx + ny * ny + nz * nz); float lReciprocal = 1.0f / l; // Normalized "normal" //nx /= l; //ny /= l; //nz /= l; m_normals[i] = nx * lReciprocal; m_normals[i + 1] = ny * lReciprocal; m_normals[i + 2] = nz * lReciprocal; i += 3; } } public Mesh Clone() { Mesh result = new Mesh(); foreach (Triangle t in m_triangles) { result.Add(new Triangle(t.v1.Clone(), t.v2.Clone(), t.v3.Clone())); } return result; } public void DumpRaw(String path, String name, String title) { if (path == null) return; String fileName = name + "_" + title + ".raw"; String completePath = System.IO.Path.Combine(path, fileName); StreamWriter sw = new StreamWriter(completePath); foreach (Triangle t in m_triangles) { String s = t.ToStringRaw(); sw.WriteLine(s); } sw.Close(); } public int[] getIndexListAsInt() { if (m_triangles == null) throw new NotSupportedException(); int[] result = new int[m_triangles.Count * 3]; for (int i = 0; i < m_triangles.Count; i++) { Triangle t = m_triangles[i]; result[3 * i + 0] = m_vertices[t.v1]; result[3 * i + 1] = m_vertices[t.v2]; result[3 * i + 2] = m_vertices[t.v3]; } return result; } /// <summary> /// creates a list of index values that defines triangle faces. THIS METHOD FREES ALL NON-PINNED MESH DATA /// </summary> /// <returns></returns> public int[] getIndexListAsIntLocked() { if (m_pinnedIndex.IsAllocated) return (int[])(m_pinnedIndex.Target); int[] result = getIndexListAsInt(); m_pinnedIndex = GCHandle.Alloc(result, GCHandleType.Pinned); // Inform the garbage collector of this unmanaged allocation so it can schedule // the next GC round more intelligently GC.AddMemoryPressure(Buffer.ByteLength(result)); return result; } public void getIndexListAsPtrToIntArray(out IntPtr indices, out int triStride, out int indexCount) { // If there isn't an unmanaged array allocated yet, do it now if (m_indicesPtr == IntPtr.Zero) { int[] indexList = getIndexListAsInt(); m_indexCount = indexList.Length; int byteCount = m_indexCount * sizeof(int); m_indicesPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(byteCount); System.Runtime.InteropServices.Marshal.Copy(indexList, 0, m_indicesPtr, m_indexCount); } // A triangle is 3 ints (indices) triStride = 3 * sizeof(int); indices = m_indicesPtr; indexCount = m_indexCount; } public List<Vector3> getVertexList() { List<Vector3> result = new List<Vector3>(); foreach (Vertex v in m_vertices.Keys) { result.Add(new Vector3(v.X, v.Y, v.Z)); } return result; } public float[] getVertexListAsFloat() { if (m_vertices == null) throw new NotSupportedException(); float[] result = new float[m_vertices.Count * 3]; foreach (KeyValuePair<Vertex, int> kvp in m_vertices) { Vertex v = kvp.Key; int i = kvp.Value; result[3 * i + 0] = v.X; result[3 * i + 1] = v.Y; result[3 * i + 2] = v.Z; } return result; } public float[] getVertexListAsFloatLocked() { if (m_pinnedVertexes.IsAllocated) return (float[])(m_pinnedVertexes.Target); float[] result = getVertexListAsFloat(); m_pinnedVertexes = GCHandle.Alloc(result, GCHandleType.Pinned); // Inform the garbage collector of this unmanaged allocation so it can schedule // the next GC round more intelligently GC.AddMemoryPressure(Buffer.ByteLength(result)); return result; } public void getVertexListAsPtrToFloatArray(out IntPtr vertices, out int vertexStride, out int vertexCount) { // A vertex is 3 floats vertexStride = 3 * sizeof(float); // If there isn't an unmanaged array allocated yet, do it now if (m_verticesPtr == IntPtr.Zero) { float[] vertexList = getVertexListAsFloat(); // Each vertex is 3 elements (floats) m_vertexCount = vertexList.Length / 3; int byteCount = m_vertexCount * vertexStride; m_verticesPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(byteCount); System.Runtime.InteropServices.Marshal.Copy(vertexList, 0, m_verticesPtr, m_vertexCount * 3); } vertices = m_verticesPtr; vertexCount = m_vertexCount; } public void releasePinned() { if (m_pinnedVertexes.IsAllocated) m_pinnedVertexes.Free(); if (m_pinnedIndex.IsAllocated) m_pinnedIndex.Free(); if (m_verticesPtr != IntPtr.Zero) { System.Runtime.InteropServices.Marshal.FreeHGlobal(m_verticesPtr); m_verticesPtr = IntPtr.Zero; } if (m_indicesPtr != IntPtr.Zero) { System.Runtime.InteropServices.Marshal.FreeHGlobal(m_indicesPtr); m_indicesPtr = IntPtr.Zero; } } /// <summary> /// frees up the source mesh data to minimize memory - call this method after calling get*Locked() functions /// </summary> public void releaseSourceMeshData() { m_triangles = null; m_vertices = null; } // Do a linear transformation of mesh. public void TransformLinear(float[,] matrix, float[] offset) { if (m_pinnedIndex.IsAllocated || m_pinnedVertexes.IsAllocated || m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero) throw new NotSupportedException("Attempt to TransformLinear a pinned Mesh"); foreach (Vertex v in m_vertices.Keys) { if (v == null) continue; float x, y, z; x = v.X * matrix[0, 0] + v.Y * matrix[1, 0] + v.Z * matrix[2, 0]; y = v.X * matrix[0, 1] + v.Y * matrix[1, 1] + v.Z * matrix[2, 1]; z = v.X * matrix[0, 2] + v.Y * matrix[1, 2] + v.Z * matrix[2, 2]; v.X = x + offset[0]; v.Y = y + offset[1]; v.Z = z + offset[2]; } } public void TrimExcess() { m_triangles.TrimExcess(); } } }
/* * Copyright 2020 Sage Intacct, 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 * * or in the "LICENSE" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using Intacct.SDK.Exceptions; using Intacct.SDK.Functions; using Intacct.SDK.Functions.Common.NewQuery; using Intacct.SDK.Functions.Common.NewQuery.QueryFilter; using Intacct.SDK.Functions.Common.NewQuery.QueryOrderBy; using Intacct.SDK.Functions.Common.NewQuery.QuerySelect; using Intacct.SDK.Tests.Xml; using Intacct.SDK.Xml; using Xunit; namespace Intacct.SDK.Tests.Functions.Common.NewQuery { public class QueryTest : XmlObjectTestHelper { [Fact] public void DefaultParamsTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <query> <select> <field>CUSTOMERID</field> </select> <object>CUSTOMER</object> <options /> </query> </function>"; SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Field("CUSTOMERID").GetFields(); IQueryFunction query = new QueryFunction("unittest") { FromObject = "CUSTOMER", SelectFields = fields }; this.CompareXml(expected, query); } [Fact] public void AllParamsTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <query> <select> <field>CUSTOMERID</field> <field>RECORDNO</field> </select> <object>CUSTOMER</object> <docparid>REPORT</docparid> <options> <caseinsensitive>true</caseinsensitive> <showprivate>true</showprivate> </options> <pagesize>10</pagesize> <offset>5</offset> </query> </function>"; SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Field("CUSTOMERID").Field("RECORDNO").GetFields(); IQueryFunction query = new QueryFunction("unittest") { FromObject = "CUSTOMER", DocParId = "REPORT", SelectFields = fields, CaseInsensitive = true, ShowPrivate = true, PageSize = 10, Offset = 5 }; this.CompareXml(expected, query); } [Fact] public void EmptySelectTest() { Stream stream = new MemoryStream(); XmlWriterSettings xmlSettings = new XmlWriterSettings { Encoding = Encoding.GetEncoding("UTF-8") }; IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings); IQueryFunction query = new QueryFunction("unittest") { SelectFields = new ISelect[0] }; var ex = Record.Exception(() => query.WriteXml(ref xml)); Assert.IsType<ArgumentException>(ex); Assert.Equal("Select fields are required for query; set through method SelectFields setter.", ex.Message); } [Fact] public void MissingObjectTest() { Stream stream = new MemoryStream(); XmlWriterSettings xmlSettings = new XmlWriterSettings { Encoding = Encoding.GetEncoding("UTF-8") }; IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings); SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Field("CUSTOMERID").GetFields(); IQueryFunction query = new QueryFunction("unittest") { SelectFields = fields }; var ex = Record.Exception(() => query.WriteXml(ref xml)); Assert.IsType<ArgumentException>(ex); Assert.Equal("From Object is required for query; set through method from setter.", ex.Message); } [Fact] public void NoSelectFieldsTest() { Stream stream = new MemoryStream(); XmlWriterSettings xmlSettings = new XmlWriterSettings { Encoding = Encoding.GetEncoding("UTF-8") }; IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings); IQueryFunction query = new QueryFunction("unittest") { FromObject = "CUSTOMER" }; var ex = Record.Exception(() => query.WriteXml(ref xml)); Assert.IsType<ArgumentException>(ex); Assert.Equal("Select fields are required for query; set through method SelectFields setter.", ex.Message); } [Fact] public void EmptyObjectNameTest() { Stream stream = new MemoryStream(); XmlWriterSettings xmlSettings = new XmlWriterSettings { Encoding = Encoding.GetEncoding("UTF-8") }; IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings); SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Field("CUSTOMERID").GetFields(); IQueryFunction query = new QueryFunction("unittest") { FromObject = "", SelectFields = fields }; var ex = Record.Exception(() => query.WriteXml(ref xml)); Assert.IsType<ArgumentException>(ex); Assert.Equal("From Object is required for query; set through method from setter.", ex.Message); } [Fact] public void NegativeOffsetTest() { SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Field("CUSTOMERID").GetFields(); QueryFunction query = new QueryFunction("unittest") { FromObject = "CUSTOMER", SelectFields = fields, }; var ex = Record.Exception(() => query.Offset = -1); Assert.IsType<IntacctException>(ex); Assert.Equal("Offset cannot be negative. Set Offset to zero or greater than zero.", ex.Message); } [Fact] public void NegativePagesizeTest() { SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Field("CUSTOMERID").GetFields(); QueryFunction query = new QueryFunction("unittest") { FromObject = "CUSTOMER", SelectFields = fields, }; var ex = Record.Exception(() => query.PageSize = -1); Assert.IsType<IntacctException>(ex); Assert.Equal("PageSize cannot be negative. Set PageSize greater than zero.", ex.Message); } [Fact] public void EmptyFieldNameForAscendingTest() { var ex = Record.Exception(() => (new OrderBuilder()).Ascending("")); Assert.IsType<ArgumentException>(ex); Assert.Equal("Field name for field cannot be empty or null. Provide a field for the builder.", ex.Message); } [Fact] public void EmptyFieldNameForDescendingTest() { var ex = Record.Exception(() => (new OrderBuilder()).Descending("")); Assert.IsType<ArgumentException>(ex); Assert.Equal("Field name for field cannot be empty or null. Provide a field for the builder.", ex.Message); } [Fact] public void FieldsTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <query> <select> <field>CUSTOMERID</field> <field>TOTALDUE</field> <field>WHENDUE</field> <field>TOTALENTERED</field> <field>TOTALDUE</field> <field>RECORDNO</field> </select> <object>ARINVOICE</object> <options /> </query> </function>"; string[] fieldNames = { "CUSTOMERID", "TOTALDUE", "WHENDUE", "TOTALENTERED", "TOTALDUE", "RECORDNO" }; SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Fields(fieldNames).GetFields(); IQueryFunction query = new QueryFunction("unittest") { FromObject = "ARINVOICE", SelectFields = fields }; this.CompareXml(expected, query); } [Fact] public void AggregateFunctionsTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <query> <select> <field>CUSTOMERID</field> <avg>TOTALDUE</avg> <min>WHENDUE</min> <max>TOTALENTERED</max> <sum>TOTALDUE</sum> <count>RECORDNO</count> </select> <object>ARINVOICE</object> <options /> </query> </function>"; SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Field("CUSTOMERID"). Average("TOTALDUE"). Minimum("WHENDUE"). Maximum("TOTALENTERED"). Sum("TOTALDUE"). Count("RECORDNO"). GetFields(); IQueryFunction query = new QueryFunction("unittest") { FromObject = "ARINVOICE", SelectFields = fields }; this.CompareXml(expected, query); } [Fact] public void OrderByTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <query> <select> <field>CUSTOMERID</field> </select> <object>CLASS</object> <orderby> <order> <field>TOTALDUE</field> <ascending /> </order> <order> <field>RECORDNO</field> <descending /> </order> </orderby> <options /> </query> </function>"; SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Field("CUSTOMERID").GetFields(); IOrder[] orderBy = (new OrderBuilder()).Ascending("TOTALDUE").Descending("RECORDNO").GetOrders(); IQueryFunction query = new QueryFunction("unittest") { FromObject = "CLASS", SelectFields = fields, OrderBy = orderBy }; this.CompareXml(expected, query); } [Fact] public void EmptyOrderByTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <query> <select> <field>CUSTOMERID</field> </select> <object>CLASS</object> <options /> </query> </function>"; SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Field("CUSTOMERID").GetFields(); IQueryFunction query = new QueryFunction("unittest") { FromObject = "CLASS", SelectFields = fields, OrderBy = new IOrder[0] }; this.CompareXml(expected, query); } [Fact] public void FilterTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <query> <select> <field>CUSTOMERID</field> <field>RECORDNO</field> </select> <object>ARINVOICE</object> <filter> <lessthanorequalto> <field>RECORDNO</field> <value>10</value> </lessthanorequalto> </filter> <options /> </query> </function>"; SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Fields(new[] {"CUSTOMERID", "RECORDNO"}).GetFields(); IFilter filter = (new Filter("RECORDNO")).SetLessThanOrEqualTo("10"); IQueryFunction query = new QueryFunction("unittest") { FromObject = "ARINVOICE", SelectFields = fields, Filter = filter }; this.CompareXml(expected, query); } [Fact] public void FilterAndConditionTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <query> <select> <field>CUSTOMERID</field> <field>RECORDNO</field> </select> <object>ARINVOICE</object> <filter> <and> <greaterthanorequalto> <field>RECORDNO</field> <value>1</value> </greaterthanorequalto> <lessthanorequalto> <field>RECORDNO</field> <value>100</value> </lessthanorequalto> </and> </filter> <options /> </query> </function>"; SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Fields(new[] {"CUSTOMERID","RECORDNO"}).GetFields(); AndOperator filter = new AndOperator(new List<IFilter>()); filter.AddFilter((new Filter("RECORDNO")).SetGreaterThanOrEqualTo("1")); filter.AddFilter((new Filter("RECORDNO")).SetLessThanOrEqualTo("100")); IQueryFunction query = new QueryFunction("unittest") { FromObject = "ARINVOICE", SelectFields = fields, Filter = filter }; this.CompareXml(expected, query); } [Fact] public void FilterOrConditionTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <query> <select> <field>CUSTOMERID</field> <field>RECORDNO</field> </select> <object>ARINVOICE</object> <filter> <or> <lessthanorequalto> <field>RECORDNO</field> <value>10</value> </lessthanorequalto> <equalto> <field>RECORDNO</field> <value>100</value> </equalto> <equalto> <field>RECORDNO</field> <value>1000</value> </equalto> <equalto> <field>RECORDNO</field> <value>10000</value> </equalto> </or> </filter> <options /> </query> </function>"; SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Fields(new[] {"CUSTOMERID","RECORDNO"}).GetFields(); OrOperator filter = new OrOperator(new List<IFilter>()); filter.AddFilter((new Filter("RECORDNO")).SetLessThanOrEqualTo("10")); filter.AddFilter((new Filter("RECORDNO")).SetEqualTo("100")); filter.AddFilter((new Filter("RECORDNO")).SetEqualTo("1000")); filter.AddFilter((new Filter("RECORDNO")).SetEqualTo("10000")); IQueryFunction query = new QueryFunction("unittest") { FromObject = "ARINVOICE", SelectFields = fields, Filter = filter }; this.CompareXml(expected, query); } [Fact] public void FilterOrWithAndConditionTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <query> <select> <field>BATCHNO</field> <field>RECORDNO</field> <field>STATE</field> </select> <object>GLBATCH</object> <filter> <or> <equalto> <field>JOURNAL</field> <value>APJ</value> </equalto> <and> <greaterthanorequalto> <field>BATCHNO</field> <value>1</value> </greaterthanorequalto> <equalto> <field>STATE</field> <value>Posted</value> </equalto> </and> </or> </filter> <options /> </query> </function>"; SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Fields(new[] {"BATCHNO","RECORDNO","STATE"}).GetFields(); AndOperator batchnoAndState = new AndOperator(new List<IFilter>()); batchnoAndState.AddFilter((new Filter("BATCHNO")).SetGreaterThanOrEqualTo("1")); batchnoAndState.AddFilter((new Filter("STATE")).SetEqualTo("Posted")); IFilter journal = new Filter("JOURNAL").SetEqualTo("APJ"); IFilter filter = new OrOperator(new List<IFilter>(){journal, batchnoAndState}); IQueryFunction query = new QueryFunction("unittest") { FromObject = "GLBATCH", SelectFields = fields, Filter = filter }; this.CompareXml(expected, query); } [Fact] public void ThreeLevelFilterTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <query> <select> <field>BATCHNO</field> <field>RECORDNO</field> <field>STATE</field> </select> <object>GLBATCH</object> <filter> <or> <and> <equalto> <field>JOURNAL</field> <value>APJ</value> </equalto> <equalto> <field>STATE</field> <value>Posted</value> </equalto> </and> <and> <equalto> <field>JOURNAL</field> <value>RCPT</value> </equalto> <equalto> <field>STATE</field> <value>Posted</value> </equalto> <or> <equalto> <field>RECORDNO</field> <value>168</value> </equalto> <equalto> <field>RECORDNO</field> <value>132</value> </equalto> </or> </and> </or> </filter> <options /> </query> </function>"; SelectBuilder builder = new SelectBuilder(); ISelect[] fields = builder.Fields(new[] {"BATCHNO","RECORDNO","STATE"}).GetFields(); AndOperator apjAndState = new AndOperator(new List<IFilter>()); apjAndState.AddFilter((new Filter("JOURNAL")).SetEqualTo("APJ")); apjAndState.AddFilter((new Filter("STATE")).SetEqualTo("Posted")); OrOperator recordnoOr = new OrOperator(new List<IFilter>()); recordnoOr.AddFilter((new Filter("RECORDNO")).SetEqualTo("168")); recordnoOr.AddFilter((new Filter("RECORDNO")).SetEqualTo("132")); AndOperator rcptAndState = new AndOperator(new List<IFilter>()); rcptAndState.AddFilter((new Filter("JOURNAL")).SetEqualTo("RCPT")); rcptAndState.AddFilter((new Filter("STATE")).SetEqualTo("Posted")); rcptAndState.AddFilter(recordnoOr); IFilter filter = new OrOperator(new List<IFilter>(){apjAndState, rcptAndState}); IFunction query = new QueryFunction("unittest") { FromObject = "GLBATCH", SelectFields = fields, Filter = filter }; this.CompareXml(expected, query); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Xml; using Nop.Core; using Nop.Core.Domain.Customers; using Nop.Core.Infrastructure; using Nop.Services.Common; using Nop.Services.Localization; namespace Nop.Services.Customers { public static class CustomerExtensions { /// <summary> /// Get full name /// </summary> /// <param name="customer">Customer</param> /// <returns>Customer full name</returns> public static string GetFullName(this Customer customer) { if (customer == null) throw new ArgumentNullException("customer"); var firstName = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName); var lastName = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastName); string fullName = ""; if (!String.IsNullOrWhiteSpace(firstName) && !String.IsNullOrWhiteSpace(lastName)) fullName = string.Format("{0} {1}", firstName, lastName); else { if (!String.IsNullOrWhiteSpace(firstName)) fullName = firstName; if (!String.IsNullOrWhiteSpace(lastName)) fullName = lastName; } return fullName; } /// <summary> /// Formats the customer name /// </summary> /// <param name="customer">Source</param> /// <param name="stripTooLong">Strip too long customer name</param> /// <param name="maxLength">Maximum customer name length</param> /// <returns>Formatted text</returns> public static string FormatUserName(this Customer customer, bool stripTooLong = false, int maxLength = 0) { if (customer == null) return string.Empty; if (customer.IsGuest()) { return EngineContext.Current.Resolve<ILocalizationService>().GetResource("Customer.Guest"); } string result = string.Empty; switch (EngineContext.Current.Resolve<CustomerSettings>().CustomerNameFormat) { case CustomerNameFormat.ShowEmails: result = customer.Email; break; case CustomerNameFormat.ShowUsernames: result = customer.Username; break; case CustomerNameFormat.ShowFullNames: result = customer.GetFullName(); break; case CustomerNameFormat.ShowFirstName: result = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName); break; default: break; } if (stripTooLong && maxLength > 0) { result = CommonHelper.EnsureMaximumLength(result, maxLength); } return result; } #region Gift cards /// <summary> /// Gets coupon codes /// </summary> /// <param name="customer">Customer</param> /// <returns>Coupon codes</returns> public static string[] ParseAppliedGiftCardCouponCodes(this Customer customer) { var genericAttributeService = EngineContext.Current.Resolve<IGenericAttributeService>(); string existingGiftCartCouponCodes = customer.GetAttribute<string>(SystemCustomerAttributeNames.GiftCardCouponCodes, genericAttributeService); var couponCodes = new List<string>(); if (String.IsNullOrEmpty(existingGiftCartCouponCodes)) return couponCodes.ToArray(); try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(existingGiftCartCouponCodes); var nodeList1 = xmlDoc.SelectNodes(@"//GiftCardCouponCodes/CouponCode"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["Code"] != null) { string code = node1.Attributes["Code"].InnerText.Trim(); couponCodes.Add(code); } } } catch (Exception exc) { Debug.Write(exc.ToString()); } return couponCodes.ToArray(); } /// <summary> /// Adds a coupon code /// </summary> /// <param name="customer">Customer</param> /// <param name="couponCode">Coupon code</param> /// <returns>New coupon codes document</returns> public static void ApplyGiftCardCouponCode(this Customer customer, string couponCode) { var genericAttributeService = EngineContext.Current.Resolve<IGenericAttributeService>(); string result = string.Empty; try { string existingGiftCartCouponCodes = customer.GetAttribute<string>(SystemCustomerAttributeNames.GiftCardCouponCodes, genericAttributeService); couponCode = couponCode.Trim().ToLower(); var xmlDoc = new XmlDocument(); if (String.IsNullOrEmpty(existingGiftCartCouponCodes)) { var element1 = xmlDoc.CreateElement("GiftCardCouponCodes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(existingGiftCartCouponCodes); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//GiftCardCouponCodes"); XmlElement gcElement = null; //find existing var nodeList1 = xmlDoc.SelectNodes(@"//GiftCardCouponCodes/CouponCode"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["Code"] != null) { string couponCodeAttribute = node1.Attributes["Code"].InnerText.Trim(); if (couponCodeAttribute.ToLower() == couponCode.ToLower()) { gcElement = (XmlElement)node1; break; } } } //create new one if not found if (gcElement == null) { gcElement = xmlDoc.CreateElement("CouponCode"); gcElement.SetAttribute("Code", couponCode); rootElement.AppendChild(gcElement); } result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } //apply new value genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.GiftCardCouponCodes, result); } /// <summary> /// Removes a coupon code /// </summary> /// <param name="customer">Customer</param> /// <param name="couponCode">Coupon code to remove</param> /// <returns>New coupon codes document</returns> public static void RemoveGiftCardCouponCode(this Customer customer, string couponCode) { //get applied coupon codes var existingCouponCodes = customer.ParseAppliedGiftCardCouponCodes(); //clear them var genericAttributeService = EngineContext.Current.Resolve<IGenericAttributeService>(); genericAttributeService.SaveAttribute<string>(customer, SystemCustomerAttributeNames.GiftCardCouponCodes, null); //save again except removed one foreach (string existingCouponCode in existingCouponCodes) if (!existingCouponCode.Equals(couponCode, StringComparison.InvariantCultureIgnoreCase)) customer.ApplyGiftCardCouponCode(existingCouponCode); } #endregion } }
using Lucene.Net.Documents; using Lucene.Net.Index; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using JCG = J2N.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using FixedBitSet = Lucene.Net.Util.FixedBitSet; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using NumericDocValuesField = NumericDocValuesField; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using SortedDocValuesField = SortedDocValuesField; using StoredField = StoredField; using TestUtil = Lucene.Net.Util.TestUtil; /// <summary> /// random sorting tests </summary> [TestFixture] public class TestSortRandom : LuceneTestCase { [Test] public virtual void TestRandomStringSort() { Random random = new Random(Random.Next()); int NUM_DOCS = AtLeast(100); Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif random, dir); bool allowDups = random.NextBoolean(); ISet<string> seen = new JCG.HashSet<string>(); int maxLength = TestUtil.NextInt32(random, 5, 100); if (Verbose) { Console.WriteLine("TEST: NUM_DOCS=" + NUM_DOCS + " maxLength=" + maxLength + " allowDups=" + allowDups); } int numDocs = 0; IList<BytesRef> docValues = new List<BytesRef>(); // TODO: deletions while (numDocs < NUM_DOCS) { Document doc = new Document(); // 10% of the time, the document is missing the value: BytesRef br; if (LuceneTestCase.Random.Next(10) != 7) { string s; if (random.NextBoolean()) { s = TestUtil.RandomSimpleString(random, maxLength); } else { s = TestUtil.RandomUnicodeString(random, maxLength); } if (!allowDups) { if (seen.Contains(s)) { continue; } seen.Add(s); } if (Verbose) { Console.WriteLine(" " + numDocs + ": s=" + s); } br = new BytesRef(s); if (DefaultCodecSupportsDocValues) { doc.Add(new SortedDocValuesField("stringdv", br)); doc.Add(new NumericDocValuesField("id", numDocs)); } else { doc.Add(NewStringField("id", Convert.ToString(numDocs), Field.Store.NO)); } doc.Add(NewStringField("string", s, Field.Store.NO)); docValues.Add(br); } else { br = null; if (Verbose) { Console.WriteLine(" " + numDocs + ": <missing>"); } docValues.Add(null); if (DefaultCodecSupportsDocValues) { doc.Add(new NumericDocValuesField("id", numDocs)); } else { doc.Add(NewStringField("id", Convert.ToString(numDocs), Field.Store.NO)); } } doc.Add(new StoredField("id", numDocs)); writer.AddDocument(doc); numDocs++; if (random.Next(40) == 17) { // force flush writer.GetReader().Dispose(); } } IndexReader r = writer.GetReader(); writer.Dispose(); if (Verbose) { Console.WriteLine(" reader=" + r); } IndexSearcher idxS = NewSearcher( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif r, false); int ITERS = AtLeast(100); for (int iter = 0; iter < ITERS; iter++) { bool reverse = random.NextBoolean(); TopFieldDocs hits; SortField sf; bool sortMissingLast; bool missingIsNull; if (DefaultCodecSupportsDocValues && random.NextBoolean()) { sf = new SortField("stringdv", SortFieldType.STRING, reverse); // Can only use sort missing if the DVFormat // supports docsWithField: sortMissingLast = DefaultCodecSupportsDocsWithField && Random.NextBoolean(); missingIsNull = DefaultCodecSupportsDocsWithField; } else { sf = new SortField("string", SortFieldType.STRING, reverse); sortMissingLast = Random.NextBoolean(); missingIsNull = true; } if (sortMissingLast) { sf.MissingValue = SortField.STRING_LAST; } Sort sort; if (random.NextBoolean()) { sort = new Sort(sf); } else { sort = new Sort(sf, SortField.FIELD_DOC); } int hitCount = TestUtil.NextInt32(random, 1, r.MaxDoc + 20); RandomFilter f = new RandomFilter(random, (float)random.NextDouble(), docValues); int queryType = random.Next(3); if (queryType == 0) { // force out of order BooleanQuery bq = new BooleanQuery(); // Add a Query with SHOULD, since bw.Scorer() returns BooleanScorer2 // which delegates to BS if there are no mandatory clauses. bq.Add(new MatchAllDocsQuery(), Occur.SHOULD); // Set minNrShouldMatch to 1 so that BQ will not optimize rewrite to return // the clause instead of BQ. bq.MinimumNumberShouldMatch = 1; hits = idxS.Search(bq, f, hitCount, sort, random.NextBoolean(), random.NextBoolean()); } else if (queryType == 1) { hits = idxS.Search(new ConstantScoreQuery(f), null, hitCount, sort, random.NextBoolean(), random.NextBoolean()); } else { hits = idxS.Search(new MatchAllDocsQuery(), f, hitCount, sort, random.NextBoolean(), random.NextBoolean()); } if (Verbose) { Console.WriteLine("\nTEST: iter=" + iter + " " + hits.TotalHits + " hits; topN=" + hitCount + "; reverse=" + reverse + "; sortMissingLast=" + sortMissingLast + " sort=" + sort); } // Compute expected results: var expected = f.matchValues.ToList(); expected.Sort(Comparer<BytesRef>.Create((a,b) => { if (a == null) { if (b == null) { return 0; } if (sortMissingLast) { return 1; } else { return -1; } } else if (b == null) { if (sortMissingLast) { return -1; } else { return 1; } } else { return a.CompareTo(b); } })); if (reverse) { expected.Reverse(); } if (Verbose) { Console.WriteLine(" expected:"); for (int idx = 0; idx < expected.Count; idx++) { BytesRef br = expected[idx]; if (br == null && missingIsNull == false) { br = new BytesRef(); } Console.WriteLine(" " + idx + ": " + (br == null ? "<missing>" : br.Utf8ToString())); if (idx == hitCount - 1) { break; } } } if (Verbose) { Console.WriteLine(" actual:"); for (int hitIDX = 0; hitIDX < hits.ScoreDocs.Length; hitIDX++) { FieldDoc fd = (FieldDoc)hits.ScoreDocs[hitIDX]; BytesRef br = (BytesRef)fd.Fields[0]; Console.WriteLine(" " + hitIDX + ": " + (br == null ? "<missing>" : br.Utf8ToString()) + " id=" + idxS.Doc(fd.Doc).Get("id")); } } for (int hitIDX = 0; hitIDX < hits.ScoreDocs.Length; hitIDX++) { FieldDoc fd = (FieldDoc)hits.ScoreDocs[hitIDX]; BytesRef br = expected[hitIDX]; if (br == null && missingIsNull == false) { br = new BytesRef(); } // Normally, the old codecs (that don't support // docsWithField via doc values) will always return // an empty BytesRef for the missing case; however, // if all docs in a given segment were missing, in // that case it will return null! So we must map // null here, too: BytesRef br2 = (BytesRef)fd.Fields[0]; if (br2 == null && missingIsNull == false) { br2 = new BytesRef(); } Assert.AreEqual(br, br2, "hit=" + hitIDX + " has wrong sort value"); } } r.Dispose(); dir.Dispose(); } private class RandomFilter : Filter { private readonly Random random; private readonly float density; private readonly IList<BytesRef> docValues; public readonly IList<BytesRef> matchValues = new SynchronizedList<BytesRef>(); // density should be 0.0 ... 1.0 public RandomFilter(Random random, float density, IList<BytesRef> docValues) { this.random = random; this.density = density; this.docValues = docValues; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { int maxDoc = context.Reader.MaxDoc; FieldCache.Int32s idSource = FieldCache.DEFAULT.GetInt32s(context.AtomicReader, "id", false); Assert.IsNotNull(idSource); FixedBitSet bits = new FixedBitSet(maxDoc); for (int docID = 0; docID < maxDoc; docID++) { if ((float)random.NextDouble() <= density && (acceptDocs == null || acceptDocs.Get(docID))) { bits.Set(docID); //System.out.println(" acc id=" + idSource.Get(docID) + " docID=" + docID + " id=" + idSource.Get(docID) + " v=" + docValues.Get(idSource.Get(docID)).Utf8ToString()); matchValues.Add(docValues[idSource.Get(docID)]); } } return bits; } } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using Google.Protobuf.Compatibility; using System; using System.Reflection; namespace Google.Protobuf.Reflection { /// <summary> /// The methods in this class are somewhat evil, and should not be tampered with lightly. /// Basically they allow the creation of relatively weakly typed delegates from MethodInfos /// which are more strongly typed. They do this by creating an appropriate strongly typed /// delegate from the MethodInfo, and then calling that within an anonymous method. /// Mind-bending stuff (at least to your humble narrator) but the resulting delegates are /// very fast compared with calling Invoke later on. /// </summary> internal static class ReflectionUtil { static ReflectionUtil() { ForceInitialize<string>(); // Handles all reference types ForceInitialize<int>(); ForceInitialize<long>(); ForceInitialize<uint>(); ForceInitialize<ulong>(); ForceInitialize<float>(); ForceInitialize<double>(); ForceInitialize<bool>(); ForceInitialize<int?>(); ForceInitialize<long?>(); ForceInitialize<uint?>(); ForceInitialize<ulong?>(); ForceInitialize<float?>(); ForceInitialize<double?>(); ForceInitialize<bool?>(); ForceInitialize<SampleEnum>(); SampleEnumMethod(); } internal static void ForceInitialize<T>() => new ReflectionHelper<IMessage, T>(); /// <summary> /// Empty Type[] used when calling GetProperty to force property instead of indexer fetching. /// </summary> internal static readonly Type[] EmptyTypes = new Type[0]; /// <summary> /// Creates a delegate which will cast the argument to the type that declares the method, /// call the method on it, then convert the result to object. /// </summary> /// <param name="method">The method to create a delegate for, which must be declared in an IMessage /// implementation.</param> internal static Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method) => GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageObject(method); /// <summary> /// Creates a delegate which will cast the argument to the type that declares the method, /// call the method on it, then convert the result to the specified type. The method is expected /// to actually return an enum (because of where we're calling it - for oneof cases). Sometimes that /// means we need some extra work to perform conversions. /// </summary> /// <param name="method">The method to create a delegate for, which must be declared in an IMessage /// implementation.</param> internal static Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method) => GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageInt32(method); /// <summary> /// Creates a delegate which will execute the given method after casting the first argument to /// the type that declares the method, and the second argument to the first parameter type of the method. /// </summary> /// <param name="method">The method to create a delegate for, which must be declared in an IMessage /// implementation.</param> internal static Action<IMessage, object> CreateActionIMessageObject(MethodInfo method) => GetReflectionHelper(method.DeclaringType, method.GetParameters()[0].ParameterType).CreateActionIMessageObject(method); /// <summary> /// Creates a delegate which will execute the given method after casting the first argument to /// type that declares the method. /// </summary> /// <param name="method">The method to create a delegate for, which must be declared in an IMessage /// implementation.</param> internal static Action<IMessage> CreateActionIMessage(MethodInfo method) => GetReflectionHelper(method.DeclaringType, typeof(object)).CreateActionIMessage(method); /// <summary> /// Creates a reflection helper for the given type arguments. Currently these are created on demand /// rather than cached; this will be "busy" when initially loading a message's descriptor, but after that /// they can be garbage collected. We could cache them by type if that proves to be important, but creating /// an object is pretty cheap. /// </summary> private static IReflectionHelper GetReflectionHelper(Type t1, Type t2) => (IReflectionHelper) Activator.CreateInstance(typeof(ReflectionHelper<,>).MakeGenericType(t1, t2)); // Non-generic interface allowing us to use an instance of ReflectionHelper<T1, T2> without statically // knowing the types involved. private interface IReflectionHelper { Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method); Action<IMessage> CreateActionIMessage(MethodInfo method); Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method); Action<IMessage, object> CreateActionIMessageObject(MethodInfo method); } private class ReflectionHelper<T1, T2> : IReflectionHelper { public Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method) { // On pleasant runtimes, we can create a Func<int> from a method returning // an enum based on an int. That's the fast path. if (CanConvertEnumFuncToInt32Func) { var del = (Func<T1, int>) method.CreateDelegate(typeof(Func<T1, int>)); return message => del((T1) message); } else { // On some runtimes (e.g. old Mono) the return type has to be exactly correct, // so we go via boxing. Reflection is already fairly inefficient, and this is // only used for one-of case checking, fortunately. var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>)); return message => (int) (object) del((T1) message); } } public Action<IMessage> CreateActionIMessage(MethodInfo method) { var del = (Action<T1>) method.CreateDelegate(typeof(Action<T1>)); return message => del((T1) message); } public Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method) { var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>)); return message => del((T1) message); } public Action<IMessage, object> CreateActionIMessageObject(MethodInfo method) { var del = (Action<T1, T2>) method.CreateDelegate(typeof(Action<T1, T2>)); return (message, arg) => del((T1) message, (T2) arg); } } // Runtime compatibility checking code - see ReflectionHelper<T1, T2>.CreateFuncIMessageInt32 for // details about why we're doing this. // Deliberately not inside the generic type. We only want to check this once. private static bool CanConvertEnumFuncToInt32Func { get; } = CheckCanConvertEnumFuncToInt32Func(); private static bool CheckCanConvertEnumFuncToInt32Func() { try { // Try to do the conversion using reflection, so we can see whether it's supported. MethodInfo method = typeof(ReflectionUtil).GetMethod(nameof(SampleEnumMethod)); // If this passes, we're in a reasonable runtime. method.CreateDelegate(typeof(Func<int>)); return true; } catch (ArgumentException) { return false; } } public enum SampleEnum { X } // Public to make the reflection simpler. public static SampleEnum SampleEnumMethod() => SampleEnum.X; } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.ApplicationFramework.Preferences; using OpenLiveWriter.CoreServices; namespace OpenLiveWriter.ApplicationFramework.ApplicationStyles { /// <summary> /// Appearance preferences panel. /// </summary> public class ApplicationStylePreferencesPanel : PreferencesPanel { #region Static & Constant Declarations /// <summary> /// The types of ApplicationStyle objects provided by the system. /// </summary> private Type[] applicationStyleTypes = new Type[] { typeof(ApplicationStyleSkyBlue), }; #endregion Static & Constant Declarations #region Private Member Variables /// <summary> /// The AppearancePreferences object. /// </summary> private ApplicationStylePreferences applicationStylePreferences; #endregion Private Member Variables #region Windows Form Designer generated code private System.Windows.Forms.FontDialog fontDialog; private System.Windows.Forms.GroupBox groupBoxTheme; private System.Windows.Forms.Label labelFolderNameFont; private System.Windows.Forms.Label label1; private System.Windows.Forms.ListBox listBoxApplicationStyles; private System.Windows.Forms.PictureBox pictureBoxPreview; private System.ComponentModel.Container components = null; #endregion Windows Form Designer generated code #region Class Initialization & Termination /// <summary> /// Initializes a new instance of the AppearancePreferencesPanel class. /// </summary> public ApplicationStylePreferencesPanel() : this(new ApplicationStylePreferences(false)) { } public ApplicationStylePreferencesPanel(ApplicationStylePreferences preferences) { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Set the panel bitmap. PanelBitmap = ResourceHelper.LoadAssemblyResourceBitmap("ApplicationStyles.Images.ApplicationStyleSmall.png"); // Instantiate the MicroViewPreferences object and initialize the controls. applicationStylePreferences = preferences; applicationStylePreferences.PreferencesModified += new EventHandler(appearancePreferences_PreferencesModified); // Initialize the application styles listbox. InitializeApplicationStyles(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion Class Initialization & Termination #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() { this.groupBoxTheme = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.pictureBoxPreview = new System.Windows.Forms.PictureBox(); this.labelFolderNameFont = new System.Windows.Forms.Label(); this.listBoxApplicationStyles = new System.Windows.Forms.ListBox(); this.fontDialog = new System.Windows.Forms.FontDialog(); this.groupBoxTheme.SuspendLayout(); this.SuspendLayout(); // // groupBoxTheme // this.groupBoxTheme.Controls.Add(this.label1); this.groupBoxTheme.Controls.Add(this.pictureBoxPreview); this.groupBoxTheme.Controls.Add(this.labelFolderNameFont); this.groupBoxTheme.Controls.Add(this.listBoxApplicationStyles); this.groupBoxTheme.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBoxTheme.Location = new System.Drawing.Point(8, 32); this.groupBoxTheme.Name = "groupBoxTheme"; this.groupBoxTheme.Size = new System.Drawing.Size(354, 282); this.groupBoxTheme.TabIndex = 1; this.groupBoxTheme.TabStop = false; this.groupBoxTheme.Text = "Color"; // // label1 // this.label1.BackColor = System.Drawing.SystemColors.Control; this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.label1.Location = new System.Drawing.Point(150, 18); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(132, 18); this.label1.TabIndex = 2; this.label1.Text = "Preview:"; // // pictureBoxPreview // this.pictureBoxPreview.BackColor = System.Drawing.SystemColors.Control; this.pictureBoxPreview.Location = new System.Drawing.Point(150, 36); this.pictureBoxPreview.Name = "pictureBoxPreview"; this.pictureBoxPreview.Size = new System.Drawing.Size(192, 235); this.pictureBoxPreview.TabIndex = 2; this.pictureBoxPreview.TabStop = false; // // labelFolderNameFont // this.labelFolderNameFont.BackColor = System.Drawing.SystemColors.Control; this.labelFolderNameFont.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelFolderNameFont.Location = new System.Drawing.Point(10, 18); this.labelFolderNameFont.Name = "labelFolderNameFont"; this.labelFolderNameFont.Size = new System.Drawing.Size(132, 18); this.labelFolderNameFont.TabIndex = 0; this.labelFolderNameFont.Text = "&Color scheme:"; // // listBoxApplicationStyles // this.listBoxApplicationStyles.DisplayMember = "DisplayName"; this.listBoxApplicationStyles.IntegralHeight = false; this.listBoxApplicationStyles.Location = new System.Drawing.Point(10, 36); this.listBoxApplicationStyles.Name = "listBoxApplicationStyles"; this.listBoxApplicationStyles.Size = new System.Drawing.Size(130, 235); this.listBoxApplicationStyles.TabIndex = 1; this.listBoxApplicationStyles.SelectedIndexChanged += new System.EventHandler(this.listBoxApplicationStyles_SelectedIndexChanged); // // fontDialog // this.fontDialog.AllowScriptChange = false; this.fontDialog.AllowVerticalFonts = false; this.fontDialog.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.fontDialog.FontMustExist = true; this.fontDialog.ScriptsOnly = true; this.fontDialog.ShowEffects = false; // // AppearancePreferencesPanel // this.Controls.Add(this.groupBoxTheme); this.Name = "AppearancePreferencesPanel"; this.PanelName = "Appearance"; this.Controls.SetChildIndex(this.groupBoxTheme, 0); this.groupBoxTheme.ResumeLayout(false); this.ResumeLayout(false); } #endregion #region Public Methods /// <summary> /// Saves the PreferencesPanel. /// </summary> public override void Save() { if (applicationStylePreferences.IsModified()) applicationStylePreferences.Save(); } #endregion Public Methods #region Private Methods /// <summary> /// Initialize the application styles listbox. /// </summary> private void InitializeApplicationStyles() { // Add each of the available styles. foreach (Type type in applicationStyleTypes) { ApplicationStyle applicationStyle; try { applicationStyle = Activator.CreateInstance(type) as ApplicationStyle; listBoxApplicationStyles.Items.Add(applicationStyle); if (applicationStyle.GetType() == ApplicationManager.ApplicationStyle.GetType()) listBoxApplicationStyles.SelectedItem = applicationStyle; } catch (Exception e) { Debug.Fail("Error loading ApplicationStyle "+type.ToString(), e.StackTrace.ToString()); } } } #endregion Private Methods #region Private Event Handlers /// <summary> /// appearancePreferences_PreferencesModified event handler. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An EventArgs that contains the event data.</param> private void appearancePreferences_PreferencesModified(object sender, EventArgs e) { OnModified(EventArgs.Empty); } /// <summary> /// listBoxApplicationStyles_SelectedIndexChanged event handler. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An EventArgs that contains the event data.</param> private void listBoxApplicationStyles_SelectedIndexChanged(object sender, EventArgs e) { // If the list box is empty, just ignore the event. if (listBoxApplicationStyles.Items.Count == 0) return; // Update state. ApplicationStyle applicationStyle = (ApplicationStyle)listBoxApplicationStyles.SelectedItem; pictureBoxPreview.Image = applicationStyle.PreviewImage; applicationStylePreferences.ApplicationStyleType = applicationStyle.GetType(); } #endregion Private Event Handlers } }
using System; using System.IO; using UnityEditorInternal; using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using Projeny.Internal; using System.Linq; namespace Projeny.Internal { public class PmPackageViewHandler { readonly PmModel _model; readonly PmSettings _pmSettings; readonly PrjCommandHandler _prjCommandHandler; readonly PmPackageHandler _packageHandler; readonly AsyncProcessor _asyncProcessor; readonly PmView _view; readonly EventManager _eventManager = new EventManager(null); public PmPackageViewHandler( PmView view, AsyncProcessor asyncProcessor, PmPackageHandler packageHandler, PrjCommandHandler prjCommandHandler, PmSettings pmSettings, PmModel model) { _model = model; _pmSettings = pmSettings; _prjCommandHandler = prjCommandHandler; _packageHandler = packageHandler; _asyncProcessor = asyncProcessor; _view = view; } public void Initialize() { _view.AddContextMenuHandler(DragListTypes.Package, GetContextMenuItems); // Use EventQueueMode.LatestOnly to ensure we don't execute anything during the OnGUI event // This is important since OnGUI is called in multiple passes and we have to ensure that the same // controls are rendered each pass _view.ClickedRefreshPackages += _eventManager.Add(OnClickedRefreshPackages, EventQueueMode.LatestOnly); _view.ClickedCreateNewPackage += _eventManager.Add(OnClickedCreateNewPackage, EventQueueMode.LatestOnly); _view.ClickedPackageFolder += _eventManager.Add<int>(OnClickedPackageFolder, EventQueueMode.LatestOnly); } public void Dispose() { _view.RemoveContextMenuHandler(DragListTypes.Package); _view.ClickedRefreshPackages -= _eventManager.Remove(OnClickedRefreshPackages); _view.ClickedCreateNewPackage -= _eventManager.Remove(OnClickedCreateNewPackage); _view.ClickedPackageFolder -= _eventManager.Remove<int>(OnClickedPackageFolder); _eventManager.AssertIsEmpty(); } public void OnClickedPackageFolder(int index) { _model.PackageFolderIndex = index; } public void OnClickedRefreshPackages() { _asyncProcessor.Process(_packageHandler.RefreshPackagesAsync(), true, "Refreshing Packages"); } public void OnClickedCreateNewPackage() { _asyncProcessor.Process(CreateNewPackageAsync()); } IEnumerator CreateNewPackageAsync() { var userInput = _view.PromptForInput("Enter new package name:", "Untitled"); yield return userInput; if (userInput.Current == null) { // User Cancelled yield break; } var packageName = userInput.Current; var packageDir = PrjPathVars.Expand(Path.Combine(_model.GetCurrentPackageFolderPath(), packageName)); Log.Debug("Creating new package directory at '{0}'", packageDir); Directory.CreateDirectory(packageDir); yield return _packageHandler.RefreshPackagesAsync(); } List<PackageInfo> GetSelectedItems() { return _view.GetSelected(DragListTypes.Package) .Select(x => (PackageInfo)x.Model).ToList(); } IEnumerable<ContextMenuItem> GetContextMenuItems() { var selected = GetSelectedItems(); var singleInfo = selected.OnlyOrDefault(); yield return new ContextMenuItem( !selected.IsEmpty(), "Delete", false, OnContextMenuDeleteSelected); yield return new ContextMenuItem( singleInfo != null, "Rename", false, OnContextMenuRenameSelected); yield return new ContextMenuItem( singleInfo != null, "Show In Explorer", false, OnContextMenuOpenPackageFolderForSelected); yield return new ContextMenuItem( singleInfo != null && HasPackageYaml(selected.Single()), "Edit " + ProjenyEditorUtil.PackageConfigFileName, false, OnContextMenuEditPackageYamlSelected); yield return new ContextMenuItem( singleInfo != null, "More Info...", false, OpenMoreInfoPopupForSelected); yield return new ContextMenuItem( singleInfo != null && !string.IsNullOrEmpty(singleInfo.InstallInfo.ReleaseInfo.AssetStoreInfo.LinkId), "Open In Asset Store", false, OpenSelectedInAssetStore); yield return new ContextMenuItem( true, "Refresh", false, OnContextMenuRefresh); yield return new ContextMenuItem( true, "New Package...", false, OnContextMenuNewPackage); yield return new ContextMenuItem( true, "Show Root Folder In Explorer", false, OnContextMenuOpenUnityPackagesFolderInExplorer); } void OnContextMenuOpenUnityPackagesFolderInExplorer() { var packageRootPath = _model.TryGetCurrentPackageFolderPath(); if (packageRootPath == null) { Log.Error("Could not find current package folder path to open in explorer"); } else { var fullPath = PrjPathVars.Expand(packageRootPath); if (Directory.Exists(fullPath)) { System.Diagnostics.Process.Start(fullPath); } else { Log.Error("Could not find directory at path '{0}'", fullPath); } } } void OpenSelectedInAssetStore() { var selected = GetSelectedItems(); Assert.IsEqual(selected.Count, 1); var info = selected.Single(); var assetStoreInfo = info.InstallInfo.ReleaseInfo.AssetStoreInfo; PmViewHandlerCommon.OpenInAssetStore(assetStoreInfo.LinkType, assetStoreInfo.LinkId); } void OpenMoreInfoPopupForSelected() { var selected = GetSelectedItems(); Assert.IsEqual(selected.Count, 1); var info = selected.Single(); _asyncProcessor.Process(OpenMoreInfoPopup(info)); } IEnumerator OpenMoreInfoPopup(PackageInfo info) { bool isDone = false; var skin = _pmSettings.ReleaseMoreInfoDialog; Vector2 scrollPos = Vector2.zero; var popupId = _view.AddPopup(delegate(Rect fullRect) { var popupRect = ImguiUtil.CenterRectInRect(fullRect, skin.PopupSize); _view.DrawPopupCommon(fullRect, popupRect); var contentRect = ImguiUtil.CreateContentRectWithPadding( popupRect, skin.PanelPadding); var scrollViewRect = new Rect( contentRect.xMin, contentRect.yMin, contentRect.width, contentRect.height - skin.MarginBottom - skin.OkButtonHeight - skin.OkButtonTopPadding); GUILayout.BeginArea(scrollViewRect); { scrollPos = GUILayout.BeginScrollView(scrollPos, false, true, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, skin.ScrollViewStyle, GUILayout.ExpandHeight(true)); { GUILayout.Space(skin.ListPaddingTop); GUILayout.Label("Package Info", skin.HeadingStyle); GUILayout.Space(skin.HeadingBottomPadding); PmViewHandlerCommon.DrawMoreInfoRow(skin, "Name", info.Name); GUILayout.Space(skin.RowSpacing); PmViewHandlerCommon.DrawMoreInfoRow(skin, "Path", info.FullPath); GUILayout.Space(skin.RowSpacing); PmViewHandlerCommon.DrawMoreInfoRow(skin, "Creation Date", !string.IsNullOrEmpty(info.InstallInfo.InstallDate) ? info.InstallInfo.InstallDate : PmViewHandlerCommon.NotAvailableLabel); GUILayout.Space(skin.ListPaddingTop); GUILayout.Space(skin.ListPaddingTop); GUILayout.Label("Release Info", skin.HeadingStyle); GUILayout.Space(skin.HeadingBottomPadding); if (string.IsNullOrEmpty(info.InstallInfo.ReleaseInfo.Id)) { GUI.color = skin.ValueStyle.normal.textColor; GUILayout.Label("No release is associated with this package", skin.HeadingStyle); GUI.color = Color.white; } else { PmViewHandlerCommon.AddReleaseInfoMoreInfoRows(info.InstallInfo.ReleaseInfo, skin); } GUILayout.Space(skin.RowSpacing); } GUI.EndScrollView(); } GUILayout.EndArea(); var okButtonRect = new Rect( contentRect.xMin + 0.5f * contentRect.width - 0.5f * skin.OkButtonWidth, contentRect.yMax - skin.MarginBottom - skin.OkButtonHeight, skin.OkButtonWidth, skin.OkButtonHeight); if (GUI.Button(okButtonRect, "Ok") || Event.current.keyCode == KeyCode.Escape) { isDone = true; } }); while (!isDone) { yield return null; } _view.RemovePopup(popupId); } void OnContextMenuNewPackage() { _asyncProcessor.Process(CreateNewPackageAsync()); } void OnContextMenuRefresh() { _asyncProcessor.Process( _packageHandler.RefreshPackagesAsync(), true, "Refreshing Packages"); } void OnContextMenuEditPackageYamlSelected() { var selected = GetSelectedItems(); Assert.IsEqual(selected.Count, 1); var info = selected.Single(); var fullPath = PrjPathVars.Expand(info.FullPath); var configPath = Path.Combine(fullPath, ProjenyEditorUtil.PackageConfigFileName); Assert.That(File.Exists(configPath)); InternalEditorUtility.OpenFileAtLineExternal(configPath, 1); } void OnContextMenuOpenPackageFolderForSelected() { var selected = GetSelectedItems(); Assert.IsEqual(selected.Count, 1); var info = selected.Single(); var expandedPath = PrjPathVars.Expand(info.FullPath); Assert.That(Directory.Exists(expandedPath), "Expected to find directory at '{0}'", expandedPath); System.Diagnostics.Process.Start(expandedPath); } void OnContextMenuRenameSelected() { var selected = GetSelectedItems(); Assert.IsEqual(selected.Count, 1); var info = selected.Single(); _asyncProcessor.Process(RenamePackageAsync(info)); } IEnumerator RenamePackageAsync(PackageInfo info) { var newPackageName = _view.PromptForInput("Enter package name:", info.Name); yield return newPackageName; if (newPackageName.Current == null) { // User Cancelled yield break; } if (newPackageName.Current == info.Name) { yield break; } var fullPath = PrjPathVars.Expand(info.FullPath); Assert.That(Directory.Exists(fullPath), "Expected path to exist: {0}", fullPath); var dirInfo = new DirectoryInfo(fullPath); Assert.That(dirInfo.Name == info.Name); var newPath = Path.Combine(dirInfo.Parent.FullName, newPackageName.Current); Assert.That(!Directory.Exists(newPath), "Package with name '{0}' already exists. Rename aborted.", newPackageName.Current); dirInfo.MoveTo(newPath); yield return _packageHandler.RefreshPackagesAsync(); _view.ClearSelected(); _view.GetList(DragListTypes.Package).Values .Where(x => ((PackageInfo)x.Model).Name == newPackageName.Current).Single().IsSelected = true; } void OnContextMenuDeleteSelected() { var selected = GetSelectedItems(); _asyncProcessor.Process(_packageHandler.DeletePackages(selected), true, "Deleting Packages"); } bool HasPackageYaml(PackageInfo info) { var fullPath = PrjPathVars.Expand(info.FullPath); var configPath = Path.Combine(fullPath, ProjenyEditorUtil.PackageConfigFileName); return File.Exists(configPath); } public void Update() { _eventManager.Flush(); } } }
using System.Diagnostics; using System.IO; using System.Threading; namespace winsw { // ReSharper disable once InconsistentNaming public interface EventLogger { void LogEvent(string message); void LogEvent(string message, EventLogEntryType type); } /// <summary> /// Abstraction for handling log. /// </summary> public abstract class LogHandler { // ReSharper disable once InconsistentNaming public abstract void log(Stream outputStream, Stream errorStream); /// <summary> /// Error and information about logging should be reported here. /// </summary> public EventLogger EventLogger { set; get; } /// <summary> /// Convenience method to copy stuff from StreamReader to StreamWriter /// </summary> protected void CopyStream(Stream i, Stream o) { byte[] buf = new byte[1024]; while (true) { int sz = i.Read(buf, 0, buf.Length); if (sz == 0) break; o.Write(buf, 0, sz); o.Flush(); } i.Close(); o.Close(); } /// <summary> /// File replacement. /// </summary> protected void CopyFile(string sourceFileName, string destFileName) { try { File.Delete(destFileName); File.Move(sourceFileName, destFileName); } catch (IOException e) { EventLogger.LogEvent("Failed to copy :" + sourceFileName + " to " + destFileName + " because " + e.Message); } } } /// <summary> /// Base class for file-based loggers /// </summary> public abstract class AbstractFileLogAppender : LogHandler { protected string BaseLogFileName { private set; get; } public AbstractFileLogAppender(string logDirectory, string baseName) { BaseLogFileName = Path.Combine(logDirectory, baseName); } } public abstract class SimpleLogAppender : AbstractFileLogAppender { public FileMode FileMode { private set; get; } public string OutputLogFileName { private set; get; } public string ErrorLogFileName { private set; get; } public SimpleLogAppender(string logDirectory, string baseName, FileMode fileMode) : base(logDirectory, baseName) { FileMode = fileMode; OutputLogFileName = BaseLogFileName + ".out.log"; ErrorLogFileName = BaseLogFileName + ".err.log"; } public override void log(Stream outputStream, Stream errorStream) { new Thread(delegate() { CopyStream(outputStream, new FileStream(OutputLogFileName, FileMode)); }).Start(); new Thread(delegate() { CopyStream(errorStream, new FileStream(ErrorLogFileName, FileMode)); }).Start(); } } public class DefaultLogAppender : SimpleLogAppender { public DefaultLogAppender(string logDirectory, string baseName) : base(logDirectory, baseName, FileMode.Append) { } } public class ResetLogAppender : SimpleLogAppender { public ResetLogAppender(string logDirectory, string baseName) : base(logDirectory, baseName, FileMode.Create) { } } /// <summary> /// LogHandler that throws away output /// </summary> public class IgnoreLogAppender : LogHandler { public override void log(Stream outputStream, Stream errorStream) { new Thread(delegate() { CopyStream(outputStream, Stream.Null); }).Start(); new Thread(delegate() { CopyStream(errorStream, Stream.Null); }).Start(); } } public class TimeBasedRollingLogAppender : AbstractFileLogAppender { public string Pattern { get; private set; } public int Period { get; private set; } public TimeBasedRollingLogAppender(string logDirectory, string baseName, string pattern, int period) : base(logDirectory, baseName) { Pattern = pattern; Period = period; } public override void log(Stream outputStream, Stream errorStream) { new Thread(delegate() { CopyStreamWithDateRotation(outputStream, ".out.log"); }).Start(); new Thread(delegate() { CopyStreamWithDateRotation(errorStream, ".err.log"); }).Start(); } /// <summary> /// Works like the CopyStream method but does a log rotation based on time. /// </summary> private void CopyStreamWithDateRotation(Stream data, string ext) { PeriodicRollingCalendar periodicRollingCalendar = new PeriodicRollingCalendar(Pattern, Period); periodicRollingCalendar.init(); byte[] buf = new byte[1024]; FileStream w = new FileStream(BaseLogFileName + "_" + periodicRollingCalendar.format + ext, FileMode.Append); while (true) { int len = data.Read(buf, 0, buf.Length); if (len == 0) break; // EOF if (periodicRollingCalendar.shouldRoll) {// rotate at the line boundary int offset = 0; bool rolled = false; for (int i = 0; i < len; i++) { if (buf[i] == 0x0A) {// at the line boundary. // time to rotate. w.Write(buf, offset, i + 1); w.Close(); offset = i + 1; // create a new file and write everything to the new file. w = new FileStream(BaseLogFileName + "_" + periodicRollingCalendar.format + ext, FileMode.Create); rolled = true; if (offset < len) { w.Write(buf, offset, len - offset); break; } } } if (!rolled) {// we didn't roll - most likely as we didnt find a line boundary, so we should log what we read and roll anyway. w.Write(buf, 0, len); w.Close(); w = new FileStream(BaseLogFileName + "_" + periodicRollingCalendar.format + ext, FileMode.Create); } } else {// typical case. write the whole thing into the current file w.Write(buf, 0, len); } w.Flush(); } data.Close(); w.Close(); } } public class SizeBasedRollingLogAppender : AbstractFileLogAppender { // ReSharper disable once InconsistentNaming public static int BYTES_PER_KB = 1024; // ReSharper disable once InconsistentNaming public static int BYTES_PER_MB = 1024 * BYTES_PER_KB; // ReSharper disable once InconsistentNaming public static int DEFAULT_SIZE_THRESHOLD = 10 * BYTES_PER_MB; // rotate every 10MB. // ReSharper disable once InconsistentNaming public static int DEFAULT_FILES_TO_KEEP = 8; public int SizeTheshold { private set; get; } public int FilesToKeep { private set; get; } public SizeBasedRollingLogAppender(string logDirectory, string baseName, int sizeThreshold, int filesToKeep) : base(logDirectory, baseName) { SizeTheshold = sizeThreshold; FilesToKeep = filesToKeep; } public SizeBasedRollingLogAppender(string logDirectory, string baseName) : this(logDirectory, baseName, DEFAULT_SIZE_THRESHOLD, DEFAULT_FILES_TO_KEEP) { } public override void log(Stream outputStream, Stream errorStream) { new Thread(delegate() { CopyStreamWithRotation(outputStream, ".out.log"); }).Start(); new Thread(delegate() { CopyStreamWithRotation(errorStream, ".err.log"); }).Start(); } /// <summary> /// Works like the CopyStream method but does a log rotation. /// </summary> private void CopyStreamWithRotation(Stream data, string ext) { byte[] buf = new byte[1024]; FileStream w = new FileStream(BaseLogFileName + ext, FileMode.Append); long sz = new FileInfo(BaseLogFileName + ext).Length; while (true) { int len = data.Read(buf, 0, buf.Length); if (len == 0) break; // EOF if (sz + len < SizeTheshold) {// typical case. write the whole thing into the current file w.Write(buf, 0, len); sz += len; } else { // rotate at the line boundary int s = 0; for (int i = 0; i < len; i++) { if (buf[i] != 0x0A) continue; if (sz + i < SizeTheshold) continue; // at the line boundary and exceeded the rotation unit. // time to rotate. w.Write(buf, s, i + 1); w.Close(); s = i + 1; try { for (int j = FilesToKeep; j >= 1; j--) { string dst = BaseLogFileName + "." + (j - 1) + ext; string src = BaseLogFileName + "." + (j - 2) + ext; if (File.Exists(dst)) File.Delete(dst); if (File.Exists(src)) File.Move(src, dst); } File.Move(BaseLogFileName + ext, BaseLogFileName + ".0" + ext); } catch (IOException e) { EventLogger.LogEvent("Failed to rotate log: " + e.Message); } // even if the log rotation fails, create a new one, or else // we'll infinitely try to rotate. w = new FileStream(BaseLogFileName + ext, FileMode.Create); sz = new FileInfo(BaseLogFileName + ext).Length; } } w.Flush(); } data.Close(); w.Close(); } } /// <summary> /// Rotate log when a service is newly started. /// </summary> public class RollingLogAppender : SimpleLogAppender { public RollingLogAppender(string logDirectory, string baseName) : base(logDirectory, baseName, FileMode.Append) { } public override void log(Stream outputStream, Stream errorStream) { CopyFile(OutputLogFileName, OutputLogFileName + ".old"); CopyFile(ErrorLogFileName, ErrorLogFileName + ".old"); base.log(outputStream, errorStream); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Net; using System.Net.Sockets; using NUnit.Framework; using log4net; using OpenSim.Tests.Common; using OpenSim.Region.Physics.RemotePhysicsPlugin; namespace OpenSim.Region.Physics.RemotePhysicsPlugin.Tests { [TestFixture] public class MessengerTest : OpenSimTestCase { protected uint m_testStaticID = 13; protected uint m_testDynamicID = 37; protected OpenMetaverse.Vector3 m_position = new OpenMetaverse.Vector3(5.0f, 6.0f, 7.0f); protected OpenMetaverse.Quaternion m_orientation = new OpenMetaverse.Quaternion(8.0f, 9.0f, 10.0f, 11.0f); protected OpenMetaverse.Vector3 m_linearVelocity = new OpenMetaverse.Vector3(1.0f, 2.0f, 3.0f); protected OpenMetaverse.Vector3 m_angularVelocity = new OpenMetaverse.Vector3(20.0f, 21.0f, 22.0f); protected float m_gravMod = 5.0f; protected bool m_staticResultsReceived = false; protected uint m_resultStaticID; protected OpenMetaverse.Vector3 m_resultPosition; protected OpenMetaverse.Quaternion m_resultOrientation; protected bool m_dynamicResultsReceived = false; protected uint m_resultDynamicID; protected OpenMetaverse.Vector3 m_resultLinearVelocity; protected OpenMetaverse.Vector3 m_resultAngularVelocity; protected bool m_testDone = false; [Test] public void StaticActorMsgTest() { IRemotePhysicsMessenger testMessenger; RemotePhysicsConfiguration defaultConfig; IRemotePhysicsPacketManager testPacketManager; IRemotePhysicsPacketManager testUdpPacketManager; Thread serverThread; // Indicate that the test isn't done, and the server thread should not be shut down m_testDone = false; // Create the mock server Console.WriteLine("Launching server thread..."); serverThread = new Thread(new ThreadStart(MockServer)); serverThread.Start(); // Create the configuration that will be used for the test; the default values are sufficient defaultConfig = new RemotePhysicsConfiguration(); // Create the packet manager that will be used for receiving messages testPacketManager = new RemotePhysicsTCPPacketManager(defaultConfig); testUdpPacketManager = new RemotePhysicsUDPPacketManager(defaultConfig); // Create the messenger that will be used to receive messages testMessenger = new RemotePhysicsAPPMessenger(); testMessenger.Initialize(defaultConfig, testPacketManager, testUdpPacketManager); testMessenger.StaticActorUpdated += new UpdateStaticActorHandler(StaticUpdated); // Send out a static actor update testMessenger.SetStaticActor(m_testStaticID, m_position, m_orientation); // Wait for the results to be sent back while (!m_staticResultsReceived) { // Sleep a bit Thread.Sleep(2000); } // Indicate that the test is done, so that the server thread can clean up m_testDone = true; // Wait for the mock server to clean up Thread.Sleep(2000); // Compare the results Assert.AreEqual(m_testStaticID, m_resultStaticID); Assert.AreEqual(m_position.X, m_resultPosition.X); Assert.AreEqual(m_position.Y, m_resultPosition.Y); Assert.AreEqual(m_position.Z, m_resultPosition.Z); Assert.AreEqual(m_orientation.X, m_resultOrientation.X); Assert.AreEqual(m_orientation.Y, m_resultOrientation.Y); Assert.AreEqual(m_orientation.Z, m_resultOrientation.Z); Assert.AreEqual(m_orientation.W, m_resultOrientation.W); } [Test] public void DynamicActorMsgTest() { IRemotePhysicsMessenger testMessenger; RemotePhysicsConfiguration defaultConfig; IRemotePhysicsPacketManager testPacketManager; IRemotePhysicsPacketManager testUdpPacketManager; Thread serverThread; // Indicate that the test ins't done, and the server thread should not be shut down m_testDone = false; // Create the mock server Console.WriteLine("Launching server thread..."); serverThread = new Thread(new ThreadStart(MockServer)); serverThread.Start(); // Create the configuration that will be used for the test; the default values are sufficient defaultConfig = new RemotePhysicsConfiguration(); // Create the packet manager that will be used for receiving messages testPacketManager = new RemotePhysicsTCPPacketManager(defaultConfig); testUdpPacketManager = new RemotePhysicsUDPPacketManager(defaultConfig); // Create the messenger that will be used to receive messages testMessenger = new RemotePhysicsAPPMessenger(); testMessenger.Initialize(defaultConfig, testPacketManager, testUdpPacketManager); testMessenger.DynamicActorUpdated += new UpdateDynamicActorHandler(DynamicUpdated); // Send out a static actor update testMessenger.SetDynamicActor(m_testDynamicID, m_position, m_orientation, m_gravMod, m_linearVelocity, m_angularVelocity); // Wait for the results to be sent back while (!m_dynamicResultsReceived) { // Sleep a bit Thread.Sleep(2000); } // Indicate that the test is done, so that the server thread can clean up m_testDone = true; // Wait for the mock server to clean up Thread.Sleep(2000); // Compare the results Assert.AreEqual(m_testDynamicID, m_resultDynamicID); Assert.AreEqual(m_position.X, m_resultPosition.X); Assert.AreEqual(m_position.Y, m_resultPosition.Y); Assert.AreEqual(m_position.Z, m_resultPosition.Z); Assert.AreEqual(m_orientation.X, m_resultOrientation.X); Assert.AreEqual(m_orientation.Y, m_resultOrientation.Y); Assert.AreEqual(m_orientation.Z, m_resultOrientation.Z); Assert.AreEqual(m_orientation.W, m_resultOrientation.W); Assert.AreEqual(m_linearVelocity.X, m_resultLinearVelocity.X); Assert.AreEqual(m_linearVelocity.Y, m_resultLinearVelocity.Y); Assert.AreEqual(m_linearVelocity.Z, m_resultLinearVelocity.Z); Assert.AreEqual(m_angularVelocity.X, m_resultAngularVelocity.X); Assert.AreEqual(m_angularVelocity.Y, m_resultAngularVelocity.Y); Assert.AreEqual(m_angularVelocity.Z, m_resultAngularVelocity.Z); } public void MockServer() { int port; IPAddress localHost; TcpListener mockServer; Socket clientSocket; byte[] incBuffer; int bytesRead; // Open up a connection on the local host with the default RemotePhysics port Console.WriteLine("Creating server..."); localHost = IPAddress.Parse("127.0.0.1"); port = 9003; // Create the mock server mockServer = new TcpListener(localHost, port); Console.WriteLine("Server created"); // Start the server mockServer.Start(); Console.WriteLine("Server started!"); // Initialize the buffer that will be used to store incoming data incBuffer = new byte[65536]; // Main server loop while (!m_testDone) { // Accept incoming connection clientSocket = mockServer.AcceptSocket(); Console.WriteLine("Connected! from " + clientSocket.RemoteEndPoint); // Wait for data from the client while (!m_testDone) { if (clientSocket.Available != 0) { // Read in the incoming data from the client Console.WriteLine("Data available"); bytesRead = clientSocket.Receive(incBuffer); // Send it back clientSocket.Send(incBuffer, bytesRead, 0); } // Sleep the thread for half a second, so that it doesn't hog resources Thread.Sleep(500); } // Close the socket for this client if (clientSocket != null) clientSocket.Close(); } // Stop the server mockServer.Stop(); Console.WriteLine("Mock server stopped"); } public void StaticUpdated(uint actorID, OpenMetaverse.Vector3 position, OpenMetaverse.Quaternion orientation) { // Update the result variables m_resultStaticID = actorID; m_resultPosition = position; m_resultOrientation = orientation; m_staticResultsReceived = true; } public void DynamicUpdated(uint actorID, OpenMetaverse.Vector3 position, OpenMetaverse.Quaternion orientation, OpenMetaverse.Vector3 linearVelocity, OpenMetaverse.Vector3 angularVelocity) { Console.WriteLine("Received dynamic results!"); // Update the result variables m_resultDynamicID = actorID; m_resultPosition = position; m_resultOrientation = orientation; m_resultLinearVelocity = linearVelocity; m_resultAngularVelocity = angularVelocity; m_dynamicResultsReceived = true; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Text; using System.Xml; using System.ComponentModel; namespace System.ServiceModel.Channels { public sealed class TextMessageEncodingBindingElement : MessageEncodingBindingElement { private int _maxReadPoolSize; private int _maxWritePoolSize; private XmlDictionaryReaderQuotas _readerQuotas; private MessageVersion _messageVersion; private Encoding _writeEncoding; public TextMessageEncodingBindingElement() : this(MessageVersion.Default, TextEncoderDefaults.Encoding) { } public TextMessageEncodingBindingElement(MessageVersion messageVersion, Encoding writeEncoding) { if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion"); if (writeEncoding == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writeEncoding"); TextEncoderDefaults.ValidateEncoding(writeEncoding); _maxReadPoolSize = EncoderDefaults.MaxReadPoolSize; _maxWritePoolSize = EncoderDefaults.MaxWritePoolSize; _readerQuotas = new XmlDictionaryReaderQuotas(); EncoderDefaults.ReaderQuotas.CopyTo(_readerQuotas); _messageVersion = messageVersion; _writeEncoding = writeEncoding; } private TextMessageEncodingBindingElement(TextMessageEncodingBindingElement elementToBeCloned) : base(elementToBeCloned) { _maxReadPoolSize = elementToBeCloned._maxReadPoolSize; _maxWritePoolSize = elementToBeCloned._maxWritePoolSize; _readerQuotas = new XmlDictionaryReaderQuotas(); elementToBeCloned._readerQuotas.CopyTo(_readerQuotas); _writeEncoding = elementToBeCloned._writeEncoding; _messageVersion = elementToBeCloned._messageVersion; } [DefaultValue(EncoderDefaults.MaxReadPoolSize)] public int MaxReadPoolSize { get { return _maxReadPoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.ValueMustBePositive)); } _maxReadPoolSize = value; } } [DefaultValue(EncoderDefaults.MaxWritePoolSize)] public int MaxWritePoolSize { get { return _maxWritePoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.ValueMustBePositive)); } _maxWritePoolSize = value; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return _readerQuotas; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); value.CopyTo(_readerQuotas); } } public override MessageVersion MessageVersion { get { return _messageVersion; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } _messageVersion = value; } } public Encoding WriteEncoding { get { return _writeEncoding; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } TextEncoderDefaults.ValidateEncoding(value); _writeEncoding = value; } } public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context) { return InternalBuildChannelFactory<TChannel>(context); } public override BindingElement Clone() { return new TextMessageEncodingBindingElement(this); } public override MessageEncoderFactory CreateMessageEncoderFactory() { return new TextMessageEncoderFactory(MessageVersion, WriteEncoding, this.MaxReadPoolSize, this.MaxWritePoolSize, this.ReaderQuotas); } public override T GetProperty<T>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } if (typeof(T) == typeof(XmlDictionaryReaderQuotas)) { return (T)(object)_readerQuotas; } else { return base.GetProperty<T>(context); } } internal override bool CheckEncodingVersion(EnvelopeVersion version) { return _messageVersion.Envelope == version; } internal override bool IsMatch(BindingElement b) { if (!base.IsMatch(b)) return false; TextMessageEncodingBindingElement text = b as TextMessageEncodingBindingElement; if (text == null) return false; if (_maxReadPoolSize != text.MaxReadPoolSize) return false; if (_maxWritePoolSize != text.MaxWritePoolSize) return false; // compare XmlDictionaryReaderQuotas if (_readerQuotas.MaxStringContentLength != text.ReaderQuotas.MaxStringContentLength) return false; if (_readerQuotas.MaxArrayLength != text.ReaderQuotas.MaxArrayLength) return false; if (_readerQuotas.MaxBytesPerRead != text.ReaderQuotas.MaxBytesPerRead) return false; if (_readerQuotas.MaxDepth != text.ReaderQuotas.MaxDepth) return false; if (_readerQuotas.MaxNameTableCharCount != text.ReaderQuotas.MaxNameTableCharCount) return false; if (this.WriteEncoding.WebName != text.WriteEncoding.WebName) return false; if (!this.MessageVersion.IsMatch(text.MessageVersion)) return false; return true; } } }
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; namespace NAssert.Constraints { /// <summary> /// The Numerics class contains common operations on numeric values. /// </summary> public class Numerics { #region Numeric Type Recognition /// <summary> /// Checks the type of the object, returning true if /// the object is a numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a numeric type</returns> public static bool IsNumericType(Object obj) { return IsFloatingPointNumeric( obj ) || IsFixedPointNumeric( obj ); } /// <summary> /// Checks the type of the object, returning true if /// the object is a floating point numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a floating point numeric type</returns> public static bool IsFloatingPointNumeric(Object obj) { if (null != obj) { if (obj is System.Double) return true; if (obj is System.Single) return true; } return false; } /// <summary> /// Checks the type of the object, returning true if /// the object is a fixed point numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a fixed point numeric type</returns> public static bool IsFixedPointNumeric(Object obj) { if (null != obj) { if (obj is System.Byte) return true; if (obj is System.SByte) return true; if (obj is System.Decimal) return true; if (obj is System.Int32) return true; if (obj is System.UInt32) return true; if (obj is System.Int64) return true; if (obj is System.UInt64) return true; if (obj is System.Int16) return true; if (obj is System.UInt16) return true; } return false; } #endregion #region Numeric Equality /// <summary> /// Test two numeric values for equality, performing the usual numeric /// conversions and using a provided or default tolerance. If the tolerance /// provided is Empty, this method may set it to a default tolerance. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <param name="tolerance">A reference to the tolerance in effect</param> /// <returns>True if the values are equal</returns> public static bool AreEqual( object expected, object actual, ref Tolerance tolerance ) { if ( expected is double || actual is double ) return AreEqual( Convert.ToDouble(expected), Convert.ToDouble(actual), ref tolerance ); if ( expected is float || actual is float ) return AreEqual( Convert.ToSingle(expected), Convert.ToSingle(actual), ref tolerance ); if (tolerance.Mode == ToleranceMode.Ulps) throw new InvalidOperationException("Ulps may only be specified for floating point arguments"); if ( expected is decimal || actual is decimal ) return AreEqual( Convert.ToDecimal(expected), Convert.ToDecimal(actual), tolerance ); if (expected is ulong || actual is ulong) return AreEqual(Convert.ToUInt64(expected), Convert.ToUInt64(actual), tolerance ); if ( expected is long || actual is long ) return AreEqual( Convert.ToInt64(expected), Convert.ToInt64(actual), tolerance ); if ( expected is uint || actual is uint ) return AreEqual( Convert.ToUInt32(expected), Convert.ToUInt32(actual), tolerance ); return AreEqual( Convert.ToInt32(expected), Convert.ToInt32(actual), tolerance ); } private static bool AreEqual( double expected, double actual, ref Tolerance tolerance ) { if (double.IsNaN(expected) && double.IsNaN(actual)) return true; // Handle infinity specially since subtracting two infinite values gives // NaN and the following test fails. mono also needs NaN to be handled // specially although ms.net could use either method. Also, handle // situation where no tolerance is used. if (double.IsInfinity(expected) || double.IsNaN(expected) || double.IsNaN(actual)) { return expected.Equals(actual); } if (tolerance.IsEmpty && GlobalSettings.DefaultFloatingPointTolerance > 0.0d) tolerance = new Tolerance(GlobalSettings.DefaultFloatingPointTolerance); switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value); case ToleranceMode.Percent: if (expected == 0.0) return expected.Equals(actual); double relativeError = Math.Abs((expected - actual) / expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); #if !NETCF_1_0 case ToleranceMode.Ulps: return FloatingPointNumerics.AreAlmostEqualUlps( expected, actual, Convert.ToInt64(tolerance.Value)); #endif default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( float expected, float actual, ref Tolerance tolerance ) { if ( float.IsNaN(expected) && float.IsNaN(actual) ) return true; // handle infinity specially since subtracting two infinite values gives // NaN and the following test fails. mono also needs NaN to be handled // specially although ms.net could use either method. if (float.IsInfinity(expected) || float.IsNaN(expected) || float.IsNaN(actual)) { return expected.Equals(actual); } if (tolerance.IsEmpty && GlobalSettings.DefaultFloatingPointTolerance > 0.0d) tolerance = new Tolerance(GlobalSettings.DefaultFloatingPointTolerance); switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value); case ToleranceMode.Percent: if (expected == 0.0f) return expected.Equals(actual); float relativeError = Math.Abs((expected - actual) / expected); return (relativeError <= Convert.ToSingle(tolerance.Value) / 100.0f); #if !NETCF_1_0 case ToleranceMode.Ulps: return FloatingPointNumerics.AreAlmostEqualUlps( expected, actual, Convert.ToInt32(tolerance.Value)); #endif default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( decimal expected, decimal actual, Tolerance tolerance ) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: decimal decimalTolerance = Convert.ToDecimal(tolerance.Value); if(decimalTolerance > 0m) return Math.Abs(expected - actual) <= decimalTolerance; return expected.Equals( actual ); case ToleranceMode.Percent: if(expected == 0m) return expected.Equals(actual); double relativeError = Math.Abs( (double)(expected - actual) / (double)expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( ulong expected, ulong actual, Tolerance tolerance ) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: ulong ulongTolerance = Convert.ToUInt64(tolerance.Value); if(ulongTolerance > 0ul) { ulong diff = expected >= actual ? expected - actual : actual - expected; return diff <= ulongTolerance; } return expected.Equals( actual ); case ToleranceMode.Percent: if (expected == 0ul) return expected.Equals(actual); // Can't do a simple Math.Abs() here since it's unsigned ulong difference = Math.Max(expected, actual) - Math.Min(expected, actual); double relativeError = Math.Abs( (double)difference / (double)expected ); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( long expected, long actual, Tolerance tolerance ) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: long longTolerance = Convert.ToInt64(tolerance.Value); if(longTolerance > 0L) return Math.Abs(expected - actual) <= longTolerance; return expected.Equals( actual ); case ToleranceMode.Percent: if(expected == 0L) return expected.Equals(actual); double relativeError = Math.Abs( (double)(expected - actual) / (double)expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( uint expected, uint actual, Tolerance tolerance ) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: uint uintTolerance = Convert.ToUInt32(tolerance.Value); if(uintTolerance > 0) { uint diff = expected >= actual ? expected - actual : actual - expected; return diff <= uintTolerance; } return expected.Equals( actual ); case ToleranceMode.Percent: if(expected == 0u) return expected.Equals(actual); // Can't do a simple Math.Abs() here since it's unsigned uint difference = Math.Max(expected, actual) - Math.Min(expected, actual); double relativeError = Math.Abs((double)difference / (double)expected ); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( int expected, int actual, Tolerance tolerance ) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: int intTolerance = Convert.ToInt32(tolerance.Value); if (intTolerance > 0) return Math.Abs(expected - actual) <= intTolerance; return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0) return expected.Equals(actual); double relativeError = Math.Abs( (double)(expected - actual) / (double)expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } #endregion #region Numeric Comparisons /// <summary> /// Compare two numeric values, performing the usual numeric conversions. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <returns>The relationship of the values to each other</returns> public static int Compare( object expected, object actual ) { if( !IsNumericType( expected ) || !IsNumericType( actual ) ) throw new ArgumentException( "Both arguments must be numeric"); if ( IsFloatingPointNumeric(expected) || IsFloatingPointNumeric(actual) ) return Convert.ToDouble(expected).CompareTo(Convert.ToDouble(actual)); if ( expected is decimal || actual is decimal ) return Convert.ToDecimal(expected).CompareTo(Convert.ToDecimal(actual)); if ( expected is ulong || actual is ulong ) return Convert.ToUInt64(expected).CompareTo(Convert.ToUInt64(actual)); if ( expected is long || actual is long ) return Convert.ToInt64(expected).CompareTo(Convert.ToInt64(actual)); if ( expected is uint || actual is uint ) return Convert.ToUInt32(expected).CompareTo(Convert.ToUInt32(actual)); return Convert.ToInt32(expected).CompareTo(Convert.ToInt32(actual)); } #endregion private Numerics() { } } }
// =========================================================== // Copyright (C) 2014-2015 Kendar.org // // 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 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 GenericHelpers; using Http.Shared.Contexts; using Http.Shared.Routing; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Http.Routing { //TODO: This must be optimized grouping definitions public class RoutingService : IRoutingHandler { public List<RouteDefinition> _routeDefinitions; private string _virtualDir; public RoutingService() { _routeDefinitions = new List<RouteDefinition>(); } public void MapStaticRoute(string route) { route = route.TrimStart('~'); if (route.StartsWith("/")) { route = route.TrimStart('/'); } _routeDefinitions.Add(new RouteDefinition(route.ToLowerInvariant(), true, false)); } public RouteInstance Resolve(string route, IHttpContext context) { if (route.StartsWith("~/")) { route = route.TrimStart('~'); } if (route.StartsWith("/")) { route = route.TrimStart('/'); } var lower = route.ToLowerInvariant(); var splitted = route.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); for (int index = (_routeDefinitions.Count - 1); index >= 0; index--) { var routeDefinition = _routeDefinitions[index]; var routeInstance = IsValid(splitted, routeDefinition, lower); if (routeInstance != null) { if (routeInstance.StaticRoute || routeInstance.BlockRoute) { return routeInstance; } if (routeInstance.Parameters.ContainsKey("controller")) { var key = routeInstance.Parameters["controller"].ToString(); if (!_controllers.ContainsKey(key)) { key = key + "controller"; } if (!_controllers.ContainsKey(key)) { continue; } routeInstance.Controller = _controllers[key]; } return routeInstance; } } return null; } public void SetVirtualDir(string virtualDir) { _virtualDir = virtualDir; } private RouteInstance IsValid(string[] route, RouteDefinition routeDefinition, string lower) { if (routeDefinition.IsStatic) { if (lower.StartsWith(routeDefinition.RouteString)) { return new RouteInstance(true, false); } } if (route.Length > routeDefinition.Url.Count) { var last = routeDefinition.Url[routeDefinition.Url.Count - 1]; if (!last.IsParameter && !last.LowerRoute.StartsWith("*", StringComparison.OrdinalIgnoreCase)) { return null; } } var routeInstance = new RouteInstance(); var index = -1; while (index < (route.Length - 1)) { index++; var routeValue = route[index]; if (index >= routeDefinition.Url.Count) { return null; } var block = routeDefinition.Url[index]; if (block.IsParameter) { if (block.LowerRoute.StartsWith("*", StringComparison.OrdinalIgnoreCase)) { var paramName = block.LowerRoute.Substring(1); var paramValue = "/" + string.Join("/", route, index, route.Length - index).Trim('/'); routeInstance.Parameters.Add(paramName, paramValue); index = route.Length; } else { routeInstance.Parameters.Add(block.Name, routeValue); } } else { if (string.Compare(routeValue, block.Name, StringComparison.OrdinalIgnoreCase) != 0) return null; } } while (index < (routeDefinition.Url.Count - 1)) { index++; var block = routeDefinition.Url[index]; if (block.IsParameter) { if (routeDefinition.Parameters.ContainsKey(block.Name)) { var parameter = routeDefinition.Parameters[block.Name]; if (parameter.Optional) { if (parameter.Value != null && parameter.Value.GetType() != typeof(RoutingParameter)) { routeInstance.Parameters.Add(block.Name, parameter.Value); } } else if (parameter.Value != null) { routeInstance.Parameters.Add(block.Name, parameter.Value); } else { return null; } } else { return null; } } else { return null; } } foreach (var param in routeDefinition.Parameters) { if (!routeInstance.Parameters.ContainsKey(param.Key)) { var paramReal = param.Value; if (paramReal.Value != null && paramReal.Value.GetType() != typeof(RoutingParameter)) { routeInstance.Parameters.Add(param.Key, paramReal.Value); } } } return routeInstance; } private void CheckForConflicting(RouteDefinition routeDefinition) { } public void MapRoute(string name,string url, dynamic defaults = null) { url = url.TrimStart('~'); if (url.StartsWith("/")) { url = url.TrimStart('/'); } var routeDefinition = new RouteDefinition(url, ReflectionUtils.ObjectToDictionary(defaults)); CheckForConflicting(routeDefinition); _routeDefinitions.Add(routeDefinition); } class MatchingRoute { public int Weight; public RouteDefinition Definition; public string Route; } public string ResolveFromParams(Dictionary<string, object> pars) { var mr = new List<MatchingRoute>(); var parKeys = new List<string>(pars.Keys); for (int i = 0; i < _routeDefinitions.Count; i++) { var routeDefinition = _routeDefinitions[i]; var weigth = IsMatching(routeDefinition, pars, parKeys); mr.Add(new MatchingRoute { Definition = routeDefinition, Weight = weigth }); } if (mr.Count == 0) return null; var max = int.MinValue; var maxRoute = -1; var hashRoute = new HashSet<string>(); var routeSplitted = new StringBuilder(); var routeMissing = new StringBuilder(); for (int index = 0; index < mr.Count; index++) { var match = mr[index]; if (match.Weight > max) { var route = CreateRoute(match, pars, parKeys, hashRoute, routeSplitted, routeMissing); if (route != null) { match.Route = route; maxRoute = index; max = match.Weight; } } } if (maxRoute != -1) { return mr[maxRoute].Route; } return null; } private int IsMatching(RouteDefinition routeDefinition, Dictionary<string, object> pars, List<string> keys) { int weight = 0; for (int i = 0; i < keys.Count; i++) { var key = keys[i]; if (!pars.ContainsKey(key)) { var pardef = routeDefinition.Parameters[key]; if (!pardef.Optional) { return 0; } if (pardef.Value != null) { weight++; } } else { weight++; } } return weight; } private string CreateRoute(MatchingRoute match, Dictionary<string, object> pars, List<string> parsKeys, HashSet<string> routeParamsUsed, StringBuilder routeSplitted, StringBuilder routeMissing) { routeMissing.Clear(); routeSplitted.Clear(); routeParamsUsed.Clear(); routeSplitted.Clear(); var routeDefinition = match.Definition; for (int i = 0; i < routeDefinition.Url.Count; i++) { var par = routeDefinition.Url[i]; var name = par.LowerRoute; if (!par.IsParameter) { routeSplitted.Append("/"); routeSplitted.Append(name); } else { if (pars.ContainsKey(name)) { routeSplitted.Append("/"); routeSplitted.Append(pars[par.Name].ToString()); routeParamsUsed.Add(name); } else { var pdesc = routeDefinition.Parameters[par.Name]; if (!pdesc.Optional) { return null; } } } } routeMissing.Clear(); var hasRoute = false; for (var i = 0; i < parsKeys.Count; i++) { var parKey = parsKeys[i]; if (!routeParamsUsed.Contains(parKey)) { if (hasRoute) routeMissing.Append("&"); routeMissing.Append(HttpUtility.UrlEncode(parKey)) .Append("=") .Append(HttpUtility.UrlEncode(pars[parKey].ToString())); hasRoute = true; } } //var url = "/" + string.Join("/", routeSplitted); if (routeMissing.Length > 0) { return null; /*routeSplitted.Append("?"); routeSplitted.Append(routeMissing);*/ } return routeSplitted.ToString(); } private Dictionary<string, Type> _controllers = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase); public void LoadControllers(IEnumerable<Type> types) { foreach (var type in types) { _controllers.Add(type.Name, type); } for (int i = 0; i < _routeDefinitions.Count; i++) { var routeDefinition = _routeDefinitions[i]; if (routeDefinition.Parameters != null && routeDefinition.Parameters.ContainsKey("controller")) { var controllerParameter = routeDefinition.Parameters["controller"]; if (controllerParameter.Value != null && !string.IsNullOrWhiteSpace(controllerParameter.Value.ToString())) { var controllerName = controllerParameter.Value.ToString(); if (!_controllers.Any(c => string.Equals(controllerName, c.Key, StringComparison.OrdinalIgnoreCase) || string.Equals(controllerName + "Controller", c.Key, StringComparison.OrdinalIgnoreCase))) { throw new Exception("Missing controller " + controllerName); } } } } } public void IgnoreRoute(string route) { if (!route.StartsWith("~/")) { throw new Exception(string.Format("Invalid route '{0}' not starting with ~", route)); } route = route.TrimStart('~'); if (route.StartsWith("/")) { route = route.TrimStart('/'); } var routeDefinition = new RouteDefinition(route, new Dictionary<string, object>(), false, true); CheckForConflicting(routeDefinition); _routeDefinitions.Add(routeDefinition); } public void EnableQuerySupport() { //throw new NotImplementedException(); } } }
using System; using EnvDTE; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace EditorConfig.VisualStudio { /// <summary> /// This plugin attaches to an editor instance and updates its settings at /// the appropriate times /// </summary> internal class Plugin { IWpfTextView view; ITextDocument document; DTE dte; ErrorListProvider messageList; ErrorTask message; private readonly IViewSettingsContainer viewSettingsContainer; FileSettings settings; private string documentPath; public Plugin(IWpfTextView view, ITextDocument document, DTE dte, ErrorListProvider messageList, IViewSettingsContainer viewSettingsContainer) { this.view = view; this.document = document; this.dte = dte; this.messageList = messageList; this.message = null; this.viewSettingsContainer = viewSettingsContainer; document.FileActionOccurred += FileActionOccurred; view.GotAggregateFocus += GotAggregateFocus; view.Closed += Closed; documentPath = document.FilePath; LoadSettings(documentPath); viewSettingsContainer.Register(documentPath, view, settings); } /// <summary> /// Reloads the settings when the filename changes /// </summary> void FileActionOccurred(object sender, TextDocumentFileActionEventArgs e) { if (!e.FileActionType.HasFlag(FileActionTypes.DocumentRenamed)) return; LoadSettings(e.FilePath); viewSettingsContainer.Update(documentPath, e.FilePath, view, settings); documentPath = e.FilePath; if (settings != null && view.HasAggregateFocus) ApplyGlobalSettings(); } /// <summary> /// Updates the global settings when the local editor receives focus /// </summary> void GotAggregateFocus(object sender, EventArgs e) { if (settings != null) ApplyGlobalSettings(); } /// <summary> /// Removes the any messages when the document is closed /// </summary> void Closed(object sender, EventArgs e) { ClearMessage(); viewSettingsContainer.Unregister(documentPath, view); document.FileActionOccurred -= FileActionOccurred; view.GotAggregateFocus -= GotAggregateFocus; view.Closed -= Closed; } /// <summary> /// Loads the settings for the given file path /// </summary> private void LoadSettings(string path) { ClearMessage(); settings = null; // Prevent parsing of internet-located documents, // or documents that do not have proper paths. if (path.StartsWith("http:", StringComparison.OrdinalIgnoreCase) || path.Equals("Temp.txt")) return; try { settings = new FileSettings(Core.Parse(path)); ApplyLocalSettings(); } catch (ParseException e) { ShowError(path, "EditorConfig syntax error in file \"" + e.File + "\", line " + e.Line); } catch (CoreException e) { ShowError(path, "EditorConfig core error: " + e.Message); } } /// <summary> /// Applies settings to the local text editor instance /// </summary> private void ApplyLocalSettings() { IEditorOptions options = view.Options; if (settings.TabWidth != null) { int value = settings.TabWidth.Value; options.SetOptionValue<int>(DefaultOptions.TabSizeOptionId, value); } if (settings.IndentSize != null) { int value = settings.IndentSize.Value; options.SetOptionValue<int>(DefaultOptions.IndentSizeOptionId, value); } if (settings.ConvertTabsToSpaces != null) { bool value = settings.ConvertTabsToSpaces.Value; options.SetOptionValue<bool>(DefaultOptions.ConvertTabsToSpacesOptionId, value); } if (settings.EndOfLine != null) { string value = settings.EndOfLine; options.SetOptionValue<string>(DefaultOptions.NewLineCharacterOptionId, value); options.SetOptionValue<bool>(DefaultOptions.ReplicateNewLineCharacterOptionId, false); } } /// <summary> /// Applies settings to the global Visual Studio application. Some /// source-code formatters, such as curly-brace auto-indenter, ignore /// the local text editor settings. This causes horrible bugs when /// the local text-editor settings disagree with the formatter's /// settings. To fix this, just apply the same settings at the global /// application level as well. /// </summary> private void ApplyGlobalSettings() { Properties props; try { string type = view.TextDataModel.ContentType.TypeName; props = dte.Properties["TextEditor", type]; } catch { // If the above code didn't work, this particular content type // didn't need its settings changed anyhow return; } if (settings.TabWidth != null) { int value = settings.TabWidth.Value; props.Item("TabSize").Value = value; } if (settings.IndentSize != null) { int value = settings.IndentSize.Value; props.Item("IndentSize").Value = value; } if (settings.ConvertTabsToSpaces != null) { bool value = !settings.ConvertTabsToSpaces.Value; props.Item("InsertTabs").Value = value; } } /// <summary> /// Adds an error message to the Visual Studio tasks pane /// </summary> void ShowError(string path, string text) { message = new ErrorTask(); message.ErrorCategory = TaskErrorCategory.Error; message.Category = TaskCategory.Comments; message.Document = path; message.Line = 0; message.Column = 0; message.Text = text; messageList.Tasks.Add(message); messageList.Show(); } /// <summary> /// Removes the file's messages, if any /// </summary> void ClearMessage() { if (message != null) messageList.Tasks.Remove(message); message = null; } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; namespace XenAPI { public enum API_Version { API_1_1 = 1, // XenServer 4.0 (codename Rio) API_1_2 = 2, // XenServer 4.1 (Miami) API_1_3 = 3, // XenServer 5.0 up to update 2 (Orlando) API_1_4 = 4, // Unreleased API_1_5 = 5, // XenServer 5.0 update 3 and above (Floodgate) API_1_6 = 6, // XenServer 5.5 (George) API_1_7 = 7, // XenServer 5.6 (Midnight Ride) API_1_8 = 8, // XenServer 5.6.1 (Cowley) API_1_9 = 9, // XenServer 6.0 (Boston) API_1_10 = 10, // XenServer 6.1 (Tampa) API_2_0 = 11, // XenServer 6.2 (Clearwater) API_2_1 = 12, // XenServer 6.2 with vGPU (vGPU) API_2_2 = 13, // XenServer 6.2 Hotfix XS62ESP1004 (Felton) API_2_3 = 14, // XenServer Creedence API_2_4 = 15, // XenServer Cream API_2_5 = 16, // XenServer Dundee LATEST = 16, // Don't forget to change LATEST above, and APIVersionString below. UNKNOWN = 99 } public static class Helper { public const string NullOpaqueRef = "OpaqueRef:NULL"; public static string APIVersionString(API_Version v) { switch (v) { case API_Version.API_1_1: return "1.1"; case API_Version.API_1_2: return "1.2"; case API_Version.API_1_3: return "1.3"; case API_Version.API_1_4: return "1.4"; case API_Version.API_1_5: return "1.5"; case API_Version.API_1_6: return "1.6"; case API_Version.API_1_7: return "1.7"; case API_Version.API_1_8: return "1.8"; case API_Version.API_1_9: return "1.9"; case API_Version.API_1_10: return "1.10"; case API_Version.API_2_0: return "2.0"; case API_Version.API_2_1: return "2.1"; case API_Version.API_2_2: return "2.2"; case API_Version.API_2_3: return "2.3"; case API_Version.API_2_4: return "2.4"; case API_Version.API_2_5: return "2.5"; default: return "Unknown"; } } public static API_Version GetAPIVersion(long major, long minor) { try { return (API_Version)Enum.Parse(typeof(API_Version), string.Format("API_{0}_{1}", major, minor)); } catch (ArgumentException) { return API_Version.UNKNOWN; } } /// <summary> /// Converts the string representation of an API version number to its API_Version equivalent. /// This function assumes that API version numbers are of form a.b /// </summary> public static API_Version GetAPIVersion(string version) { if (version != null) { string[] tokens = version.Split('.'); int major, minor; if (tokens.Length == 2 && int.TryParse(tokens[0], out major) && int.TryParse(tokens[1], out minor)) { return GetAPIVersion(major, minor); } } return API_Version.UNKNOWN; } /// <summary> /// Return a positive number if the given session's API version is greater than the given /// API_version, negative if it is less, and 0 if they are equal. /// </summary> internal static int APIVersionCompare(Session session, API_Version v) { return (int)session.APIVersion - (int)v; } /// <summary> /// Return true if the given session's API version is greater than or equal to the given /// API_version. /// </summary> internal static bool APIVersionMeets(Session session, API_Version v) { return APIVersionCompare(session, v) >= 0; } /// <summary> /// Test to see if two objects are equal. If the objects implement ICollection, then we will /// call AreCollectionsEqual to compare elements within the collection. /// </summary> public static bool AreEqual(object o1, object o2) { if (o1 == null && o2 == null) return true; if (o1 == null || o2 == null) return false; if (o1 is IDictionary) return AreDictEqual((IDictionary)o1, (IDictionary)o2); if (o1 is System.Collections.ICollection) return AreCollectionsEqual((ICollection)o1, (ICollection)o2); return o1.Equals(o2); } /// <summary> /// Test to see if two objects are equal. Different from AreEqual in that this function /// considers an empty Collection and null to be equal. /// </summary> public static bool AreEqual2<T>(T o1, T o2) { if (o1 == null && o2 == null) return true; if (o1 == null || o2 == null) return o1 == null && IsEmptyCollection(o2) || o2 == null && IsEmptyCollection(o1); if (typeof(T) is IDictionary) return AreDictEqual((IDictionary)o1, (IDictionary)o2); if (typeof(T) is System.Collections.ICollection) return AreCollectionsEqual((ICollection)o1, (ICollection)o2); return o1.Equals(o2); } private static bool IsEmptyCollection(object obj) { ICollection collection = obj as ICollection; return collection != null && collection.Count == 0; } /// <summary> /// Test to see if two dictionaries are equal. This dictionary comparison method places a call to AreEqual /// for underlying objects. /// </summary> private static bool AreDictEqual(IDictionary d1, IDictionary d2) { if (d1.Count != d2.Count) return false; foreach (object k in d1.Keys) { if (!d2.Contains(k) || !AreEqual(d2[k], d1[k])) return false; } return true; } /// <summary> /// Test to see if two collections are equal. The collections are equal if they have the same elements, /// in the same order, and quantity. Elements are equal if their values are equal. /// </summary> private static bool AreCollectionsEqual(ICollection c1, ICollection c2) { if (c1.Count != c2.Count) return false; IEnumerator c1Enum = c1.GetEnumerator(); IEnumerator c2Enum = c2.GetEnumerator(); while (c1Enum.MoveNext() && c2Enum.MoveNext()) { if (!AreEqual(c1Enum.Current, c2Enum.Current)) return false; } return true; } public static bool DictEquals<K, V>(Dictionary<K, V> d1, Dictionary<K, V> d2) { if (d1 == null && d2 == null) return true; if (d1 == null || d2 == null) return false; if (d1.Count != d2.Count) return false; foreach (K k in d1.Keys) { if (!d2.ContainsKey(k) || !EqualOrEquallyNull(d2[k], d1[k])) return false; } return true; } internal static bool EqualOrEquallyNull(object o1, object o2) { return o1 == null ? o2 == null : o1.Equals(o2); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="opaqueRefs">Must not be null.</param> /// <returns></returns> internal static string[] RefListToStringArray<T>(List<XenRef<T>> opaqueRefs) where T : XenObject<T> { string[] result = new string[opaqueRefs.Count]; int i = 0; foreach (XenRef<T> opaqueRef in opaqueRefs) result[i++] = opaqueRef.opaque_ref; return result; } public static bool IsNullOrEmptyOpaqueRef(string opaqueRef) { return string.IsNullOrEmpty(opaqueRef) || (string.Compare(opaqueRef, NullOpaqueRef, true) == 0); } /// <summary> /// Converts a List of objects into a string array by calling the ToString() method of each list element. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list">Must not be null. Must not contain null. May contain no elements.</param> /// <returns></returns> internal static string[] ObjectListToStringArray<T>(List<T> list) { string[] result = new string[list.Count]; int i = 0; foreach (T t in list) result[i++] = t.ToString(); return result; } /// <summary> /// Parses an array of strings into a List of members of the given enum T. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input">Must not be null. Must not contain null. May have Length zero.</param> /// <returns></returns> internal static List<T> StringArrayToEnumList<T>(string[] input) { List<T> result = new List<T>(); foreach (string s in input) { try { result.Add((T)Enum.Parse(typeof(T), s)); } catch (ArgumentException) { } } return result; } /// <summary> /// Parses an array of strings into an Array of longs /// </summary> /// <param name="input">Must not be null. Must not contain null. May have Length zero.</param> /// <returns></returns> internal static long[] StringArrayToLongArray(string[] input) { long[] result = new long[input.Length]; for(int i=0; i<input.Length; i++) { try { result[i]=long.Parse(input[i]); } catch (ArgumentException) { } } return result; } /// <summary> /// Parses an array of longs into an Array of strings /// </summary> /// <param name="input">Must not be null. Must not contain null. May have Length zero.</param> /// <returns></returns> internal static string[] LongArrayToStringArray(long[] input) { string[] result = new string[input.Length]; for(int i=0; i<input.Length; i++) { try { result[i]=input[i].ToString(); } catch (ArgumentException) { } } return result; } /// <summary> /// Parses an array of objects into a List of members of the given enum T by first calling ToString() on each array element. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input">Must not be null. Must not contain null. May have Length zero.</param> /// <returns></returns> internal static List<T> ObjectArrayToEnumList<T>(object[] input) { List<T> result = new List<T>(); foreach (object o in input) { try { result.Add((T)Enum.Parse(typeof(T), o.ToString())); } catch (ArgumentException) { } } return result; } internal static List<Message> Proxy_MessageArrayToMessageList(Proxy_Message[] input) { List<Message> result = new List<Message>(); foreach (Proxy_Message pm in input) { result.Add(new Message(pm)); } return result; } internal static List<Data_source> Proxy_Data_sourceArrayToData_sourceList(Proxy_Data_source[] input) { List<Data_source> result = new List<Data_source>(); foreach (Proxy_Data_source pd in input) { result.Add(new Data_source(pd)); } return result; } internal static Object EnumParseDefault(Type t, string s) { try { return Enum.Parse(t, s == null ? null : s.Replace('-','_')); } catch (ArgumentException) { try { return Enum.Parse(t, "unknown"); } catch (ArgumentException) { try { return Enum.Parse(t, "Unknown"); } catch (ArgumentException) { return 0; } } } } } }
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="Management.CRLDPServerBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementCRLDPServerCRLDPServerDefinition))] public partial class ManagementCRLDPServer : iControlInterface { public ManagementCRLDPServer() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] public void create( ManagementCRLDPServerCRLDPServerDefinition [] servers ) { this.Invoke("create", new object [] { servers}); } public System.IAsyncResult Begincreate(ManagementCRLDPServerCRLDPServerDefinition [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { servers}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_servers //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] public void delete_all_servers( ) { this.Invoke("delete_all_servers", new object [0]); } public System.IAsyncResult Begindelete_all_servers(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_servers", new object[0], callback, asyncState); } public void Enddelete_all_servers(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] public void delete_server( string [] servers ) { this.Invoke("delete_server", new object [] { servers}); } public System.IAsyncResult Begindelete_server(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_server", new object[] { servers}, callback, asyncState); } public void Enddelete_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_base_dn //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_base_dn( string [] servers ) { object [] results = this.Invoke("get_base_dn", new object [] { servers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_base_dn(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_base_dn", new object[] { servers}, callback, asyncState); } public string [] Endget_base_dn(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] servers ) { object [] results = this.Invoke("get_description", new object [] { servers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { servers}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_hostname //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_hostname( string [] servers ) { object [] results = this.Invoke("get_hostname", new object [] { servers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_hostname(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_hostname", new object[] { servers}, callback, asyncState); } public string [] Endget_hostname(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] [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_port //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] get_port( string [] servers ) { object [] results = this.Invoke("get_port", new object [] { servers}); return ((long [])(results[0])); } public System.IAsyncResult Beginget_port(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_port", new object[] { servers}, callback, asyncState); } public long [] Endget_port(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [])(results[0])); } //----------------------------------------------------------------------- // get_reverse_dn_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_reverse_dn_state( string [] servers ) { object [] results = this.Invoke("get_reverse_dn_state", new object [] { servers}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_reverse_dn_state(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_reverse_dn_state", new object[] { servers}, callback, asyncState); } public CommonEnabledState [] Endget_reverse_dn_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] [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])); } //----------------------------------------------------------------------- // set_base_dn //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] public void set_base_dn( string [] servers, string [] base_dns ) { this.Invoke("set_base_dn", new object [] { servers, base_dns}); } public System.IAsyncResult Beginset_base_dn(string [] servers,string [] base_dns, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_base_dn", new object[] { servers, base_dns}, callback, asyncState); } public void Endset_base_dn(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] public void set_description( string [] servers, string [] descriptions ) { this.Invoke("set_description", new object [] { servers, descriptions}); } public System.IAsyncResult Beginset_description(string [] servers,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { servers, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_hostname //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] public void set_hostname( string [] servers, string [] hostnames ) { this.Invoke("set_hostname", new object [] { servers, hostnames}); } public System.IAsyncResult Beginset_hostname(string [] servers,string [] hostnames, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_hostname", new object[] { servers, hostnames}, callback, asyncState); } public void Endset_hostname(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_port //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] public void set_port( string [] servers, long [] ports ) { this.Invoke("set_port", new object [] { servers, ports}); } public System.IAsyncResult Beginset_port(string [] servers,long [] ports, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_port", new object[] { servers, ports}, callback, asyncState); } public void Endset_port(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_reverse_dn_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPServer", RequestNamespace="urn:iControl:Management/CRLDPServer", ResponseNamespace="urn:iControl:Management/CRLDPServer")] public void set_reverse_dn_state( string [] servers, CommonEnabledState [] states ) { this.Invoke("set_reverse_dn_state", new object [] { servers, states}); } public System.IAsyncResult Beginset_reverse_dn_state(string [] servers,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_reverse_dn_state", new object[] { servers, states}, callback, asyncState); } public void Endset_reverse_dn_state(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 = "Management.CRLDPServer.CRLDPServerDefinition", Namespace = "urn:iControl")] public partial class ManagementCRLDPServerCRLDPServerDefinition { private string nameField; public string name { get { return this.nameField; } set { this.nameField = value; } } private string hostnameField; public string hostname { get { return this.hostnameField; } set { this.hostnameField = value; } } private long portField; public long port { get { return this.portField; } set { this.portField = value; } } }; }
// 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.Text; using System.Xml; using Microsoft.Build.Framework; using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; using Xunit; namespace Microsoft.Build.UnitTests { /// <summary> /// Unit tests for the AppConfig class /// </summary> public class AppConfig_Tests { /// <summary> /// A simple app.config. /// </summary> [Fact] public void Simple() { AppConfig app = new AppConfig(); string xml = "<configuration>\n" + " <runtime>\n" + " <dependentAssembly>\n" + " <assemblyIdentity name='Simple' PublicKeyToken='b03f5f7f11d50a3a' culture='neutral' />\n" + " <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" + " </dependentAssembly>\n" + " </runtime>\n" + "</configuration>"; app.Read(new XmlTextReader(xml, XmlNodeType.Document, null)); string s = Summarize(app); Assert.Contains("Dependent Assembly: Simple, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a oldVersionLow=1.0.0.0 oldVersionHigh=1.0.0.0 newVersion=2.0.0.0", s); } /// <summary> /// A simple app.config. /// </summary> [Fact] public void SimpleRange() { AppConfig app = new AppConfig(); string xml = "<configuration>\n" + " <runtime>\n" + " <dependentAssembly>\n" + " <assemblyIdentity name='Simple' PublicKeyToken='b03f5f7f11d50a3a' culture='neutral' />\n" + " <bindingRedirect oldVersion='1.0.0.0-2.0.0.0' newVersion='2.0.0.0' />\n" + " </dependentAssembly>\n" + " </runtime>\n" + "</configuration>"; app.Read(new XmlTextReader(xml, XmlNodeType.Document, null)); string s = Summarize(app); Assert.Contains("Dependent Assembly: Simple, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a oldVersionLow=1.0.0.0 oldVersionHigh=2.0.0.0 newVersion=2.0.0.0", s); } /// <summary> /// An app.config taken from rascal, that has some bindingRedirects. /// </summary> [Fact] public void RascalTest() { AppConfig app = new AppConfig(); string xml = "<configuration>\n" + " <runtime>\n" + " <assemblyBinding xmlns='urn:schemas-microsoft-com:asm.v1'>\n" + " <probing privatePath='PrimaryInteropAssemblies'/>\n" + " <qualifyAssembly partialName='System.Web' fullName='System.Web, Version=1.2.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, Custom=null'/>\n" + " <qualifyAssembly partialName='System' fullName='System, Version=1.2.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null'/>\n" + " <qualifyAssembly partialName='CustomMarshalers' fullName='CustomMarshalers, Version=1.2.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'/>\n" + " <qualifyAssembly partialName='CustomMarshalers, Version=1.2.3300.0' fullName='CustomMarshalers, Version=1.2.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'/>\n" + " <qualifyAssembly partialName='CustomMarshalers, Version=1.2.3300.0, PublicKeyToken=b03f5f7f11d50a3a' fullName='CustomMarshalers, Version=1.2.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'/>\n" + " </assemblyBinding>\n" + " <dependentAssembly>\n" + " <assemblyIdentity name='Microsoft.VSDesigner' PublicKeyToken='b03f5f7f11d50a3a' culture='neutral' />\n" + " <bindingRedirect oldVersion='7.0.3300.0' newVersion='8.0.1000.0' />\n" + " </dependentAssembly>\n" + " <dependentAssembly>\n" + " <assemblyIdentity name='Microsoft.VisualStudio.Designer.Interfaces' PublicKeyToken='b03f5f7f11d50a3a' culture='neutral' />\n" + " <bindingRedirect oldVersion='1.0.3300.0' newVersion='1.2.3400.0' />\n" + " </dependentAssembly>\n" + " <dependentAssembly>\n" + " <assemblyIdentity name='Microsoft.VisualStudio' PublicKeyToken='b03f5f7f11d50a3a' culture='neutral' />\n" + " <bindingRedirect oldVersion='1.0.3300.0' newVersion='1.2.3400.0' />\n" + " </dependentAssembly>\n" + " </runtime>\n" + " <system.net>\n" + " <settings>\n" + " <ipv6 enabled='true' />\n" + " </settings>\n" + " </system.net>\n" + "</configuration>"; app.Read(new XmlTextReader(xml, XmlNodeType.Document, null)); string s = Summarize(app); Assert.Contains("Dependent Assembly: Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a oldVersionLow=7.0.3300.0 oldVersionHigh=7.0.3300.0 newVersion=8.0.1000.0", s); Assert.Contains("Dependent Assembly: Microsoft.VisualStudio.Designer.Interfaces, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a oldVersionLow=1.0.3300.0 oldVersionHigh=1.0.3300.0 newVersion=1.2.3400.0", s); Assert.Contains("Dependent Assembly: Microsoft.VisualStudio, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a oldVersionLow=1.0.3300.0 oldVersionHigh=1.0.3300.0 newVersion=1.2.3400.0", s); } /// <summary> /// A machine.config file. /// </summary> [Fact] public void MachineConfig() { AppConfig app = new AppConfig(); string xml = "<configuration>\n" + " <runtime>\n" + " <developerSettings\n" + " installationVersion='v2.0.40107.0' />\n" + " <assemblyBinding xmlns='urn:schemas-microsoft-com:asm.v1'>\n" + " <dependentAssembly>\n" + " <assemblyIdentity name='Microsoft.VSDesigner' publicKeyToken='b03f5f7f11d50a3a' />\n" + " <bindingRedirect oldVersion='7.1.3300.0' newVersion='7.2.3300.0' />\n" + " </dependentAssembly>\n" + " </assemblyBinding>\n" + " </runtime>\n" + " <system.runtime.remoting>\n" + " <application>\n" + " <channels>\n" + " <channel ref='http client' displayName='http client (delay loaded)' delayLoadAsClientChannel='true' />\n" + " <channel ref='tcp client' displayName='tcp client (delay loaded)' delayLoadAsClientChannel='true' />\n" + " <channel ref='tcps client' displayName='tcps client (delay loaded)' delayLoadAsClientChannel='true' />\n" + " </channels>\n" + " </application>\n" + " <channels>\n" + " <channel id='http' type='System.Runtime.Remoting.Channels.Http.HttpChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <channel id='https' secure='true' type='System.Runtime.Remoting.Channels.Http.HttpChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <channel id='http client' type='System.Runtime.Remoting.Channels.Http.HttpClientChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <channel id='http server' type='System.Runtime.Remoting.Channels.Http.HttpServerChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <channel id='https server' secure='true' type='System.Runtime.Remoting.Channels.Http.HttpServerChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <channel id='tcp' type='System.Runtime.Remoting.Channels.Tcp.TcpChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <channel id='tcps' secure='true' type='System.Runtime.Remoting.Channels.Tcp.TcpChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <channel id='tcp client' type='System.Runtime.Remoting.Channels.Tcp.TcpClientChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <channel id='tcps client' secure='true' type='System.Runtime.Remoting.Channels.Tcp.TcpClientChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <channel id='tcp server' type='System.Runtime.Remoting.Channels.Tcp.TcpServerChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <channel id='tcps server' secure='true' type='System.Runtime.Remoting.Channels.Tcp.TcpServerChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " </channels>\n" + " <channelSinkProviders>\n" + " <clientProviders>\n" + " <formatter id='soap' type='System.Runtime.Remoting.Channels.SoapClientFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <formatter id='binary' type='System.Runtime.Remoting.Channels.BinaryClientFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " </clientProviders>\n" + " <serverProviders>\n" + " <formatter id='soap' type='System.Runtime.Remoting.Channels.SoapServerFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <formatter id='binary' type='System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " <provider id='wsdl' type='System.Runtime.Remoting.MetadataServices.SdlChannelSinkProvider, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' />\n" + " </serverProviders>\n" + " </channelSinkProviders>\n" + " </system.runtime.remoting>\n" + "</configuration> "; app.Read(new XmlTextReader(xml, XmlNodeType.Document, null)); string s = Summarize(app); Assert.Contains("Dependent Assembly: Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a oldVersionLow=7.1.3300.0 oldVersionHigh=7.1.3300.0 newVersion=7.2.3300.0", s); } /// <summary> /// Make sure that only dependent assemblies under the configuration-->runtime tag work. /// </summary> [Fact] public void Regress339840_DependentAssemblyUnderAlienTag() { AppConfig app = new AppConfig(); string xml = "<configuration>\n" + " <runtime>\n" + " <dependentAssembly>\n" + " <assemblyIdentity name='Simple' PublicKeyToken='b03f5f7f11d50a3a' culture='neutral' />\n" + " <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" + " </dependentAssembly>\n" + " </runtime>\n" + "</configuration>"; app.Read(new XmlTextReader(xml, XmlNodeType.Document, null)); string s = Summarize(app); Assert.Contains("Dependent Assembly", s); } /// <summary> /// Summarize the parsed contents of the app.config files. /// </summary> /// <param name="app"></param> private static string Summarize(AppConfig app) { StringBuilder b = new StringBuilder(); foreach (DependentAssembly dependentAssembly in app.Runtime.DependentAssemblies) { foreach (BindingRedirect bindingRedirect in dependentAssembly.BindingRedirects) { string message = String.Format("Dependent Assembly: {0} oldVersionLow={1} oldVersionHigh={2} newVersion={3}", dependentAssembly.PartialAssemblyName, bindingRedirect.OldVersionLow, bindingRedirect.OldVersionHigh, bindingRedirect.NewVersion); b.AppendLine(message); } } Console.WriteLine(b.ToString()); return b.ToString(); } } }
//----------------------------------------------------------------------------- // // <copyright file="CompoundFileDeflateTransform.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // Implementation of a helper class that provides a fully functional Stream on unmanaged ZLib in a fashion // consistent with Office and RMA (see Creating Rights-Managed HTML Files at // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/rma/introduction.asp). // // History: // 10/05/2005: BruceMac: First created. // 02/14/2006: BruceMac: Rename file to reflect class name and apply security mitigations // identified during security code review. // 03/09/2006: BruceMac: Make AllocOrRealloc SecurityCritical because it allocates // pinned memory based on caller arguments. //----------------------------------------------------------------------------- // Allow use of presharp warning numbers [6518] unknown to the compiler #pragma warning disable 1634, 1691 using System; using System.IO; using System.Diagnostics; using System.IO.Compression; using System.IO.Packaging; using System.Windows; using System.Runtime.InteropServices; // for Marshal class using MS.Internal.IO.Packaging; // for PackagingUtilities using System.Security; // for SecurityCritical and SecurityTreatAsSafe using MS.Internal.WindowsBase; namespace MS.Internal.IO.Packaging.CompoundFile { //------------------------------------------------------ // // Internal Members // //------------------------------------------------------ /// <summary> /// Provides Office-compatible ZLib compression using interop to ZLib library /// </summary> /// <remarks>This class makes use of GCHandles in order to share data in a non-trivial fashion with the /// unmanaged ZLib library. Because of this, it demands UnmanagedCodePermission of it's caller. /// IDeflateTransform is a batch-oriented interface. All data will be transformed from source /// to destination.</remarks> internal class CompoundFileDeflateTransform : IDeflateTransform { //------------------------------------------------------ // // IDeflateTransform Interface // //------------------------------------------------------ /// <summary> /// Decompress delegate - invoke ZLib in a manner consistent with RMA/Office /// </summary> /// <param name="source">stream to read from</param> /// <param name="sink">stream to write to</param> ///<SecurityNote> /// Critical: calls AllocOrRealloc which is allocates pinned memory based on arguments /// TreatAsSafe: Callers cannot use this to allocate memory of arbitrary size. /// AllocOrRealloc is used in two occasions: /// 1. Compress - here we provide size based on our default block size (of 4k) /// and growth will not exceed double this size (we are compressing, but sometimes /// compression doesn't succeed in reducing sizes). /// 2. Decompress - here the block size is based on values obtained from the /// stream itself (see ReadBlockHeader) but we are careful to throw on malicious /// input. Any size > 1MB is considered malicious and rejected. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] public void Decompress(Stream source, Stream sink) { if (source == null) throw new ArgumentNullException("source"); if (sink == null) throw new ArgumentNullException("sink"); Invariant.Assert(source.CanRead); Invariant.Assert(sink.CanWrite, "Logic Error - Cannot decompress into a read-only stream"); // remember this for later long storedPosition = -1; try { if (source.CanSeek) { storedPosition = source.Position; source.Position = 0; } if (sink.CanSeek) sink.Position = 0; // zlib state ZLibNative.ZLibStreamHandle zStream; // initialize the zlib library ZLibNative.ErrorCode retVal = ZLibNative.CreateZLibStreamForInflate(out zStream, DEFAULT_WINDOW_BITS); ThrowIfZLibError(retVal); byte[] sourceBuf = null; // source buffer byte[] sinkBuf = null; // destination buffer - where to write data GCHandle gcSourceBuf = new GCHandle(); // Preallocate these so we can safely access them GCHandle gcSinkBuf = new GCHandle(); // in the next finally block. try { // read all available data // each block is preceded by a header that is 3 ulongs int uncompressedSize, compressedSize; long destStreamLength = 0; // keep track of decompressed size while (ReadBlockHeader(source, out uncompressedSize, out compressedSize)) { // ensure we have space AllocOrRealloc(compressedSize, ref sourceBuf, ref gcSourceBuf); AllocOrRealloc(uncompressedSize, ref sinkBuf, ref gcSinkBuf); // read the data into the sourceBuf int bytesRead = PackagingUtilities.ReliableRead(source, sourceBuf, 0, compressedSize); if (bytesRead > 0) { if (compressedSize != bytesRead) throw new FileFormatException(SR.Get(SRID.CorruptStream)); // prepare structure // The buffer pointers must be reset for every call // because ZLibNative.Inflate modifies them zStream.NextIn = gcSourceBuf.AddrOfPinnedObject(); zStream.NextOut = gcSinkBuf.AddrOfPinnedObject(); zStream.AvailIn = (uint)bytesRead; // this is number of bytes available for decompression at pInBuf and is updated by ums_deflate call zStream.AvailOut = (uint)sinkBuf.Length; // this is the number of bytes free in pOutBuf and is updated by ums_deflate call // InvokeZLib does the actual interop. It updates zStream, and sinkBuf (sourceBuf passed by ref to avoid copying) // and leaves the decompressed data in sinkBuf. // int decompressedSize = InvokeZLib(bytesRead, ref zStream, ref sourceBuf, ref sinkBuf, pSource, pSink, false); retVal = zStream.Inflate(ZLibNative.FlushCode.SyncFlush); ThrowIfZLibError(retVal); checked { int decompressedSize = sinkBuf.Length - (int) zStream.AvailOut; // verify that data matches header if (decompressedSize != uncompressedSize) throw new FileFormatException(SR.Get(SRID.CorruptStream)); destStreamLength += decompressedSize; // write to the base stream sink.Write(sinkBuf, 0, decompressedSize); } } else { // block header but no block data if (compressedSize != 0) throw new FileFormatException(SR.Get(SRID.CorruptStream)); } } // make sure we truncate if the destination stream was longer than this current decompress if (sink.CanSeek) sink.SetLength(destStreamLength); } finally { if (gcSourceBuf.IsAllocated) gcSourceBuf.Free(); if (gcSinkBuf.IsAllocated) gcSinkBuf.Free(); } } finally { // seek to the current logical position before returning if (source.CanSeek) source.Position = storedPosition; } } /// <summary> /// Compress delegate - invoke ZLib in a manner consistent with RMA/Office /// </summary> /// <param name="source"></param> /// <param name="sink"></param> /// <remarks>We are careful to avoid use of Position, Length or SetLength on non-seekable streams. If /// source or sink are non-seekable, it is assumed that positions are correctly set upon entry and that /// they need not be restored. We also assume that destination stream length need not be truncated.</remarks> ///<SecurityNote> /// Critical: calls AllocOrRealloc which is allocates pinned memory based on arguments /// TreatAsSafe: Callers cannot use this to allocate memory of arbitrary size. /// AllocOrRealloc is used in two occasions: /// 1. Compress - here we provide size based on our default block size (of 4k) /// and growth will not exceed double this size (we are compressing, but sometimes /// compression doesn't succeed in reducing sizes). /// 2. Decompress - here the block size is based on values obtained from the /// stream itself (see ReadBlockHeader) but we are careful to throw on malicious /// input. Any size > 1MB is considered malicious and rejected. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] public void Compress(Stream source, Stream sink) { if (source == null) throw new ArgumentNullException("source"); if (sink == null) throw new ArgumentNullException("sink"); Invariant.Assert(source.CanRead); Invariant.Assert(sink.CanWrite, "Logic Error - Cannot compress into a read-only stream"); // remember this for later if possible long storedPosition = -1; // default to illegal value to catch any logic errors try { int sourceBufferSize; // don't allocate 4k for really tiny source streams if (source.CanSeek) { storedPosition = source.Position; source.Position = 0; // Casting result to int is safe because _defaultBlockSize is very small and the result // of Math.Min(x, _defaultBlockSize) must be no larger than _defaultBlockSize. sourceBufferSize = (int)(Math.Min(source.Length, (long)_defaultBlockSize)); } else sourceBufferSize = _defaultBlockSize; // can't call Length so fallback to default if (sink.CanSeek) sink.Position = 0; // zlib state ZLibNative.ZLibStreamHandle zStream; // initialize the zlib library ZLibNative.ErrorCode retVal = ZLibNative.CreateZLibStreamForDeflate( out zStream, ZLibNative.CompressionLevel.DefaultCompression, DEFAULT_WINDOW_BITS, DEFAULT_MEM_LEVEL, ZLibNative.CompressionStrategy.DefaultStrategy); ThrowIfZLibError(retVal); // where to write data - can actually grow if data is uncompressible long destStreamLength = 0; byte[] sourceBuf = null; // source buffer byte[] sinkBuf = null; // destination buffer GCHandle gcSourceBuf = new GCHandle(); GCHandle gcSinkBuf = new GCHandle(); try { // allocate managed buffers AllocOrRealloc(sourceBufferSize, ref sourceBuf, ref gcSourceBuf); AllocOrRealloc(_defaultBlockSize + (_defaultBlockSize >> 1), ref sinkBuf, ref gcSinkBuf); // while (more data is available) // - read into the sourceBuf // - compress into the sinkBuf // - emit the header // - write out to the _baseStream // Suppress 6518 Local IDisposable object not disposed: // Reason: The stream is not owned by us, therefore we cannot // close the BinaryWriter as it will Close the stream underneath. #pragma warning disable 6518 BinaryWriter writer = new BinaryWriter(sink); int bytesRead; while ((bytesRead = PackagingUtilities.ReliableRead(source, sourceBuf, 0, sourceBuf.Length)) > 0) { Invariant.Assert(bytesRead <= sourceBufferSize); // prepare structure // these pointers must be re-assigned for each loop because // ums_deflate modifies them zStream.NextIn = gcSourceBuf.AddrOfPinnedObject(); zStream.NextOut = gcSinkBuf.AddrOfPinnedObject(); zStream.AvailIn = (uint)bytesRead; // this is number of bytes available for compression at pInBuf and is updated by ums_deflate call zStream.AvailOut = (uint)sinkBuf.Length; // this is the number of bytes free in pOutBuf and is updated by ums_deflate call // cast is safe because SyncFlush is a constant retVal = zStream.Deflate(ZLibNative.FlushCode.SyncFlush); ThrowIfZLibError(retVal); checked { int compressedSize = sinkBuf.Length - (int) zStream.AvailOut; Invariant.Assert(compressedSize > 0, "compressing non-zero bytes creates a non-empty block"); // This should never happen because our destination buffer // is twice as large as our source buffer Invariant.Assert(zStream.AvailIn == 0, "Expecting all data to be compressed!"); // write the header writer.Write(_blockHeaderToken); // token writer.Write((UInt32)bytesRead); writer.Write((UInt32)compressedSize); destStreamLength += _headerBuf.Length; // write to the base stream sink.Write(sinkBuf, 0, compressedSize); destStreamLength += compressedSize; } } // post-compression // truncate if necessary if (sink.CanSeek) sink.SetLength(destStreamLength); } finally { if (gcSourceBuf.IsAllocated) gcSourceBuf.Free(); if (gcSinkBuf.IsAllocated) gcSinkBuf.Free(); } #pragma warning restore 6518 } finally { // seek to the current logical position before returning if (sink.CanSeek) source.Position = storedPosition; } } //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ /// <summary> /// Ensures that Buffer has enough room for size using alloc or realloc /// </summary> /// <param name="buffer">buffer - may be null</param> /// <param name="size">desired size</param> /// <param name="gcHandle">handle</param> /// <remarks>When this exits, buffer is at least as large as size /// and gcHandle is pointing to the pinned buffer. If the buffer was already large enough, /// no action is taken.</remarks> /// <SecurityNote> /// Critical - allocates pinned memory based on arguments /// </SecurityNote> [SecurityCritical] private static void AllocOrRealloc(int size, ref byte[] buffer, ref GCHandle gcHandle) { Invariant.Assert(size >= 0, "Cannot allocate negative number of bytes"); // verify we have room if (buffer != null) { // do we have room? if (buffer.Length < size) { // overallocate to reduce the chance of future reallocations size = Math.Max(size, buffer.Length + (buffer.Length >> 1)); // fast Length * 1.5 // free existing because it's too small if (gcHandle.IsAllocated) gcHandle.Free(); } else return; // current buffer satisfies the request so there is no need to alloc } // We have to allocate in two cases: // 1. We were called with buffer == null // 2. The original buffer was too small buffer = new byte[size]; // managed source buffer gcHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); // pinned so unmanaged code can read/write it } /// <summary> /// ReadBlockHeader - reads the block header and returns true if successful /// </summary> /// <param name="source">stream to read from</param> /// <param name="compressedSize">compressedSize from header</param> /// <param name="uncompressedSize">uncompressedSize from header</param> /// <returns>true if header found</returns> private bool ReadBlockHeader(Stream source, out int uncompressedSize, out int compressedSize) { int bytesRead = PackagingUtilities.ReliableRead(source, _headerBuf, 0, _headerBuf.Length); if (bytesRead > 0) { if (bytesRead < _headerBuf.Length) throw new FileFormatException(SR.Get(SRID.CorruptStream)); // header format = 3 ulong's // read and inspect token uint token = BitConverter.ToUInt32(_headerBuf, _ulongSize * 0); if (token != _blockHeaderToken) throw new FileFormatException(SR.Get(SRID.CorruptStream)); // convert to int's as that's what we use everywhere checked { uncompressedSize = (int)BitConverter.ToUInt32(_headerBuf, _ulongSize * 1); compressedSize = (int)BitConverter.ToUInt32(_headerBuf, _ulongSize * 2); // screen out malicious data if (uncompressedSize < 0 || uncompressedSize > _maxAllowableBlockSize || compressedSize < 0 || compressedSize > _maxAllowableBlockSize) throw new FileFormatException(SR.Get(SRID.CorruptStream)); } } else { uncompressedSize = compressedSize = 0; } return (bytesRead > 0); } /// <summary> /// Throw exception based on ZLib error code /// </summary> /// <param name="retVal"></param> private static void ThrowIfZLibError(ZLibNative.ErrorCode retVal) { // switch does not support fall-through bool invalidOperation = false; bool corruption = false; switch (retVal) { case ZLibNative.ErrorCode.Ok: return; case ZLibNative.ErrorCode.StreamEnd: invalidOperation = true; break; case ZLibNative.ErrorCode.NeedDictionary: corruption = true; break; case ZLibNative.ErrorCode.StreamError: corruption = true; break; case ZLibNative.ErrorCode.DataError: corruption = true; break; case ZLibNative.ErrorCode.MemError: throw new OutOfMemoryException(); case ZLibNative.ErrorCode.BufError: invalidOperation = true; break; case ZLibNative.ErrorCode.VersionError: throw new InvalidOperationException(SR.Get(SRID.ZLibVersionError, ZLibNative.ZLibVersion)); default: { // ErrorNo throw new IOException(); } } if (invalidOperation) throw new InvalidOperationException(); if (corruption) throw new FileFormatException(SR.Get(SRID.CorruptStream)); } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ // for reading each block header private byte[] _headerBuf = new byte[_blockHeaderSize]; // 3 ulongs // static private const int _defaultBlockSize = 0x1000; // 4k default private const int _maxAllowableBlockSize = 0xFFFFF; // The spec is open ended about supported block sizes but we // want to defend against malicious input so we restrict input to 1MB. private const int _ulongSize = 4; // a ULONG in unmanaged C++ is 4 bytes private const UInt32 _blockHeaderToken = 0x0FA0; // signature at start of each block header private const int _blockHeaderSize = _ulongSize * 3; // length of block header private const int DEFAULT_WINDOW_BITS = 15; private const int DEFAULT_MEM_LEVEL = 8; } }
// 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 Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.PythonTools.Django.Project { /// <summary> /// Merges the PTVS IVsCfg object with the Venus IVsCfg implementation redirecting /// things appropriately to either one. /// </summary> class DjangoProjectConfig : IVsCfg, IVsProjectCfg, IVsProjectCfg2, IVsProjectFlavorCfg, IVsDebuggableProjectCfg, ISpecifyPropertyPages, IVsSpecifyProjectDesignerPages, IVsCfgBrowseObject { private readonly IVsCfg _pythonCfg; private readonly IVsProjectFlavorCfg _webCfg; public DjangoProjectConfig(IVsCfg pythonCfg, IVsProjectFlavorCfg webConfig) { _pythonCfg = pythonCfg; _webCfg = webConfig; } #region IVsCfg Members public int get_DisplayName(out string pbstrDisplayName) { return _pythonCfg.get_DisplayName(out pbstrDisplayName); } public int get_IsDebugOnly(out int pfIsDebugOnly) { return _pythonCfg.get_IsDebugOnly(out pfIsDebugOnly); } public int get_IsReleaseOnly(out int pfIsReleaseOnly) { return _pythonCfg.get_IsReleaseOnly(out pfIsReleaseOnly); } #endregion #region IVsProjectCfg Members public int EnumOutputs(out IVsEnumOutputs ppIVsEnumOutputs) { IVsProjectCfg projCfg = _webCfg as IVsProjectCfg; if (projCfg != null) { return projCfg.EnumOutputs(out ppIVsEnumOutputs); } ppIVsEnumOutputs = null; return VSConstants.E_NOTIMPL; } public int OpenOutput(string szOutputCanonicalName, out IVsOutput ppIVsOutput) { IVsProjectCfg projCfg = _webCfg as IVsProjectCfg; if (projCfg != null) { return projCfg.OpenOutput(szOutputCanonicalName, out ppIVsOutput); } ppIVsOutput = null; return VSConstants.E_NOTIMPL; } public int get_BuildableProjectCfg(out IVsBuildableProjectCfg ppIVsBuildableProjectCfg) { IVsProjectCfg projCfg = _webCfg as IVsProjectCfg; if (projCfg != null) { return projCfg.get_BuildableProjectCfg(out ppIVsBuildableProjectCfg); } ppIVsBuildableProjectCfg = null; return VSConstants.E_NOTIMPL; } public int get_CanonicalName(out string pbstrCanonicalName) { IVsProjectCfg projCfg = _webCfg as IVsProjectCfg; if (projCfg != null) { return projCfg.get_CanonicalName(out pbstrCanonicalName); } pbstrCanonicalName = null; return VSConstants.E_NOTIMPL; } public int get_IsPackaged(out int pfIsPackaged) { IVsProjectCfg projCfg = _webCfg as IVsProjectCfg; if (projCfg != null) { return projCfg.get_IsPackaged(out pfIsPackaged); } pfIsPackaged = 0; return VSConstants.E_NOTIMPL; } public int get_IsSpecifyingOutputSupported(out int pfIsSpecifyingOutputSupported) { IVsProjectCfg projCfg = _webCfg as IVsProjectCfg; if (projCfg != null) { return projCfg.get_IsSpecifyingOutputSupported(out pfIsSpecifyingOutputSupported); } pfIsSpecifyingOutputSupported = 0; return VSConstants.E_NOTIMPL; } public int get_Platform(out Guid pguidPlatform) { IVsProjectCfg projCfg = _webCfg as IVsProjectCfg; if (projCfg != null) { return projCfg.get_Platform(out pguidPlatform); } pguidPlatform = Guid.Empty; return VSConstants.E_NOTIMPL; } public int get_ProjectCfgProvider(out IVsProjectCfgProvider ppIVsProjectCfgProvider) { IVsProjectCfg projCfg = _webCfg as IVsProjectCfg; if (projCfg != null) { return projCfg.get_ProjectCfgProvider(out ppIVsProjectCfgProvider); } ppIVsProjectCfgProvider = null; return VSConstants.E_NOTIMPL; } public int get_RootURL(out string pbstrRootURL) { IVsProjectCfg projCfg = _webCfg as IVsProjectCfg; if (projCfg != null) { return projCfg.get_RootURL(out pbstrRootURL); } pbstrRootURL = null; return VSConstants.E_NOTIMPL; } public int get_TargetCodePage(out uint puiTargetCodePage) { IVsProjectCfg projCfg = _webCfg as IVsProjectCfg; if (projCfg != null) { return projCfg.get_TargetCodePage(out puiTargetCodePage); } puiTargetCodePage = 0; return VSConstants.E_NOTIMPL; } public int get_UpdateSequenceNumber(ULARGE_INTEGER[] puliUSN) { IVsProjectCfg projCfg = _webCfg as IVsProjectCfg; if (projCfg != null) { return projCfg.get_UpdateSequenceNumber(puliUSN); } return VSConstants.E_NOTIMPL; } #endregion #region IVsProjectCfg2 Members public int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup) { IVsProjectCfg2 projCfg = _pythonCfg as IVsProjectCfg2; if (projCfg != null) { return projCfg.OpenOutputGroup(szCanonicalName, out ppIVsOutputGroup); } ppIVsOutputGroup = null; return VSConstants.E_NOTIMPL; } public int OutputsRequireAppRoot(out int pfRequiresAppRoot) { IVsProjectCfg2 projCfg = _pythonCfg as IVsProjectCfg2; if (projCfg != null) { return projCfg.OutputsRequireAppRoot(out pfRequiresAppRoot); } pfRequiresAppRoot = 1; return VSConstants.E_NOTIMPL; } public int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg) { if (iidCfg == typeof(IVsDebuggableProjectCfg).GUID) { var pyCfg = _pythonCfg as IVsProjectFlavorCfg; if (pyCfg != null) { return pyCfg.get_CfgType(ref iidCfg, out ppCfg); } } var projCfg = _webCfg as IVsProjectFlavorCfg; if (projCfg != null) { return projCfg.get_CfgType(ref iidCfg, out ppCfg); } ppCfg = IntPtr.Zero; return VSConstants.E_NOTIMPL; } public int get_IsPrivate(out int pfPrivate) { IVsProjectCfg2 projCfg = _pythonCfg as IVsProjectCfg2; if (projCfg != null) { return projCfg.get_IsPrivate(out pfPrivate); } pfPrivate = 0; return VSConstants.E_NOTIMPL; } public int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual = null) { IVsProjectCfg2 projCfg = _pythonCfg as IVsProjectCfg2; if (projCfg != null) { return projCfg.get_OutputGroups(celt, rgpcfg, pcActual); } return VSConstants.E_NOTIMPL; } public int get_VirtualRoot(out string pbstrVRoot) { IVsProjectCfg2 projCfg = _pythonCfg as IVsProjectCfg2; if (projCfg != null) { return projCfg.get_VirtualRoot(out pbstrVRoot); } pbstrVRoot = null; return VSConstants.E_NOTIMPL; } #endregion #region IVsProjectFlavorCfg Members public int Close() { IVsProjectFlavorCfg cfg = _webCfg as IVsProjectFlavorCfg; if (cfg != null) { return cfg.Close(); } return VSConstants.S_OK; } #endregion #region IVsDebuggableProjectCfg Members public int DebugLaunch(uint grfLaunch) { IVsDebuggableProjectCfg cfg = _pythonCfg as IVsDebuggableProjectCfg; if (cfg != null) { return cfg.DebugLaunch(grfLaunch); } return VSConstants.E_NOTIMPL; } public int QueryDebugLaunch(uint grfLaunch, out int pfCanLaunch) { IVsDebuggableProjectCfg cfg = _pythonCfg as IVsDebuggableProjectCfg; if (cfg != null) { return cfg.QueryDebugLaunch(grfLaunch, out pfCanLaunch); } pfCanLaunch = 0; return VSConstants.E_NOTIMPL; } #endregion #region ISpecifyPropertyPages Members public void GetPages(CAUUID[] pPages) { var cfg = _pythonCfg as ISpecifyPropertyPages; if (cfg != null) { cfg.GetPages(pPages); } } #endregion #region IVsSpecifyProjectDesignerPages Members public int GetProjectDesignerPages(CAUUID[] pPages) { var cfg = _pythonCfg as IVsSpecifyProjectDesignerPages; if (cfg != null) { return cfg.GetProjectDesignerPages(pPages); } return VSConstants.E_NOTIMPL; } #endregion #region IVsCfgBrowseObject Members public int GetCfg(out IVsCfg ppCfg) { ppCfg = this; return VSConstants.S_OK; } public int GetProjectItem(out IVsHierarchy pHier, out uint pItemid) { var cfg = _pythonCfg as IVsCfgBrowseObject; if (cfg != null) { return cfg.GetProjectItem(out pHier, out pItemid); } pHier = null; pItemid = 0; return VSConstants.E_NOTIMPL; } #endregion } }
namespace Microsoft.Protocols.TestSuites.SharedTestSuite { using System; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.SharedAdapter; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// A class which contains test cases used to capture the requirements related with FileOperation operation. /// </summary> [TestClass] public abstract class S17_FileOperation : SharedTestSuiteBase { #region Test Suite Initialization and clean up /// <summary> /// A method used to initialize this class. /// </summary> /// <param name="testContext">A parameter represents the context of the test suite.</param> [ClassInitialize] public static new void ClassInitialize(TestContext testContext) { SharedTestSuiteBase.ClassInitialize(testContext); } /// <summary> /// A method used to clean up this class. /// </summary> [ClassCleanup] public static new void ClassCleanup() { SharedTestSuiteBase.ClassCleanup(); } #endregion #region Test Case Initialization /// <summary> /// A method used to initialize the test class. /// </summary> [TestInitialize] public void S17_FileOperationInitialization() { this.Site.Assume.IsTrue(Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 111111, this.Site), "This test case only runs when FileOperation subrequest is supported."); this.DefaultFileUrl = this.PrepareFile(); } #endregion #region Test Cases for "FileOperation" sub-request. /// <summary> /// A method used to verify that FileOperation sub-request can be executed successfully when all input parameters are correct. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S17_TC01_FileOperation_Success() { // Initialize the context using user01 and defaultFileUrl. this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Get the exclusive lock with all valid parameters, expect the server responses the error code "Success". ExclusiveLockSubRequestType subRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.GetLock); CellStorageResponse cellStoreageResponse = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { subRequest }); ExclusiveLockSubResponseType exclusiveResponse = SharedTestSuiteHelper.ExtractSubResponse<ExclusiveLockSubResponseType>(cellStoreageResponse, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site), "Test case cannot continue unless the Get Lock of ExclusiveLock sub request succeeds."); // Record the current file status. this.StatusManager.RecordExclusiveLock(this.DefaultFileUrl, subRequest.SubRequestData.ExclusiveLockID); string fileName = this.DefaultFileUrl.Substring(this.DefaultFileUrl.LastIndexOf("/", StringComparison.OrdinalIgnoreCase) + 1); string newName = Common.GenerateResourceName(this.Site, "fileName") + ".txt"; FileOperationSubRequestType fileOperationSubRequest = SharedTestSuiteHelper.CreateFileOperationSubRequest(FileOperationRequestTypes.Rename, newName, SharedTestSuiteHelper.DefaultExclusiveLockID, this.Site); cellStoreageResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { fileOperationSubRequest }); FileOperationSubResponseType fileOperationSubResponse = SharedTestSuiteHelper.ExtractSubResponse<FileOperationSubResponseType>(cellStoreageResponse, 0, 0, this.Site); this.Site.Assert.IsNotNull(fileOperationSubResponse, "The object 'versioningSubResponse' should not be null."); this.Site.Assert.IsNotNull(fileOperationSubResponse.ErrorCode, "The object 'versioningSubResponse.ErrorCode' should not be null."); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R11146 Site.CaptureRequirementIfAreEqual<string>( "Success", fileOperationSubResponse.ErrorCode, "MS-FSSHTTP", 11109, @"[In FileOperationSubRequestDataType] This parameter [ExclusiveLockID] is used to validate that the file operation can be performed even though the file is under exclusive lock."); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R11120 // This requirement can be captured directly after capturing MS-FSSHTTP_R11109 Site.CaptureRequirement( "MS-FSSHTTP", 11120, @"[In FileOperationSubResponseType] In the case of success, it contains information requested as part of a file operation subrequest."); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R2356 Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(fileOperationSubResponse.ErrorCode, this.Site), "MS-FSSHTTP", 2356, @"[FileOperation SubRequest][The protocol server returns results based on the following conditions:]Otherwise, the protocol server sets the error code value to ""Success"" to indicate success in processing the FileOperation subrequest."); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R2357 Site.CaptureRequirement( "MS-FSSHTTP", 2357, @"[FileOperation SubRequest]If the FileOperation attribute is set to ""Rename"", the protocol server considers the file operation subrequest to be of type ""Rename"". "); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R2358 Site.CaptureRequirement( "MS-FSSHTTP", 2358, @"[FileOperation SubRequest]The protocol server processes this request to request a name change of a file on the server. "); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R11125 Site.CaptureRequirementIfIsNull( fileOperationSubResponse.SubResponseData, "MS-FSSHTTP", 11125, @"[In FileOperationSubResponseType] The SubResponseData element is empty in a SubResponse element of type FileOperationSubRequestType."); } else { Assert.AreEqual<string>( "Success", fileOperationSubResponse.ErrorCode, "MS-FSSHTTP", @"[In FileOperationSubRequestDataType] This parameter [ExclusiveLockID] is used to validate that the file operation can be performed even though the file is under exclusive lock."); } } /// <summary> /// A method used to verify that FileOperation sub-request failed with FileOperation is not specified. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S17_TC02_FileOperation_ErrorCode() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); FileOperationSubRequestType fileOperationSubRequest = new FileOperationSubRequestType(); fileOperationSubRequest.SubRequestToken = SequenceNumberGenerator.GetCurrentToken().ToString(); fileOperationSubRequest.SubRequestData = new FileOperationSubRequestDataType(); fileOperationSubRequest.SubRequestData.FileOperation = FileOperationRequestTypes.Rename; fileOperationSubRequest.SubRequestData.FileOperationSpecified = false; fileOperationSubRequest.SubRequestData.ExclusiveLockID = null; CellStorageResponse cellStoreageResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { fileOperationSubRequest }); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R11267 if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 11267, this.Site)) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R11267 Site.CaptureRequirementIfAreEqual<GenericErrorCodeTypes>( GenericErrorCodeTypes.InvalidArgument, cellStoreageResponse.ResponseVersion.ErrorCode, "MS-FSSHTTP", 11267, @"[In Appendix B: Product Behavior] If the specified attributes[FileOperation] are not provided, the implementation does return error code. &lt;33&gt; Section 2.3.1.33: SharePoint Server 2010 returns an ""InvalidArgument"" error code as part of the SubResponseData element associated with the file operation subresponse(Microsoft Office 2010 suites/Microsoft SharePoint Foundation 2010/Microsoft SharePoint Server 2010/Microsoft SharePoint Workspace 2010 follow this behavior.)"); } // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R11268 if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 11268, this.Site)) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R11268 Site.CaptureRequirementIfAreEqual<GenericErrorCodeTypes>( GenericErrorCodeTypes.HighLevelExceptionThrown, cellStoreageResponse.ResponseVersion.ErrorCode, "MS-FSSHTTP", 11268, @"[In Appendix B: Product Behavior] If the specified attributes[FileOperation] are not provided, the implementation does return error code. &lt;33&gt; Section 2.3.1.33: SharePoint Server 2013 and SharePoint Server 2016, return ""HighLevelExceptionThrown"" error code as part of the SubResponseData element associated with the file operation subresponse(Microsoft SharePoint Foundation 2013/Microsoft SharePoint Server 2013/Microsoft SharePoint Server 2016 follow this behavior)."); } } else { if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 11267, this.Site)) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R11267 Site.Assert.AreEqual<GenericErrorCodeTypes>( GenericErrorCodeTypes.HighLevelExceptionThrown, cellStoreageResponse.ResponseVersion.ErrorCode, @"[In Appendix B: Product Behavior] If the specified attributes[FileOperation attribute] are not provided, the implementation does return an ""InvalidArgument"" error code as part of the SubResponseData element associated with the file opeartion subresponse. (Microsoft Office 2010 suites/Microsoft SharePoint Foundation 2010/Microsoft SharePoint Server 2010/Microsoft SharePoint Workspace 2010/Microsoft Office 2016/Microsoft SharePoint Server 2016/Microsoft Office 2019/Microsoft SharePoint Server 2019 follow this behavior.)"); } } } /// <summary> /// A method used to verify that ResourceID is not changed even if the URL of the file changes. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S17_TC03_ResourceIDNotChanged() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Invoke "GetVersions"sub-request with correct input parameters. GetVersionsSubRequestType getVersionsSubRequest = SharedTestSuiteHelper.CreateGetVersionsSubRequest(SequenceNumberGenerator.GetCurrentToken()); CellStorageResponse cellStoreageResponse = Adapter.CellStorageRequest( this.DefaultFileUrl, new SubRequestType[] { getVersionsSubRequest }, "1", 2, 2, null, null, null, null, null, null, true); GetVersionsSubResponseType getVersionsSubResponse = SharedTestSuiteHelper.ExtractSubResponse<GetVersionsSubResponseType>(cellStoreageResponse, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(getVersionsSubResponse.ErrorCode, this.Site), "GetVersions should be succeed."); VersionType version = cellStoreageResponse.ResponseVersion as VersionType; Site.Assume.AreEqual<ushort>(3, version.MinorVersion, "This test case runs only when MinorVersion is 3 which indicates the protocol server is capable of performing ResourceID specific behavior."); string resourceID = cellStoreageResponse.ResponseCollection.Response[0].ResourceID; // Rename the file string newName = Common.GenerateResourceName(this.Site, "fileName") + ".txt"; FileOperationSubRequestType fileOperationSubRequest = SharedTestSuiteHelper.CreateFileOperationSubRequest(FileOperationRequestTypes.Rename, newName, null, this.Site); cellStoreageResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { fileOperationSubRequest }); FileOperationSubResponseType fileOperationSubResponse = SharedTestSuiteHelper.ExtractSubResponse<FileOperationSubResponseType>(cellStoreageResponse, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(getVersionsSubResponse.ErrorCode, this.Site), "Rename file should be succeed."); this.DefaultFileUrl = this.DefaultFileUrl.Substring(0, this.DefaultFileUrl.LastIndexOf('/') + 1) + newName; cellStoreageResponse = Adapter.CellStorageRequest( this.DefaultFileUrl, new SubRequestType[] { getVersionsSubRequest }, "1", 2, 2, null, null, null, null, null, null, true); getVersionsSubResponse = SharedTestSuiteHelper.ExtractSubResponse<GetVersionsSubResponseType>(cellStoreageResponse, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(getVersionsSubResponse.ErrorCode, this.Site), "GetVersions should be succeed."); string resourceID2 = cellStoreageResponse.ResponseCollection.Response[0].ResourceID; if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R11026 Site.CaptureRequirementIfAreEqual<string>( resourceID, resourceID2, "MS-FSSHTTP", 11026, @"[In Response] [ResourceID] A ResourceID MUST NOT change over the lifetime of a file, even if the URL of the file changes."); } else { Site.Assert.AreEqual<string>( resourceID, resourceID2, "ResourceID MUST NOT change over the lifetime of a file, even if the URL of the file changes."); } } /// <summary> /// A method used to verify that an error when neither of the ResourceID and Url attributes identify valid files. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S17_TC04_ResourceIdDoesNotExist() { string invalidUrl = this.DefaultFileUrl + "Invalid"; // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Invoke "GetVersions"sub-request with correct invalid parameters. GetVersionsSubRequestType getVersionsSubRequest = SharedTestSuiteHelper.CreateGetVersionsSubRequest(SequenceNumberGenerator.GetCurrentToken()); CellStorageResponse cellStoreageResponse = Adapter.CellStorageRequest( invalidUrl, new SubRequestType[] { getVersionsSubRequest }, "1", 2, 2, null, null, null, null, null, "test", true); if (Common.IsRequirementEnabled(11023, this.Site)) { GetVersionsSubResponseType getVersionsSubResponse = SharedTestSuiteHelper.ExtractSubResponse<GetVersionsSubResponseType>(cellStoreageResponse, 0, 0, this.Site); VersionType version = cellStoreageResponse.ResponseVersion as VersionType; Site.Assume.AreEqual<ushort>(3, version.MinorVersion, "This test case runs only when MinorVersion is 3 which indicates the protocol server is capable of performing ResourceID specific behavior."); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R2171 Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.ResourceIdDoesNotExist, SharedTestSuiteHelper.ConvertToErrorCodeType(getVersionsSubResponse.ErrorCode, this.Site), "MS-FSSHTTP", 2171, @"[In GenericErrorCodeTypes] InvalidArgument indicates an error when any of the cell storage service subrequests for the targeted URL for the file contains input parameters that are not valid."); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R11023 Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.ResourceIdDoesNotExist, SharedTestSuiteHelper.ConvertToErrorCodeType(getVersionsSubResponse.ErrorCode, this.Site), "MS-FSSHTTP", 11023, @"[In Request] [UseResourceID]In the case where the protocol server is using the ResourceID attribute but the ResourceID attribute does not identify a valid file the protocol server SHOULD set an error code in the ErrorCode attribute of the corresponding Response attribute."); } else { Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.ResourceIdDoesNotExist, SharedTestSuiteHelper.ConvertToErrorCodeType(getVersionsSubResponse.ErrorCode, this.Site), @"[In GenericErrorCodeTypes] InvalidArgument indicates an error when any of the cell storage service subrequests for the targeted URL for the file contains input parameters that are not valid."); } } } #endregion } }
using System; using System.Linq; using System.Web; using System.Collections.Generic; using System.Security.Cryptography; using System.IO; using System.Text; namespace HttpSignatures { public interface IAuthorizationParser { ISignatureAuthorization Parse(string authorizationHeader); } public class AuthorizationParser : IAuthorizationParser { private List<string> Algorithms = new List<string>(){ "hmac-sha1", "hmac-sha256", "hmac-sha512" }; public ISignatureAuthorization Parse(string authorizationHeader) { var authz = authorizationHeader; var state = State.New; var substate = ParamsState.Name; var parsed = new ParsedAuthorization(); var tmpName = ""; var tmpValue = ""; for (var i = 0; i < authz.Length; i++) { var c = authz[i]; switch (state) { case State.New: if (c != ' ') parsed.Scheme += c; else state = State.Params; break; case State.Params: switch (substate) { case ParamsState.Name: var code = (int)c; // restricted name of A-Z / a-z if ((code >= 0x41 && code <= 0x5a) || // A-Z (code >= 0x61 && code <= 0x7a)) { // a-z tmpName += c; } else if (c == '=') { if (tmpName.Length == 0) throw new InvalidHeaderException("bad param format"); substate = ParamsState.Quote; } else { throw new InvalidHeaderException("bad param format"); } break; case ParamsState.Quote: if (c == '"') { tmpValue = ""; substate = ParamsState.Value; } else { throw new InvalidHeaderException("bad param format"); } break; case ParamsState.Value: if (c == '"') { parsed.Params[tmpName] = tmpValue; substate = ParamsState.Comma; } else { tmpValue += c; } break; case ParamsState.Comma: if (c == ',') { tmpName = ""; substate = ParamsState.Name; } else { throw new InvalidHeaderException("bad param format"); } break; default: throw new Exception("Invalid substate"); } break; default: throw new Exception("Invalid substate"); } } if (string.IsNullOrEmpty(parsed.Params["headers"]) || parsed.Params["headers"] == "") { // if (request.headers['x-date']) { // parsed.params.headers = ['x-date']; // } else { // parsed.params.headers = ['date']; // } parsed.Headers = new string[] { "date" }; } else { parsed.Headers = parsed.Params["headers"].Split(' '); } // Minimally validate the parsed object if (string.IsNullOrEmpty(parsed.Scheme) || parsed.Scheme != "Signature") throw new InvalidHeaderException("scheme was not \"Signature\""); if (string.IsNullOrEmpty(parsed.Params["keyId"])) throw new InvalidHeaderException("keyId was not specified"); if (string.IsNullOrEmpty(parsed.Params["algorithm"])) throw new InvalidHeaderException("algorithm was not specified"); if (string.IsNullOrEmpty(parsed.Params["signature"])) throw new InvalidHeaderException("signature was not specified"); parsed.Params["algorithm"] = parsed.Params["algorithm"].ToLower(); if (!this.Algorithms.Contains(parsed.Params["algorithm"])) { throw new InvalidParamsException(parsed.Params["algorithm"] + " is not supported"); } return new SignatureAuthorization(parsed); } } public class ParsedAuthorization { public ParsedAuthorization() { Scheme = ""; Params = new Dictionary<string, string>(); } public string Scheme { get; set; } public Dictionary<string, string> Params { get; set; } public IEnumerable<string> Headers { get; set; } } public class InvalidHeaderException : InvalidSignatureException { public InvalidHeaderException(string message) : base(message) { } } public class InvalidParamsException : InvalidSignatureException { public InvalidParamsException(string message) : base(message) { } } public enum State { New = 0, Params = 1 }; public enum ParamsState { Name = 0, Quote = 1, Value = 2, Comma = 3 } public interface ISignatureAuthorization : ISignatureSpecification { string Signature { get; } } public class SignatureAuthorization : ISignatureAuthorization { private ParsedAuthorization authorization; public SignatureAuthorization(ParsedAuthorization auth) { this.authorization = auth; } public string Signature { get { return authorization.Params["signature"]; } } public string KeyId { get { return authorization.Params["keyId"]; } } public IEnumerable<string> Headers { get { return authorization.Headers; } } public string Algorithm { get { return authorization.Params["algorithm"]; } } public string HashAlgorithm { get { return Algorithm.Split('-')[1]; } } public string Realm { get { return authorization.Params["realm"]; } } } }
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Android.Accounts; using Android.App; using Android.Content; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows; using Microsoft.Identity.Core; using Microsoft.Identity.Core.Cache; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.OAuth2; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Helpers; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Broker; namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform { [Android.Runtime.Preserve(AllMembers = true)] internal class AndroidBroker : IBroker { private static SemaphoreSlim readyForResponse = null; private static AdalResultWrapper resultEx = null; private readonly AndroidBrokerProxy _brokerProxy; private readonly ICoreLogger _logger; public AndroidBroker(ICoreLogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _brokerProxy = new AndroidBrokerProxy(Application.Context, logger); } public IPlatformParameters PlatformParameters { get; set; } public bool CanInvokeBroker { get { bool canInvoke = WillUseBroker() && _brokerProxy.CanSwitchToBroker(); _logger.Verbose("Can invoke broker? " + canInvoke); return canInvoke; } } public async Task<AdalResultWrapper> AcquireTokenUsingBrokerAsync(IDictionary<string, string> brokerPayload) { resultEx = null; readyForResponse = new SemaphoreSlim(0); try { await Task.Run(() => AcquireTokenInternal(brokerPayload)).ConfigureAwait(false); } catch (Exception ex) { _logger.ErrorPii(ex); throw; } await readyForResponse.WaitAsync().ConfigureAwait(false); return resultEx; } private void AcquireTokenInternal(IDictionary<string, string> brokerPayload) { if (brokerPayload.ContainsKey(BrokerParameter.BrokerInstallUrl)) { _logger.Info("Android Broker - broker payload contains install url"); string url = brokerPayload[BrokerParameter.BrokerInstallUrl]; Uri uri = new Uri(url); string query = uri.Query; if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase)) { query = query.Substring(1); } Dictionary<string, string> keyPair = EncodingHelper.ParseKeyValueList(query, '&', true, false, null); PlatformParameters pp = PlatformParameters as PlatformParameters; var appLink = keyPair["app_link"]; _logger.Info("Android Broker - Starting ActionView activity to " + appLink); pp.CallerActivity.StartActivity(new Intent(Intent.ActionView, Android.Net.Uri.Parse(appLink))); throw new AdalException(AdalErrorAndroidEx.BrokerApplicationRequired, AdalErrorMessageAndroidEx.BrokerApplicationRequired); } Context mContext = Application.Context; AuthenticationRequest request = new AuthenticationRequest(brokerPayload); PlatformParameters platformParams = PlatformParameters as PlatformParameters; // BROKER flow intercepts here // cache and refresh call happens through the authenticator service if (_brokerProxy.VerifyUser(request.LoginHint, request.UserId)) { request.BrokerAccountName = request.LoginHint; _logger.InfoPii( "It switched to broker for context: " + mContext.PackageName + " login hint: " + request.BrokerAccountName, "It switched to broker for context"); // Don't send background request, if prompt flag is always or // refresh_session bool hasAccountNameOrUserId = !string.IsNullOrEmpty(request.BrokerAccountName) || !string.IsNullOrEmpty(request.UserId); if (string.IsNullOrEmpty(request.Claims) && hasAccountNameOrUserId) { _logger.Verbose("User is specified for background token request"); resultEx = _brokerProxy.GetAuthTokenInBackground(request, platformParams.CallerActivity); } else { _logger.Verbose("User is not specified for background token request"); } if (resultEx != null && resultEx.Result != null && !string.IsNullOrEmpty(resultEx.Result.AccessToken)) { _logger.Verbose("Token is returned from background call"); readyForResponse.Release(); return; } // Launch broker activity // if cache and refresh request is not handled. // Initial request to authenticator needs to launch activity to // record calling uid for the account. This happens for Prompt auto // or always behavior. _logger.Verbose("Token is not returned from backgroud call"); // Only happens with callback since silent call does not show UI _logger.Verbose("Launch activity for Authenticator"); _logger.Verbose("Starting Authentication Activity"); if (resultEx == null) { _logger.Verbose("Initial request to authenticator"); // Log the initial request but not force a prompt } if (brokerPayload.ContainsKey(BrokerParameter.SilentBrokerFlow)) { _logger.Error("Can't invoke the broker in interactive mode because this is a silent flow"); throw new AdalSilentTokenAcquisitionException(); } // onActivityResult will receive the response // Activity needs to launch to record calling app for this // account Intent brokerIntent = _brokerProxy.GetIntentForBrokerActivity(request, platformParams.CallerActivity); if (brokerIntent != null) { try { _logger.Verbose( "Calling activity pid:" + Android.OS.Process.MyPid() + " tid:" + Android.OS.Process.MyTid() + "uid:" + Android.OS.Process.MyUid()); platformParams.CallerActivity.StartActivityForResult(brokerIntent, 1001); } catch (ActivityNotFoundException e) { _logger.ErrorPii(e); } } } else { throw new AdalException(AdalErrorAndroidEx.NoBrokerAccountFound, "Add requested account as a Workplace account via Settings->Accounts or set UseBroker=true."); } } internal static void SetBrokerResult(Intent data, int resultCode) { if (resultCode != BrokerResponseCode.ResponseReceived) { resultEx = new AdalResultWrapper { Exception = new AdalException(data.GetStringExtra(BrokerConstants.ResponseErrorCode), data.GetStringExtra(BrokerConstants.ResponseErrorMessage)) }; } else { var tokenResponse = new TokenResponse { Authority = data.GetStringExtra(BrokerConstants.AccountAuthority), AccessToken = data.GetStringExtra(BrokerConstants.AccountAccessToken), IdTokenString = data.GetStringExtra(BrokerConstants.AccountIdToken), TokenType = "Bearer", ExpiresOn = data.GetLongExtra(BrokerConstants.AccountExpireDate, 0) }; resultEx = tokenResponse.GetResult(AndroidBrokerProxy.ConvertFromTimeT(tokenResponse.ExpiresOn), AndroidBrokerProxy.ConvertFromTimeT(tokenResponse.ExpiresOn)); } readyForResponse.Release(); } private bool WillUseBroker() { PlatformParameters pp = PlatformParameters as PlatformParameters; bool useBroker = pp?.UseBroker ?? false; _logger.Verbose("Is Android Broker use configured via PlatformParamters? " + useBroker); return useBroker; } } }
// Odp.Net Data Provider. // http://www.oracle.com/technology/tech/windows/odpnet/index.html // using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using BLToolkit.Aspects; using BLToolkit.Common; using BLToolkit.Mapping; using BLToolkit.Reflection; using Oracle.DataAccess.Client; using Oracle.DataAccess.Types; namespace BLToolkit.Data.DataProvider { using Sql.SqlProvider; /// <summary> /// Implements access to the Data Provider for Oracle. /// </summary> /// <remarks> /// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example. /// </remarks> /// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataManager Method</seealso> public class OdpDataProvider : DataProviderBase { public OdpDataProvider() { MappingSchema = new OdpMappingSchema(); } static OdpDataProvider() { // Fix Oracle.Net bug #1: Array types are not handled. // var oraDbDbTypeTableType = typeof(OracleParameter).Assembly.GetType("Oracle.DataAccess.Client.OraDb_DbTypeTable"); if (null != oraDbDbTypeTableType) { var typeTable = (Hashtable)oraDbDbTypeTableType.InvokeMember( "s_table", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.GetField, null, null, Type.EmptyTypes); if (null != typeTable) { typeTable[typeof(DateTime[])] = OracleDbType.TimeStamp; typeTable[typeof(Int16[])] = OracleDbType.Int16; typeTable[typeof(Int32[])] = OracleDbType.Int32; typeTable[typeof(Int64[])] = OracleDbType.Int64; typeTable[typeof(Single[])] = OracleDbType.Single; typeTable[typeof(Double[])] = OracleDbType.Double; typeTable[typeof(Decimal[])] = OracleDbType.Decimal; typeTable[typeof(TimeSpan[])] = OracleDbType.IntervalDS; typeTable[typeof(String[])] = OracleDbType.Varchar2; typeTable[typeof(OracleBFile[])] = OracleDbType.BFile; typeTable[typeof(OracleBinary[])] = OracleDbType.Raw; typeTable[typeof(OracleBlob[])] = OracleDbType.Blob; typeTable[typeof(OracleClob[])] = OracleDbType.Clob; typeTable[typeof(OracleDate[])] = OracleDbType.Date; typeTable[typeof(OracleDecimal[])] = OracleDbType.Decimal; typeTable[typeof(OracleIntervalDS[])] = OracleDbType.IntervalDS; typeTable[typeof(OracleIntervalYM[])] = OracleDbType.IntervalYM; typeTable[typeof(OracleRefCursor[])] = OracleDbType.RefCursor; typeTable[typeof(OracleString[])] = OracleDbType.Varchar2; typeTable[typeof(OracleTimeStamp[])] = OracleDbType.TimeStamp; typeTable[typeof(OracleTimeStampLTZ[])]= OracleDbType.TimeStampLTZ; typeTable[typeof(OracleTimeStampTZ[])] = OracleDbType.TimeStampTZ; typeTable[typeof(OracleXmlType[])] = OracleDbType.XmlType; typeTable[typeof(Boolean)] = OracleDbType.Byte; typeTable[typeof(Guid)] = OracleDbType.Raw; typeTable[typeof(SByte)] = OracleDbType.Decimal; typeTable[typeof(UInt16)] = OracleDbType.Decimal; typeTable[typeof(UInt32)] = OracleDbType.Decimal; typeTable[typeof(UInt64)] = OracleDbType.Decimal; typeTable[typeof(Boolean[])] = OracleDbType.Byte; typeTable[typeof(Guid[])] = OracleDbType.Raw; typeTable[typeof(SByte[])] = OracleDbType.Decimal; typeTable[typeof(UInt16[])] = OracleDbType.Decimal; typeTable[typeof(UInt32[])] = OracleDbType.Decimal; typeTable[typeof(UInt64[])] = OracleDbType.Decimal; typeTable[typeof(Boolean?)] = OracleDbType.Byte; typeTable[typeof(Guid?)] = OracleDbType.Raw; typeTable[typeof(SByte?)] = OracleDbType.Decimal; typeTable[typeof(UInt16?)] = OracleDbType.Decimal; typeTable[typeof(UInt32?)] = OracleDbType.Decimal; typeTable[typeof(UInt64?)] = OracleDbType.Decimal; typeTable[typeof(DateTime?[])] = OracleDbType.TimeStamp; typeTable[typeof(Int16?[])] = OracleDbType.Int16; typeTable[typeof(Int32?[])] = OracleDbType.Int32; typeTable[typeof(Int64?[])] = OracleDbType.Int64; typeTable[typeof(Single?[])] = OracleDbType.Single; typeTable[typeof(Double?[])] = OracleDbType.Double; typeTable[typeof(Decimal?[])] = OracleDbType.Decimal; typeTable[typeof(TimeSpan?[])] = OracleDbType.IntervalDS; typeTable[typeof(Boolean?[])] = OracleDbType.Byte; typeTable[typeof(Guid?[])] = OracleDbType.Raw; typeTable[typeof(SByte?[])] = OracleDbType.Decimal; typeTable[typeof(UInt16?[])] = OracleDbType.Decimal; typeTable[typeof(UInt32?[])] = OracleDbType.Decimal; typeTable[typeof(UInt64?[])] = OracleDbType.Decimal; typeTable[typeof(XmlReader)] = OracleDbType.XmlType; typeTable[typeof(XmlDocument)] = OracleDbType.XmlType; typeTable[typeof(MemoryStream)] = OracleDbType.Blob; typeTable[typeof(XmlReader[])] = OracleDbType.XmlType; typeTable[typeof(XmlDocument[])] = OracleDbType.XmlType; typeTable[typeof(MemoryStream[])] = OracleDbType.Blob; } } } /// <summary> /// Creates the database connection object. /// </summary> /// <remarks> /// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example. /// </remarks> /// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataManager Method</seealso> /// <returns>The database connection object.</returns> public override IDbConnection CreateConnectionObject() { return new OracleConnection(); } public override IDbCommand CreateCommandObject(IDbConnection connection) { var oraConnection = connection as OracleConnection; if (null != oraConnection) { var oraCommand = oraConnection.CreateCommand(); // Fix Oracle.Net bug #2: Empty arrays can not be sent to the server. // oraCommand.BindByName = true; return oraCommand; } return base.CreateCommandObject(connection); } public override IDbDataParameter CloneParameter(IDbDataParameter parameter) { var oraParameter = (parameter is OracleParameterWrap)? (parameter as OracleParameterWrap).OracleParameter: parameter as OracleParameter; if (null != oraParameter) { var oraParameterClone = (OracleParameter)oraParameter.Clone(); // Fix Oracle.Net bug #3: CollectionType property is not cloned. // oraParameterClone.CollectionType = oraParameter.CollectionType; // Fix Oracle.Net bug #8423178 // See http://forums.oracle.com/forums/thread.jspa?threadID=975902&tstart=0 // if (oraParameterClone.OracleDbType == OracleDbType.RefCursor) { // Set OracleDbType to itself to reset m_bSetDbType and m_bOracleDbTypeExSet // oraParameterClone.OracleDbType = OracleDbType.RefCursor; } return OracleParameterWrap.CreateInstance(oraParameterClone); } return base.CloneParameter(parameter); } public override void SetUserDefinedType(IDbDataParameter parameter, string typeName) { var oraParameter = (parameter is OracleParameterWrap) ? (parameter as OracleParameterWrap).OracleParameter : parameter as OracleParameter; if (oraParameter == null) throw new ArgumentException("OracleParameter expected.", "parameter"); oraParameter.UdtTypeName = typeName; } /// <summary> /// Creates the data adapter object. /// </summary> /// <remarks> /// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example. /// </remarks> /// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataManager Method</seealso> /// <returns>A data adapter object.</returns> public override DbDataAdapter CreateDataAdapterObject() { return new OracleDataAdapter(); } /// <summary> /// Populates the specified IDbCommand object's Parameters collection with /// parameter information for the stored procedure specified in the IDbCommand. /// </summary> /// <remarks> /// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example. /// </remarks> /// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataManager Method</seealso> /// <param name="command">The IDbCommand referencing the stored procedure for which the parameter /// information is to be derived. The derived parameters will be populated into /// the Parameters of this command.</param> public override bool DeriveParameters(IDbCommand command) { var oraCommand = command as OracleCommand; if (null != oraCommand) { try { OracleCommandBuilder.DeriveParameters(oraCommand); } catch (Exception ex) { // Make Oracle less laconic. // throw new DataException(string.Format("{0}\nCommandText: {1}", ex.Message, oraCommand.CommandText), ex); } return true; } return false; } public override object Convert(object value, ConvertType convertType) { switch (convertType) { case ConvertType.NameToCommandParameter: case ConvertType.NameToSprocParameter: return ParameterPrefix == null? value: ParameterPrefix + value; case ConvertType.SprocParameterToName: var name = (string)value; if (name.Length > 0) { if (name[0] == ':') return name.Substring(1); if (ParameterPrefix != null && name.ToUpper(CultureInfo.InvariantCulture).StartsWith(ParameterPrefix)) { return name.Substring(ParameterPrefix.Length); } } break; case ConvertType.ExceptionToErrorNumber: if (value is OracleException) return ((OracleException)value).Number; break; } return SqlProvider.Convert(value, convertType); } public override void PrepareCommand(ref CommandType commandType, ref string commandText, ref IDbDataParameter[] commandParameters) { base.PrepareCommand(ref commandType, ref commandText, ref commandParameters); if (commandType == CommandType.Text) { // Fix Oracle bug #11 '\r' is not a valid character! // commandText = commandText.Replace('\r', ' '); } } public override void AttachParameter(IDbCommand command, IDbDataParameter parameter) { var oraParameter = (parameter is OracleParameterWrap)? (parameter as OracleParameterWrap).OracleParameter: parameter as OracleParameter; if (null != oraParameter) { if (oraParameter.CollectionType == OracleCollectionType.PLSQLAssociativeArray) { if (oraParameter.Direction == ParameterDirection.Input || oraParameter.Direction == ParameterDirection.InputOutput) { var ar = oraParameter.Value as Array; if (null != ar && !(ar is byte[] || ar is char[])) { oraParameter.Size = ar.Length; if (oraParameter.DbType == DbType.String && oraParameter.Direction == ParameterDirection.InputOutput) { var arrayBindSize = new int[oraParameter.Size]; for (var i = 0; i < oraParameter.Size; ++i) { arrayBindSize[i] = 1024; } oraParameter.ArrayBindSize = arrayBindSize; } } if (oraParameter.Size == 0) { // Skip this parameter. // Fix Oracle.Net bug #2: Empty arrays can not be sent to the server. // return; } if (oraParameter.Value is Stream[]) { var streams = (Stream[]) oraParameter.Value; for (var i = 0; i < oraParameter.Size; ++i) { if (streams[i] is OracleBFile || streams[i] is OracleBlob || streams[i] is OracleClob || streams[i] is OracleXmlStream) { // Known Oracle type. // continue; } streams[i] = CopyStream(streams[i], (OracleCommand)command); } } else if (oraParameter.Value is XmlDocument[]) { var xmlDocuments = (XmlDocument[]) oraParameter.Value; var values = new object[oraParameter.Size]; switch (oraParameter.OracleDbType) { case OracleDbType.XmlType: for (var i = 0; i < oraParameter.Size; ++i) { values[i] = xmlDocuments[i].DocumentElement == null? (object) DBNull.Value: new OracleXmlType((OracleConnection)command.Connection, xmlDocuments[i]); } oraParameter.Value = values; break; // Fix Oracle.Net bug #9: XmlDocument.ToString() returns System.Xml.XmlDocument, // so m_value.ToString() is not enought. // case OracleDbType.Clob: case OracleDbType.NClob: case OracleDbType.Varchar2: case OracleDbType.NVarchar2: case OracleDbType.Char: case OracleDbType.NChar: for (var i = 0; i < oraParameter.Size; ++i) { values[i] = xmlDocuments[i].DocumentElement == null? (object) DBNull.Value: xmlDocuments[i].InnerXml; } oraParameter.Value = values; break; // Or convert to bytes if need. // case OracleDbType.Blob: case OracleDbType.BFile: case OracleDbType.Raw: case OracleDbType.Long: case OracleDbType.LongRaw: for (var i = 0; i < oraParameter.Size; ++i) { if (xmlDocuments[i].DocumentElement == null) values[i] = DBNull.Value; else using (var s = new MemoryStream()) { xmlDocuments[i].Save(s); values[i] = s.GetBuffer(); } } oraParameter.Value = values; break; } } } else if (oraParameter.Direction == ParameterDirection.Output) { // Fix Oracle.Net bug #4: ArrayBindSize must be explicitly specified. // if (oraParameter.DbType == DbType.String) { oraParameter.Size = 1024; var arrayBindSize = new int[oraParameter.Size]; for (var i = 0; i < oraParameter.Size; ++i) { arrayBindSize[i] = 1024; } oraParameter.ArrayBindSize = arrayBindSize; } else { oraParameter.Size = 32767; } } } else if (oraParameter.Value is Stream) { var stream = (Stream) oraParameter.Value; if (!(stream is OracleBFile) && !(stream is OracleBlob) && !(stream is OracleClob) && !(stream is OracleXmlStream)) { oraParameter.Value = CopyStream(stream, (OracleCommand)command); } } else if (oraParameter.Value is Byte[]) { var bytes = (Byte[]) oraParameter.Value; if (bytes.Length > 32000) { oraParameter.Value = CopyStream(bytes, (OracleCommand)command); } } else if (oraParameter.Value is XmlDocument) { var xmlDocument = (XmlDocument)oraParameter.Value; if (xmlDocument.DocumentElement == null) oraParameter.Value = DBNull.Value; else { switch (oraParameter.OracleDbType) { case OracleDbType.XmlType: oraParameter.Value = new OracleXmlType((OracleConnection)command.Connection, xmlDocument); break; // Fix Oracle.Net bug #9: XmlDocument.ToString() returns System.Xml.XmlDocument, // so m_value.ToString() is not enought. // case OracleDbType.Clob: case OracleDbType.NClob: case OracleDbType.Varchar2: case OracleDbType.NVarchar2: case OracleDbType.Char: case OracleDbType.NChar: using (TextWriter w = new StringWriter()) { xmlDocument.Save(w); oraParameter.Value = w.ToString(); } break; // Or convert to bytes if need. // case OracleDbType.Blob: case OracleDbType.BFile: case OracleDbType.Raw: case OracleDbType.Long: case OracleDbType.LongRaw: using (var s = new MemoryStream()) { xmlDocument.Save(s); oraParameter.Value = s.GetBuffer(); } break; } } } parameter = oraParameter; } base.AttachParameter(command, parameter); } private static Stream CopyStream(Stream stream, OracleCommand cmd) { return CopyStream(Common.Convert.ToByteArray(stream), cmd); } private static Stream CopyStream(Byte[] bytes, OracleCommand cmd) { var ret = new OracleBlob(cmd.Connection); ret.Write(bytes, 0, bytes.Length); return ret; } public override bool IsValueParameter(IDbDataParameter parameter) { var oraParameter = (parameter is OracleParameterWrap)? (parameter as OracleParameterWrap).OracleParameter: parameter as OracleParameter; if (null != oraParameter) { if (oraParameter.OracleDbType == OracleDbType.RefCursor && oraParameter.Direction == ParameterDirection.Output) { // Ignore out ref cursors, while out parameters of other types are o.k. return false; } } return base.IsValueParameter(parameter); } public override IDbDataParameter CreateParameterObject(IDbCommand command) { var parameter = base.CreateParameterObject(command); if (parameter is OracleParameter) parameter = OracleParameterWrap.CreateInstance(parameter as OracleParameter); return parameter; } public override IDbDataParameter GetParameter(IDbCommand command, NameOrIndexParameter nameOrIndex) { var parameter = base.GetParameter(command, nameOrIndex); if (parameter is OracleParameter) parameter = OracleParameterWrap.CreateInstance(parameter as OracleParameter); return parameter; } /// <summary> /// Returns connection type. /// </summary> /// <remarks> /// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example. /// </remarks> /// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataManager Method</seealso> /// <value>An instance of the <see cref="Type"/> class.</value> public override Type ConnectionType { get { return typeof(OracleConnection); } } public const string NameString = DataProvider.ProviderName.Oracle; /// <summary> /// Returns the data provider name. /// </summary> /// <remarks> /// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example. /// </remarks> /// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataProvider Method</seealso> /// <value>Data provider name.</value> public override string Name { get { return NameString; } } public override int MaxBatchSize { get { return 0; } } public override ISqlProvider CreateSqlProvider() { return new OracleSqlProvider(); } public override IDataReader GetDataReader(MappingSchema schema, IDataReader dataReader) { return dataReader is OracleDataReader ? new OracleDataReaderEx((OracleDataReader)dataReader) : base.GetDataReader(schema, dataReader); } class OracleDataReaderEx: DataReaderEx<OracleDataReader> { public OracleDataReaderEx(OracleDataReader rd) : base(rd) { } public override DateTimeOffset GetDateTimeOffset(int i) { var ts = DataReader.GetOracleTimeStampTZ(i); return new DateTimeOffset(ts.Value, ts.GetTimeZoneOffset()); } } private string _parameterPrefix = "P"; public string ParameterPrefix { get { return _parameterPrefix; } set { _parameterPrefix = string.IsNullOrEmpty(value)? null: value.ToUpper(CultureInfo.InvariantCulture); } } /// <summary> /// One time initialization from a configuration file. /// </summary> /// <param name="attributes">Provider specific attributes.</param> public override void Configure(System.Collections.Specialized.NameValueCollection attributes) { var val = attributes["ParameterPrefix"]; if (val != null) ParameterPrefix = val; base.Configure(attributes); } #region Inner types public class OdpMappingSchema : MappingSchema { public override DataReaderMapper CreateDataReaderMapper(IDataReader dataReader) { return new OracleDataReaderMapper(this, dataReader); } public override DataReaderMapper CreateDataReaderMapper( IDataReader dataReader, NameOrIndexParameter nip) { return new OracleScalarDataReaderMapper(this, dataReader, nip); } #region Convert #region Primitive Types [CLSCompliant(false)] public override SByte ConvertToSByte(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultSByteNullValue: (SByte)oraDecimal.Value; } return base.ConvertToSByte(value); } public override Int16 ConvertToInt16(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultInt16NullValue: oraDecimal.ToInt16(); } return base.ConvertToInt16(value); } public override Int32 ConvertToInt32(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultInt32NullValue: oraDecimal.ToInt32(); } return base.ConvertToInt32(value); } public override Int64 ConvertToInt64(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultInt64NullValue: oraDecimal.ToInt64(); } return base.ConvertToInt64(value); } public override Byte ConvertToByte(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultByteNullValue: oraDecimal.ToByte(); } return base.ConvertToByte(value); } [CLSCompliant(false)] public override UInt16 ConvertToUInt16(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultUInt16NullValue: (UInt16)oraDecimal.Value; } return base.ConvertToUInt16(value); } [CLSCompliant(false)] public override UInt32 ConvertToUInt32(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultUInt32NullValue: (UInt32)oraDecimal.Value; } return base.ConvertToUInt32(value); } [CLSCompliant(false)] public override UInt64 ConvertToUInt64(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultUInt64NullValue: (UInt64)oraDecimal.Value; } return base.ConvertToUInt64(value); } public override Single ConvertToSingle(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultSingleNullValue: oraDecimal.ToSingle(); } return base.ConvertToSingle(value); } public override Double ConvertToDouble(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultDoubleNullValue: oraDecimal.ToDouble(); } return base.ConvertToDouble(value); } public override Boolean ConvertToBoolean(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultBooleanNullValue: (oraDecimal.Value != 0); } return base.ConvertToBoolean(value); } public override DateTime ConvertToDateTime(object value) { if (value is OracleDate) { var oraDate = (OracleDate)value; return oraDate.IsNull? DefaultDateTimeNullValue: oraDate.Value; } return base.ConvertToDateTime(value); } public override Decimal ConvertToDecimal(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? DefaultDecimalNullValue: oraDecimal.Value; } return base.ConvertToDecimal(value); } public override Guid ConvertToGuid(object value) { if (value is OracleString) { var oraString = (OracleString)value; return oraString.IsNull? DefaultGuidNullValue: new Guid(oraString.Value); } if (value is OracleBlob) { var oraBlob = (OracleBlob)value; return oraBlob.IsNull? DefaultGuidNullValue: new Guid(oraBlob.Value); } return base.ConvertToGuid(value); } public override String ConvertToString(object value) { if (value is OracleString) { var oraString = (OracleString)value; return oraString.IsNull? DefaultStringNullValue: oraString.Value; } if (value is OracleXmlType) { var oraXmlType = (OracleXmlType)value; return oraXmlType.IsNull ? DefaultStringNullValue : oraXmlType.Value; } if (value is OracleClob) { var oraClob = (OracleClob)value; return oraClob.IsNull? DefaultStringNullValue: oraClob.Value; } return base.ConvertToString(value); } public override Stream ConvertToStream(object value) { if (value is OracleXmlType) { var oraXml = (OracleXmlType)value; return oraXml.IsNull? DefaultStreamNullValue: oraXml.GetStream(); } return base.ConvertToStream(value); } public override XmlReader ConvertToXmlReader(object value) { if (value is OracleXmlType) { var oraXml = (OracleXmlType)value; return oraXml.IsNull? DefaultXmlReaderNullValue: oraXml.GetXmlReader(); } return base.ConvertToXmlReader(value); } public override XmlDocument ConvertToXmlDocument(object value) { if (value is OracleXmlType) { var oraXml = (OracleXmlType)value; return oraXml.IsNull? DefaultXmlDocumentNullValue: oraXml.GetXmlDocument(); } return base.ConvertToXmlDocument(value); } public override Byte[] ConvertToByteArray(object value) { if (value is OracleBlob) { var oraBlob = (OracleBlob)value; return oraBlob.IsNull? null: oraBlob.Value; } if (value is OracleBinary) { var oraBinary = (OracleBinary)value; return oraBinary.IsNull? null: oraBinary.Value; } if (value is OracleBFile) { var oraBFile = (OracleBFile)value; return oraBFile.IsNull? null: oraBFile.Value; } return base.ConvertToByteArray(value); } public override Char[] ConvertToCharArray(object value) { if (value is OracleString) { var oraString = (OracleString)value; return oraString.IsNull? null: oraString.Value.ToCharArray(); } if (value is OracleClob) { var oraClob = (OracleClob)value; return oraClob.IsNull? null: oraClob.Value.ToCharArray(); } return base.ConvertToCharArray(value); } #endregion #region Nullable Types [CLSCompliant(false)] public override SByte? ConvertToNullableSByte(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (SByte?)oraDecimal.Value; } return base.ConvertToNullableSByte(value); } public override Int16? ConvertToNullableInt16(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (Int16?)oraDecimal.ToInt16(); } return base.ConvertToNullableInt16(value); } public override Int32? ConvertToNullableInt32(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (Int32?)oraDecimal.ToInt32(); } return base.ConvertToNullableInt32(value); } public override Int64? ConvertToNullableInt64(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (Int64?)oraDecimal.ToInt64(); } return base.ConvertToNullableInt64(value); } public override Byte? ConvertToNullableByte(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (Byte?)oraDecimal.ToByte(); } return base.ConvertToNullableByte(value); } [CLSCompliant(false)] public override UInt16? ConvertToNullableUInt16(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (UInt16?)oraDecimal.Value; } return base.ConvertToNullableUInt16(value); } [CLSCompliant(false)] public override UInt32? ConvertToNullableUInt32(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (UInt32?)oraDecimal.Value; } return base.ConvertToNullableUInt32(value); } [CLSCompliant(false)] public override UInt64? ConvertToNullableUInt64(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (UInt64?)oraDecimal.Value; } return base.ConvertToNullableUInt64(value); } public override Single? ConvertToNullableSingle(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (Single?)oraDecimal.ToSingle(); } return base.ConvertToNullableSingle(value); } public override Double? ConvertToNullableDouble(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (Double?)oraDecimal.ToDouble(); } return base.ConvertToNullableDouble(value); } public override Boolean? ConvertToNullableBoolean(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (Boolean?)(oraDecimal.Value != 0); } return base.ConvertToNullableBoolean(value); } public override DateTime? ConvertToNullableDateTime(object value) { if (value is OracleDate) { var oraDate = (OracleDate)value; return oraDate.IsNull? null: (DateTime?)oraDate.Value; } return base.ConvertToNullableDateTime(value); } public override Decimal? ConvertToNullableDecimal(object value) { if (value is OracleDecimal) { var oraDecimal = (OracleDecimal)value; return oraDecimal.IsNull? null: (Decimal?)oraDecimal.Value; } return base.ConvertToNullableDecimal(value); } public override Guid? ConvertToNullableGuid(object value) { if (value is OracleString) { var oraString = (OracleString)value; return oraString.IsNull? null: (Guid?)new Guid(oraString.Value); } if (value is OracleBlob) { var oraBlob = (OracleBlob)value; return oraBlob.IsNull? null: (Guid?)new Guid(oraBlob.Value); } return base.ConvertToNullableGuid(value); } #endregion #endregion public override object MapValueToEnum(object value, Type type) { if (value is OracleString) { var oracleValue = (OracleString)value; value = oracleValue.IsNull? null: oracleValue.Value; } else if (value is OracleDecimal) { var oracleValue = (OracleDecimal)value; if (oracleValue.IsNull) value = null; else value = oracleValue.Value; } return base.MapValueToEnum(value, type); } public override object ConvertChangeType(object value, Type conversionType) { // Handle OracleDecimal with IsNull == true case // return base.ConvertChangeType(IsNull(value)? null: value, conversionType); } public override bool IsNull(object value) { // ODP 10 does not expose this interface to public. // // return value is INullable && ((INullable)value).IsNull; return value is OracleDecimal? ((OracleDecimal) value).IsNull: value is OracleString? ((OracleString) value).IsNull: value is OracleDate? ((OracleDate) value).IsNull: value is OracleTimeStamp? ((OracleTimeStamp) value).IsNull: value is OracleTimeStampTZ? ((OracleTimeStampTZ) value).IsNull: value is OracleTimeStampLTZ? ((OracleTimeStampLTZ)value).IsNull: value is OracleXmlType? ((OracleXmlType) value).IsNull: value is OracleBlob? ((OracleBlob) value).IsNull: value is OracleClob? ((OracleClob) value).IsNull: value is OracleBFile? ((OracleBFile) value).IsNull: value is OracleBinary? ((OracleBinary) value).IsNull: value is OracleIntervalDS? ((OracleIntervalDS) value).IsNull: value is OracleIntervalYM? ((OracleIntervalYM) value).IsNull: base.IsNull(value); } } // TODO: implement via IDataReaderEx / DataReaderEx // public class OracleDataReaderMapper : DataReaderMapper { public OracleDataReaderMapper(MappingSchema mappingSchema, IDataReader dataReader) : base(mappingSchema, dataReader) { _dataReader = dataReader is OracleDataReaderEx? ((OracleDataReaderEx)dataReader).DataReader: (OracleDataReader)dataReader; } private readonly OracleDataReader _dataReader; public override Type GetFieldType(int index) { var fieldType = _dataReader.GetProviderSpecificFieldType(index); if (fieldType != typeof(OracleXmlType) && fieldType != typeof(OracleBlob)) fieldType = _dataReader.GetFieldType(index); return fieldType; } public override object GetValue(object o, int index) { var fieldType = _dataReader.GetProviderSpecificFieldType(index); if (fieldType == typeof(OracleXmlType)) { var xml = _dataReader.GetOracleXmlType(index); return MappingSchema.ConvertToXmlDocument(xml); } if (fieldType == typeof(OracleBlob)) { var blob = _dataReader.GetOracleBlob(index); return MappingSchema.ConvertToStream(blob); } return _dataReader.IsDBNull(index)? null: _dataReader.GetValue(index); } public override Boolean GetBoolean(object o, int index) { return MappingSchema.ConvertToBoolean(GetValue(o, index)); } public override Char GetChar (object o, int index) { return MappingSchema.ConvertToChar (GetValue(o, index)); } public override Guid GetGuid (object o, int index) { return MappingSchema.ConvertToGuid (GetValue(o, index)); } [CLSCompliant(false)] public override SByte GetSByte (object o, int index) { return (SByte)_dataReader.GetDecimal(index); } [CLSCompliant(false)] public override UInt16 GetUInt16 (object o, int index) { return (UInt16)_dataReader.GetDecimal(index); } [CLSCompliant(false)] public override UInt32 GetUInt32 (object o, int index) { return (UInt32)_dataReader.GetDecimal(index); } [CLSCompliant(false)] public override UInt64 GetUInt64 (object o, int index) { return (UInt64)_dataReader.GetDecimal(index); } public override Decimal GetDecimal(object o, int index) { return OracleDecimal.SetPrecision(_dataReader.GetOracleDecimal(index), 28).Value; } public override Boolean? GetNullableBoolean(object o, int index) { return MappingSchema.ConvertToNullableBoolean(GetValue(o, index)); } public override Char? GetNullableChar (object o, int index) { return MappingSchema.ConvertToNullableChar (GetValue(o, index)); } public override Guid? GetNullableGuid (object o, int index) { return MappingSchema.ConvertToNullableGuid (GetValue(o, index)); } [CLSCompliant(false)] public override SByte? GetNullableSByte (object o, int index) { return _dataReader.IsDBNull(index)? null: (SByte?)_dataReader.GetDecimal(index); } [CLSCompliant(false)] public override UInt16? GetNullableUInt16 (object o, int index) { return _dataReader.IsDBNull(index)? null: (UInt16?)_dataReader.GetDecimal(index); } [CLSCompliant(false)] public override UInt32? GetNullableUInt32 (object o, int index) { return _dataReader.IsDBNull(index)? null: (UInt32?)_dataReader.GetDecimal(index); } [CLSCompliant(false)] public override UInt64? GetNullableUInt64 (object o, int index) { return _dataReader.IsDBNull(index)? null: (UInt64?)_dataReader.GetDecimal(index); } public override Decimal? GetNullableDecimal(object o, int index) { return _dataReader.IsDBNull(index)? (decimal?)null: OracleDecimal.SetPrecision(_dataReader.GetOracleDecimal(index), 28).Value; } } public class OracleScalarDataReaderMapper : ScalarDataReaderMapper { private readonly OracleDataReader _dataReader; public OracleScalarDataReaderMapper( MappingSchema mappingSchema, IDataReader dataReader, NameOrIndexParameter nameOrIndex) : base(mappingSchema, dataReader, nameOrIndex) { _dataReader = dataReader is OracleDataReaderEx? ((OracleDataReaderEx)dataReader).DataReader: (OracleDataReader)dataReader; _fieldType = _dataReader.GetProviderSpecificFieldType(Index); if (_fieldType != typeof(OracleXmlType) && _fieldType != typeof(OracleBlob)) _fieldType = _dataReader.GetFieldType(Index); } private readonly Type _fieldType; public override Type GetFieldType(int index) { return _fieldType; } public override object GetValue(object o, int index) { if (_fieldType == typeof(OracleXmlType)) { var xml = _dataReader.GetOracleXmlType(Index); return MappingSchema.ConvertToXmlDocument(xml); } if (_fieldType == typeof(OracleBlob)) { var blob = _dataReader.GetOracleBlob(Index); return MappingSchema.ConvertToStream(blob); } return _dataReader.IsDBNull(index)? null: _dataReader.GetValue(Index); } public override Boolean GetBoolean(object o, int index) { return MappingSchema.ConvertToBoolean(GetValue(o, Index)); } public override Char GetChar (object o, int index) { return MappingSchema.ConvertToChar (GetValue(o, Index)); } public override Guid GetGuid (object o, int index) { return MappingSchema.ConvertToGuid (GetValue(o, Index)); } [CLSCompliant(false)] public override SByte GetSByte (object o, int index) { return (SByte)_dataReader.GetDecimal(Index); } [CLSCompliant(false)] public override UInt16 GetUInt16 (object o, int index) { return (UInt16)_dataReader.GetDecimal(Index); } [CLSCompliant(false)] public override UInt32 GetUInt32 (object o, int index) { return (UInt32)_dataReader.GetDecimal(Index); } [CLSCompliant(false)] public override UInt64 GetUInt64 (object o, int index) { return (UInt64)_dataReader.GetDecimal(Index); } public override Decimal GetDecimal(object o, int index) { return OracleDecimal.SetPrecision(_dataReader.GetOracleDecimal(Index), 28).Value; } public override Boolean? GetNullableBoolean(object o, int index) { return MappingSchema.ConvertToNullableBoolean(GetValue(o, Index)); } public override Char? GetNullableChar (object o, int index) { return MappingSchema.ConvertToNullableChar (GetValue(o, Index)); } public override Guid? GetNullableGuid (object o, int index) { return MappingSchema.ConvertToNullableGuid (GetValue(o, Index)); } [CLSCompliant(false)] public override SByte? GetNullableSByte (object o, int index) { return _dataReader.IsDBNull(index)? null: (SByte?)_dataReader.GetDecimal(Index); } [CLSCompliant(false)] public override UInt16? GetNullableUInt16 (object o, int index) { return _dataReader.IsDBNull(index)? null: (UInt16?)_dataReader.GetDecimal(Index); } [CLSCompliant(false)] public override UInt32? GetNullableUInt32 (object o, int index) { return _dataReader.IsDBNull(index)? null: (UInt32?)_dataReader.GetDecimal(Index); } [CLSCompliant(false)] public override UInt64? GetNullableUInt64 (object o, int index) { return _dataReader.IsDBNull(index)? null: (UInt64?)_dataReader.GetDecimal(Index); } public override Decimal? GetNullableDecimal(object o, int index) { return _dataReader.IsDBNull(index)? (decimal?)null: OracleDecimal.SetPrecision(_dataReader.GetOracleDecimal(Index), 28).Value; } } [Mixin(typeof(IDbDataParameter), "_oracleParameter")] [Mixin(typeof(IDataParameter), "_oracleParameter")] [Mixin(typeof(IDisposable), "_oracleParameter")] [Mixin(typeof(ICloneable), "_oracleParameter")] [CLSCompliant(false)] public abstract class OracleParameterWrap { protected OracleParameter _oracleParameter; public OracleParameter OracleParameter { get { return _oracleParameter; } } public static IDbDataParameter CreateInstance(OracleParameter oraParameter) { var wrap = TypeAccessor<OracleParameterWrap>.CreateInstanceEx(); wrap._oracleParameter = oraParameter; return (IDbDataParameter)wrap; } public override string ToString() { return _oracleParameter.ToString(); } ///<summary> ///Gets or sets the value of the parameter. ///</summary> ///<returns> ///An <see cref="T:System.Object"/> that is the value of the parameter. ///The default value is null. ///</returns> protected object Value { #if CONVERTORACLETYPES [MixinOverride] get { object value = _oracleParameter.Value; if (value is OracleBinary) { OracleBinary oracleValue = (OracleBinary)value; return oracleValue.IsNull? null: oracleValue.Value; } if (value is OracleDate) { OracleDate oracleValue = (OracleDate)value; if (oracleValue.IsNull) return null; return oracleValue.Value; } if (value is OracleDecimal) { OracleDecimal oracleValue = (OracleDecimal)value; if (oracleValue.IsNull) return null; return oracleValue.Value; } if (value is OracleIntervalDS) { OracleIntervalDS oracleValue = (OracleIntervalDS)value; if (oracleValue.IsNull) return null; return oracleValue.Value; } if (value is OracleIntervalYM) { OracleIntervalYM oracleValue = (OracleIntervalYM)value; if (oracleValue.IsNull) return null; return oracleValue.Value; } if (value is OracleString) { OracleString oracleValue = (OracleString)value; return oracleValue.IsNull? null: oracleValue.Value; } if (value is OracleTimeStamp) { OracleTimeStamp oracleValue = (OracleTimeStamp)value; if (oracleValue.IsNull) return null; return oracleValue.Value; } if (value is OracleTimeStampLTZ) { OracleTimeStampLTZ oracleValue = (OracleTimeStampLTZ)value; if (oracleValue.IsNull) return null; return oracleValue.Value; } if (value is OracleTimeStampTZ) { OracleTimeStampTZ oracleValue = (OracleTimeStampTZ)value; if (oracleValue.IsNull) return null; return oracleValue.Value; } if (value is OracleXmlType) { OracleXmlType oracleValue = (OracleXmlType)value; return oracleValue.IsNull? null: oracleValue.Value; } return value; } #endif [MixinOverride] set { if (null != value) { if (value is Guid) { // Fix Oracle.Net bug #6: guid type is not handled // value = ((Guid)value).ToByteArray(); } else if (value is Array && !(value is byte[] || value is char[])) { _oracleParameter.CollectionType = OracleCollectionType.PLSQLAssociativeArray; } else if (value is IConvertible) { var convertible = (IConvertible)value; var typeCode = convertible.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: // Fix Oracle.Net bug #7: bool type is handled wrong // value = convertible.ToByte(null); break; case TypeCode.SByte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: // Fix Oracle.Net bug #8: some integer types are handled wrong // value = convertible.ToDecimal(null); break; // Fix Oracle.Net bug #10: zero-length string can not be converted to // ORAXML type, but null value can be. // case TypeCode.String: if (((string)value).Length == 0) value = null; break; default: // Fix Oracle.Net bug #5: Enum type is not handled // if (value is Enum) { // Convert a Enum value to it's underlying type. // value = System.Convert.ChangeType(value, typeCode); } break; } } } _oracleParameter.Value = value; } } } #endregion #region InsertBatch public override int InsertBatch<T>( DbManager db, string insertText, IEnumerable<T> collection, MemberMapper[] members, int maxBatchSize, DbManager.ParameterProvider<T> getParameters) { var sb = new StringBuilder(); var sp = new OracleSqlProvider(); var n = 0; var cnt = 0; var str = "\t" + insertText .Substring(0, insertText.IndexOf(") VALUES (")) .Substring(7) .Replace("\r", "") .Replace("\n", "") .Replace("\t", " ") .Replace("( ", "(") //.Replace(" ", " ") + ") VALUES ("; foreach (var item in collection) { if (sb.Length == 0) sb.AppendLine("INSERT ALL"); sb.Append(str); foreach (var member in members) { var value = member.GetValue(item); if (value is Nullable<DateTime>) value = ((DateTime?)value).Value; if (value is DateTime) { var dt = (DateTime)value; sb.Append(string.Format("to_timestamp('{0:dd.MM.yyyy HH:mm:ss.ffffff}', 'DD.MM.YYYY HH24:MI:SS.FF6')", dt)); } else sp.BuildValue(sb, value); sb.Append(", "); } sb.Length -= 2; sb.AppendLine(")"); n++; if (n >= maxBatchSize) { sb.AppendLine("SELECT * FROM dual"); var sql = sb.ToString(); if (DbManager.TraceSwitch.TraceInfo) DbManager.WriteTraceLine("\n" + sql, DbManager.TraceSwitch.DisplayName); cnt += db.SetCommand(sql).ExecuteNonQuery(); n = 0; sb.Length = 0; } } if (n > 0) { sb.AppendLine("SELECT * FROM dual"); var sql = sb.ToString(); if (DbManager.TraceSwitch.TraceInfo) DbManager.WriteTraceLine("\n" + sql, DbManager.TraceSwitch.DisplayName); cnt += db.SetCommand(sql).ExecuteNonQuery(); } return cnt; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Signum.Utilities; using Signum.Engine.DynamicQuery; using Signum.Entities.DynamicQuery; using Signum.Engine.Maps; using Signum.Entities.Basics; using Signum.Entities; using System.Globalization; using Signum.Engine.Operations; using Signum.Entities.Help; using Signum.Engine.Basics; using DocumentFormat.OpenXml.EMMA; using Signum.Entities.Reflection; using Signum.Utilities.ExpressionTrees; using System.Text.Json.Serialization; namespace Signum.Engine.Help { public abstract class BaseHelp { public abstract string? IsAllowed(); public void AssertAllowed() { string? error = IsAllowed(); if (error != null) throw new UnauthorizedAccessException(EngineMessage.UnauthorizedAccessTo0Because1.NiceToString().FormatWith(this.GetType(), error)); } public abstract override string ToString(); } public class NamespaceHelp : BaseHelp { public readonly string Namespace; public readonly string? Before; public readonly string Title; public readonly string? Description; [JsonIgnore] public readonly CultureInfo Culture; [JsonIgnore] public readonly NamespaceHelpEntity? DBEntity; [JsonIgnore] public readonly Type[] Types; public NamespaceHelp(string @namespace, CultureInfo culture, NamespaceHelpEntity? entity, Type[] types) { Culture = culture; Namespace = @namespace; Types = types; var clean = @namespace.Replace(".Entities", ""); Title = entity?.Let(a => a.Title.DefaultToNull()) ?? clean.TryAfterLast('.') ?? clean; Before = clean.TryBeforeLast('.'); Description = entity?.Description; DBEntity = entity; } public NamespaceHelpEntity Entity { get { var result = new NamespaceHelpEntity { Culture = this.Culture.ToCultureInfoEntity(), Name = this.Namespace, }; if (DBEntity != null) { result.Title = DBEntity.Title; result.Description = DBEntity.Description; result.SetId(DBEntity.Id); result.SetIsNew(DBEntity.IsNew); result.Ticks = DBEntity.Ticks; } return result; } } public EntityItem[] AllowedTypes { get { Schema s = Schema.Current; return Types.Where(t => s.IsAllowed(t, inUserInterface: true) == null).Select(t => new EntityItem(t)).ToArray(); } } public override string? IsAllowed() { if (AllowedTypes.Any()) return null; return "all the types in the nemespace are not allowed"; } public override string ToString() { return "Namespace " + Namespace; } } public class EntityItem { public string CleanName; public bool HasDescription; public EntityItem(Type t) { CleanName = TypeLogic.GetCleanName(t); HasDescription = HelpLogic.GetTypeHelp(t).HasEntity; } } public class TypeHelp : BaseHelp { public readonly Type Type; public readonly CultureInfo Culture; public readonly bool HasEntity; public TypeHelpEntity? DBEntity; public readonly string Info; public readonly Dictionary<PropertyRoute, PropertyHelp> Properties; public readonly Dictionary<OperationSymbol, OperationHelp> Operations; public readonly Dictionary<object, QueryHelp> Queries; public TypeHelp(Type type, CultureInfo culture, TypeHelpEntity? entity) { Type = type; Culture = culture; Info = HelpGenerator.GetEntityHelp(type); var props = DBEntity?.Properties.ToDictionaryEx(a => a.Property.ToPropertyRoute(), a => a.Info); var opers = DBEntity?.Operations.ToDictionaryEx(a => a.Operation, a => a.Info); Properties = PropertyRoute.GenerateRoutes(type) .ToDictionary(pp => pp, pp => new PropertyHelp(pp, props?.TryGetC(pp))); Operations = OperationLogic.TypeOperations(type) .ToDictionary(op => op.OperationSymbol, op => new OperationHelp(op.OperationSymbol, type, opers?.TryGetC(op.OperationSymbol))); var allQueries = HelpLogic.CachedQueriesHelp(); Queries = HelpLogic.TypeToQuery.Value.TryGetC(this.Type).EmptyIfNull().Select(a => allQueries.GetOrThrow(a)).ToDictionary(qh => qh.QueryName); DBEntity = entity; } public TypeHelpEntity GetEntity() { var result = new TypeHelpEntity { Culture = this.Culture.ToCultureInfoEntity(), Type = this.Type.ToTypeEntity(), Description = DBEntity?.Description, Info = Info }; result.Properties.AddRange( from pre in PropertyRouteLogic.RetrieveOrGenerateProperties(this.Type.ToTypeEntity()) let pr = pre.ToPropertyRoute() where !(pr.PropertyInfo != null && pr.PropertyInfo.SetMethod == null && ExpressionCleaner.HasExpansions(pr.PropertyInfo.DeclaringType!, pr.PropertyInfo)) let ph = Properties.GetOrThrow(pre.ToPropertyRoute()) where ph.IsAllowed() == null select new PropertyRouteHelpEmbedded { Property = pre, Info = ph.Info, Description = ph.UserDescription, }); result.Operations.AddRange( from oh in Operations.Values where oh.IsAllowed() == null select new OperationHelpEmbedded { Operation = oh.OperationSymbol, Info = oh.Info, Description = oh.UserDescription, }); result.Queries.AddRange( from qn in QueryLogic.Queries.GetTypeQueries(this.Type).Keys let qh = HelpLogic.GetQueryHelp(qn) where qh.IsAllowed() == null select qh.GetEntity()); if (DBEntity != null) { result.SetId(DBEntity.Id); result.SetIsNew(DBEntity.IsNew); result.Ticks = DBEntity.Ticks; } return result; } public override string? IsAllowed() { return Schema.Current.IsAllowed(Type, inUserInterface: true); } public override string ToString() { return "Type " + TypeLogic.GetCleanName(Type); } } public class PropertyHelp : BaseHelp { public PropertyHelp(PropertyRoute propertyRoute, string? userDescription) { if(propertyRoute.PropertyRouteType != PropertyRouteType.FieldOrProperty) throw new ArgumentException("propertyRoute should be of type Property"); this.PropertyRoute = propertyRoute; this.Info = HelpGenerator.GetPropertyHelp(propertyRoute); this.UserDescription = userDescription; } public readonly string Info; public readonly PropertyRoute PropertyRoute; public readonly string? UserDescription; public PropertyInfo PropertyInfo { get { return PropertyRoute.PropertyInfo!; } } public override string? IsAllowed() { return PropertyRoute.IsAllowed(); } public override string ToString() { return "Property " + this.PropertyRoute.ToString(); } } public class OperationHelp : BaseHelp { public readonly OperationSymbol OperationSymbol; public readonly Type Type; public readonly string Info; public readonly string? UserDescription; public OperationHelp(OperationSymbol operationSymbol, Type type, string? userDescription) { this.OperationSymbol = operationSymbol; this.Type = type; this.Info = HelpGenerator.GetOperationHelp(type, operationSymbol); this.UserDescription = userDescription; } public override string? IsAllowed() { return OperationLogic.OperationAllowed(OperationSymbol, this.Type, inUserInterface: true) ? null : OperationMessage.Operation01IsNotAuthorized.NiceToString(this.OperationSymbol.NiceToString(), this.OperationSymbol.Key); } public override string ToString() { return "Operation " + this.OperationSymbol.Key; } } public class QueryHelp : BaseHelp { public readonly object QueryName; public readonly CultureInfo Culture; public readonly string Info; public readonly Dictionary<string, QueryColumnHelp> Columns; public readonly QueryHelpEntity? DBEntity; public readonly string? UserDescription; public QueryHelp(object queryName, CultureInfo ci, QueryHelpEntity? entity) { QueryName = queryName; Culture = ci; Info = HelpGenerator.GetQueryHelp(QueryLogic.Queries.GetQuery(queryName).Core.Value); var cols = entity?.Columns.ToDictionary(a => a.ColumnName, a => a.Description); Columns = QueryLogic.Queries.GetQuery(queryName).Core.Value.StaticColumns.ToDictionary( cf => cf.Name, cf => new QueryColumnHelp(cf, cf.DisplayName(), HelpGenerator.GetQueryColumnHelp(cf), cols?.TryGetCN(cf.Name))); DBEntity = entity; UserDescription = entity?.Description; } public QueryHelpEntity GetEntity() { var cd = DBEntity?.Columns.ToDictionary(a => a.ColumnName, a => a.Description); var result = new QueryHelpEntity { Culture = this.Culture.ToCultureInfoEntity(), Query = QueryLogic.GetQueryEntity(this.QueryName), Description = DBEntity?.Description, Info = Info, Columns = this.Columns.Values.Where(a => a.Column.IsAllowed() == null) .Select(c => new QueryColumnHelpEmbedded { ColumnName = c.Column.Name, Description = cd?.TryGetCN(c.Column.Name)!, NiceName = c.NiceName, Info = c.Info, }).ToMList() }; if (DBEntity != null) { result.SetId(DBEntity.Id); result.SetIsNew(DBEntity.IsNew); result.Ticks = DBEntity.Ticks; } return result; } public override string ToString() { return "Query " + QueryUtils.GetKey(this.QueryName); } public override string? IsAllowed() { return QueryLogic.Queries.QueryAllowed(this.QueryName, false) ? null : "Access to query {0} not allowed".FormatWith(QueryUtils.GetKey(this.QueryName)); } } public class QueryColumnHelp : BaseHelp { public ColumnDescriptionFactory Column; public string NiceName; public string Info; public string? UserDescription; public QueryColumnHelp(ColumnDescriptionFactory column, string niceName, string info, string? userDescription) { this.Column = column; this.NiceName = niceName; this.Info = info; this.UserDescription = userDescription; } public override string? IsAllowed() { return Column.IsAllowed(); } public override string ToString() { return "Column " + Column.Name; } } }
using System; using System.Xml; using YamlDotNet.RepresentationModel; using System.Globalization; using System.Diagnostics; namespace YamlDotNet.Converters.Xml { /// <summary> /// Converts between <see cref="YamlDocument"/> and <see cref="XmlDocument"/>. /// </summary> public class XmlConverter { #region YamlToXmlDocumentVisitor private class YamlToXmlDocumentVisitor : YamlVisitor { private XmlDocument myDocument; private XmlNode current; private readonly XmlConverterOptions options; public XmlDocument Document { get { return myDocument; } } private void PushNode(string elementName) { XmlNode newNode = myDocument.CreateElement(elementName); current.AppendChild(newNode); current = newNode; } private void PopNode() { current = current.ParentNode; } public YamlToXmlDocumentVisitor(XmlConverterOptions options) { this.options = options; } protected override void Visit(YamlDocument document) { myDocument = new XmlDocument(); current = myDocument; PushNode(options.RootElementName); } protected override void Visit(YamlScalarNode scalar) { current.AppendChild(myDocument.CreateTextNode(scalar.Value)); } protected override void Visit(YamlSequenceNode sequence) { PushNode(options.SequenceElementName); } protected override void Visited(YamlSequenceNode sequence) { PopNode(); } protected override void VisitChildren(YamlSequenceNode sequence) { foreach (var item in sequence.Children) { PushNode(options.SequenceItemElementName); item.Accept(this); PopNode(); } } protected override void Visit(YamlMappingNode mapping) { PushNode(options.MappingElementName); } protected override void Visited(YamlMappingNode mapping) { PopNode(); } protected override void VisitChildren(YamlMappingNode mapping) { foreach (var pair in mapping.Children) { PushNode(options.MappingEntryElementName); PushNode(options.MappingKeyElementName); pair.Key.Accept(this); PopNode(); PushNode(options.MappingValueElementName); pair.Value.Accept(this); PopNode(); PopNode(); } } } #endregion #region XmlToYamlConverter private class XmlToYamlConverter { private struct ExitCaller : IDisposable { private readonly XmlToYamlConverter owner; public ExitCaller(XmlToYamlConverter owner) { this.owner = owner; } #region IDisposable Members public void Dispose() { owner.Exit(); } #endregion } private readonly XmlConverterOptions options; private readonly XmlDocument document; private XmlNode current; private XmlNode currentParent; public XmlToYamlConverter(XmlDocument document, XmlConverterOptions options) { this.document = document; this.options = options; } public YamlDocument ParseDocument() { currentParent = document; current = document.DocumentElement; using (ExpectElement(options.RootElementName)) { return new YamlDocument(ParseNode()); } } private YamlNode ParseNode() { if(AcceptText()) { return ParseScalar(); } if (AcceptElement(options.SequenceElementName)) { return ParseSequence(); } if (AcceptElement(options.MappingElementName)) { return ParseMapping(); } throw new InvalidOperationException("Expected sequence, mapping or scalar."); } private YamlNode ParseMapping() { using(ExpectElement(options.MappingElementName)) { YamlMappingNode mapping = new YamlMappingNode(); while (AcceptElement(options.MappingEntryElementName)) { using(ExpectElement(options.MappingEntryElementName)) { YamlNode key; using(ExpectElement(options.MappingKeyElementName)) { key = ParseNode(); } YamlNode value; using(ExpectElement(options.MappingValueElementName)) { value = ParseNode(); } mapping.Children.Add(key, value); } } return mapping; } } private YamlNode ParseSequence() { using (ExpectElement(options.SequenceElementName)) { YamlSequenceNode sequence = new YamlSequenceNode(); while (AcceptElement(options.SequenceItemElementName)) { using(ExpectElement(options.SequenceItemElementName)) { sequence.Children.Add(ParseNode()); } } return sequence; } } private YamlNode ParseScalar() { string text = ExpectText(); Exit(); return new YamlScalarNode(text); } #region Navigation methods private bool Accept(XmlNodeType nodeType, string elementName) { if (current == null) { return false; } if (current.NodeType != nodeType) { return false; } if (nodeType == XmlNodeType.Element) { if (current.LocalName != elementName) { return false; } } return true; } private bool AcceptText() { return Accept(XmlNodeType.Text, null); } private bool AcceptElement(string elementName) { return Accept(XmlNodeType.Element, elementName); } private XmlNode Expect(XmlNodeType nodeType, string elementName) { if(!Accept(nodeType, elementName)) { if (nodeType == XmlNodeType.Text) { throw new InvalidOperationException(string.Format( CultureInfo.InvariantCulture, "Expected node type '{0}', got '{1}'.", nodeType, current.NodeType )); } else { throw new InvalidOperationException(string.Format( CultureInfo.InvariantCulture, "Expected element '{0}', got '{1}'.", elementName, current.LocalName )); } } currentParent = current; current = current.FirstChild; return currentParent; } private IDisposable ExpectElement(string elementName) { Expect(XmlNodeType.Element, elementName); return new ExitCaller(this); } private string ExpectText() { return Expect(XmlNodeType.Text, null).Value; } private void Exit() { Debug.Assert(current == null); current = currentParent.NextSibling; currentParent = currentParent.ParentNode; } #endregion } #endregion private readonly XmlConverterOptions options; /// <summary> /// Initializes a new instance of the <see cref="XmlConverter"/> class. /// </summary> /// <param name="options">The options.</param> public XmlConverter(XmlConverterOptions options) { this.options = options.IsReadOnly ? options : options.AsReadOnly(); } /// <summary> /// Initializes a new instance of the <see cref="XmlConverter"/> class. /// </summary> public XmlConverter() : this(XmlConverterOptions.Default) { } /// <summary> /// Converts a <see cref="YamlDocument"/> to <see cref="XmlDocument"/>. /// </summary> /// <param name="document">The YAML document to convert.</param> /// <returns></returns> public XmlDocument ToXml(YamlDocument document) { YamlToXmlDocumentVisitor visitor = new YamlToXmlDocumentVisitor(options); document.Accept(visitor); return visitor.Document; } /// <summary> /// Converts a <see cref="XmlDocument"/> to <see cref="YamlDocument"/>. /// </summary> /// <param name="document">The XML document to convert.</param> /// <returns></returns> public YamlDocument FromXml(XmlDocument document) { XmlToYamlConverter converter = new XmlToYamlConverter(document, options); return converter.ParseDocument(); } } }
using System; using System.Xml.Serialization; using FarseerGames.FarseerPhysics.Dynamics.Joints; using FarseerGames.FarseerPhysics.Dynamics.Springs; using FarseerGames.FarseerPhysics.Interfaces; using FarseerGames.FarseerPhysics.Collisions; using FarseerGames.FarseerPhysics.Controllers; #if (XNA) using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; #else using FarseerGames.FarseerPhysics.Mathematics; #endif namespace FarseerGames.FarseerPhysics.Dynamics { public delegate bool FixedJointDelegate(Joint sender, Body body); public delegate bool JointDelegate(Joint sender, Body body1, Body body2); public delegate bool FixedSpringDelegate(Spring sender, Body body); public delegate bool SpringDelegate(Spring sender, Body body1, Body body2); public delegate void UpdatedEventHandler(ref Vector2 position, ref float rotation); /// <summary> /// The Body handles all the physics of motion: position, velocity, acceleration /// forces, torques, etc...</para> /// <para>The Body is integrated every time step (which should be fixed) by the <see cref="PhysicsSimulator"/> in the following manner: /// Set forces and torques (gravity, springs, user input...)->Apply forces and torques (updating velocity only)->Update positions and Rotations</para> /// <para>In technical terms, this is known as Symplectic Euler Integration because /// velocity is updated prior to position (The reverse of simple Euler Integration)</para> /// </summary> public sealed class Body : IIsDisposable { private float _momentOfInertia = 1; //1 unit square private float _previousAngularVelocity; private Vector2 _previousLinearVelocity = Vector2.Zero; private Vector2 _previousPosition = Vector2.Zero; private float _previousRotation; private int _revolutions; private float _torque; private bool _isDisposed; internal Vector2 impulse = Vector2.Zero; internal float inverseMass = 1; internal float inverseMomentOfInertia = 1; internal float totalRotation; internal float rotation; internal Vector2 linearVelocityBias = Vector2.Zero; internal float mass = 1; internal Vector2 position = Vector2.Zero; internal float angularVelocityBias; internal Vector2 force = Vector2.Zero; internal bool isStatic; /// <summary> /// The rate at which a body is rotating /// </summary> /// <Value>The angular velocity.</Value> public float AngularVelocity; /// <summary> ///Sets whether or not the body will take part in the simulation. /// If not enabled, the body will remain in the internal list of bodies but it will not be updated. /// </summary> public bool Enabled = true; /// <summary> /// Gets or sets a Value indicating whether this body ignores gravity. /// </summary> /// <Value><c>true</c> if it ignores gravity; otherwise, <c>false</c>.</Value> public bool IgnoreGravity; /// <summary> /// Gets or sets a Value indicating whether this body is quadratic drag enabled. /// </summary> /// <Value> /// <c>true</c> if this body is quadratic drag enabled; otherwise, <c>false</c>. /// </Value> public bool IsQuadraticDragEnabled; /// <summary> /// The linear drag coefficient is the amount of drag a body has. /// Linear drag is the drag applied when the body travels in a straight line. /// Default is 0.001f - tuned for a body of mass 1 /// </summary> public float LinearDragCoefficient = .001f; /// <summary> /// Gets or sets the linear velocity. /// </summary> /// <Value>The linear velocity.</Value> public Vector2 LinearVelocity = Vector2.Zero; /// <summary> /// Gets or sets the quadratic drag coefficient. /// </summary> /// <Value>The quadratic drag coefficient.</Value> public float QuadraticDragCoefficient = .001f; /// <summary> /// Gets or sets the rotational drag coefficient. /// </summary> /// <Value>The rotational drag coefficient.</Value> public float RotationalDragCoefficient = .001f; //tuned for a 1.28m X 1.28m rectangle with mass = 1 #if(XNA) [ContentSerializerIgnore] #endif [XmlIgnore] /// <summary> /// Gets or sets the tag. A tag is used to attach a custom object to the Body. /// </summary> /// <Value>The custom object</Value> public object Tag; #if(XNA) [ContentSerializerIgnore] #endif [XmlIgnore] /// <summary> /// If the position or rotation of the body changes, this event will be fired. /// </summary> public UpdatedEventHandler Updated; /// <summary> /// Fires when body gets disposed /// </summary> public event EventHandler<EventArgs> Disposed; //NOTE: shouldn't need this. commenting out but keeping incase needed in the future. //private float linearDragVelocityThreshhold = .000001f; public Body() { } /// <summary> /// Body constructor that makes a copy of another body /// </summary> /// <param name="body"></param> public Body(Body body) { Mass = body.Mass; MomentOfInertia = body.MomentOfInertia; LinearDragCoefficient = body.LinearDragCoefficient; RotationalDragCoefficient = body.RotationalDragCoefficient; IsQuadraticDragEnabled = body.IsQuadraticDragEnabled; QuadraticDragCoefficient = body.QuadraticDragCoefficient; Enabled = body.Enabled; Tag = body.Tag; IgnoreGravity = body.IgnoreGravity; IsStatic = body.isStatic; } #region Added by Daniel Pramel 08/17/08 /// <summary> /// Returns or sets how long (ms) the body is below the <see cref="MinimumVelocity"/>. /// If this time is greater than the InactivityControllers "MaxIdleTime", it will be deactivated /// </summary> public float IdleTime; /// <summary> /// Returns or sets whether the body can be deactivated by the <see cref="InactivityController"/> or not /// </summary> public bool IsAutoIdle; /// <summary> /// Returns or sets the minimum velocity. If the body's velocity is below this Value, it can /// be deactivated /// </summary> public float MinimumVelocity = 55; /// <summary> /// Returns whether the body is below the minimum velocity or not /// </summary> public bool Moves { get { return LinearVelocity.Length() >= MinimumVelocity; } } #endregion /// <summary> /// The mass of the Body /// </summary> /// <exception cref="ArgumentException">Mass cannot be 0</exception> public float Mass { get { return mass; } set { if (value == 0) throw new ArgumentException("Mass cannot be 0", "value"); mass = value; if (isStatic) inverseMass = 0; else inverseMass = 1f / value; } } /// <summary> /// The inverse of the mass of the body (1/Mass) /// </summary> public float InverseMass { get { return inverseMass; } } /// <summary> /// The moment of inertia of the body. /// <para>The moment of inertia of a body in 2D is a scalar Value that represents how /// difficult (or not difficult) it is to rotate a body about the center of mass.</para> /// <para>The moment of inertia varies by the shape of the body. For basic shapes like /// circles and rectangles, formulas exist for computing the moment of inertia based on /// the shape properties (radius of the circle, or length and width of the rectangle)</para> /// <para>For bodies that are not basic, it is usually good enough to estimate the moment of /// inertia by picking a basic shape that is close to the same shape. It is also possible /// using more advance calculus techniques to compute the actual moment of inertia of /// non-basic shapes.</para> /// The <see cref="Vertices"/> class has the ability of calculating the MOI (Moment of Inertia) from a polygon shape. /// </summary> /// <exception cref="ArgumentException">Moment of inertia cannot be 0 or less</exception> public float MomentOfInertia { get { return _momentOfInertia; } set { if (value <= 0) throw new ArgumentException("Moment of inertia cannot be 0 or less", "value"); _momentOfInertia = value; if (isStatic) inverseMomentOfInertia = 0; else inverseMomentOfInertia = 1f / value; } } /// <summary> /// The inverse of the moment of inertia of the body (1/<see cref="MomentOfInertia"/>) /// </summary> public float InverseMomentOfInertia { get { return inverseMomentOfInertia; } } /// <summary> /// Indicates this body is fixed within the world and will not move no matter what forces are applied. /// <para>Bodies that represent land or world borders are a good examples of static bodies.</para> /// </summary> public bool IsStatic { get { return isStatic; } set { isStatic = value; if (isStatic) { inverseMass = 0; inverseMomentOfInertia = 0; } else { inverseMass = 1f / mass; inverseMomentOfInertia = 1f / _momentOfInertia; } } } /// <summary> /// Gets or sets the position. /// </summary> /// <Value>The position.</Value> public Vector2 Position { get { return position; } set { position = value; if (Updated != null) { Updated(ref position, ref rotation); } } } /// <summary> /// Gets the revolutions relative to the original state of the body /// </summary> /// <Value>The revolutions.</Value> public int Revolutions { get { return _revolutions; } } /// <summary> /// Gets or sets the rotation. /// </summary> /// <Value>The rotation.</Value> public float Rotation { get { return rotation; } set { rotation = value; // Calculate floating point remainder of rotation int z = (int)(rotation / MathHelper.TwoPi); if (rotation < 0) z--; rotation = (rotation - z * MathHelper.TwoPi); _revolutions += z; totalRotation = rotation + _revolutions * MathHelper.TwoPi; if (Updated != null) { Updated(ref position, ref rotation); } } } /// <summary> /// Returns the total rotation of a body. /// If a body spins around 10 times then TotalRotation wold return 2 * Pi * 10. /// This property is mostly intended for internal use by the angle joints and springs but it could be useful in some situations for game related things. /// This property is read-only /// </summary> /// <Value>The total rotation.</Value> public float TotalRotation { get { return totalRotation; } } /// <summary> /// The total amount of force that will be applied to the body in the upcoming loop. /// The force is cleared at the end of every update call, so this Value should only be called just prior to calling update. /// This property is read-only. /// </summary> /// <Value>The force.</Value> public Vector2 Force { get { return force; } } /// <summary> /// The total amount of torque that will be applied to the body in the upcoming loop. /// The Torque is cleared at the end of every update call, so this Value should only be called just prior to calling update. /// Torque can be thought of as the rotational analog of a force. /// This property is read-only. /// </summary> /// <Value>The torque.</Value> public float Torque { get { return _torque; } } /// <summary> /// Returns a unit vector that represents the local X direction of a body converted to world coordinates. /// This property is read-only /// </summary> /// <Value>The X vector in world coordinates.</Value> public Vector2 XVectorInWorldCoordinates { get { GetBodyMatrix(out _bodyMatrixTemp); return new Vector2(_bodyMatrixTemp.Right.X, _bodyMatrixTemp.Right.Y); } } /// <summary> /// Returns a unit vector that represents the local Y direction of a body converted to world coordinates. /// This property is read-only /// </summary> /// <Value>The Y vector in world coordinates.</Value> public Vector2 YVectorInWorldCoordinates { get { GetBodyMatrix(out _bodyMatrixTemp); return new Vector2(_bodyMatrixTemp.Up.X, _bodyMatrixTemp.Up.Y); } } /// <summary> /// This method will reset position and motion properties. This method is useful /// when creating pools of re-usable bodies. It could be used when releasing bodies /// back into the pool. /// </summary> public void ResetDynamics() { LinearVelocity.X = 0; LinearVelocity.Y = 0; _previousLinearVelocity.X = 0; _previousLinearVelocity.Y = 0; AngularVelocity = 0; _previousAngularVelocity = 0; position.X = 0; position.Y = 0; _previousPosition.X = 0; _previousPosition.Y = 0; rotation = 0; _revolutions = 0; totalRotation = 0; force.X = 0; force.Y = 0; _torque = 0; impulse.X = 0; impulse.Y = 0; _linearDrag.X = 0; _linearDrag.Y = 0; _rotationalDrag = 0; } /// <summary> /// Gets the body matrix. /// It's a combination of the translation and rotation matrix. /// </summary> /// <returns></returns> public Matrix GetBodyMatrix() { Matrix.CreateTranslation(position.X, position.Y, 0, out _translationMatrixTemp); Matrix.CreateRotationZ(rotation, out _rotationMatrixTemp); Matrix.Multiply(ref _rotationMatrixTemp, ref _translationMatrixTemp, out _bodyMatrixTemp); return _bodyMatrixTemp; } /// <summary> /// Gets the body matrix. /// It's a combination of the translation and rotation matrix. /// </summary> /// <returns></returns> public void GetBodyMatrix(out Matrix bodyMatrix) { Matrix.CreateTranslation(position.X, position.Y, 0, out _translationMatrixTemp); Matrix.CreateRotationZ(rotation, out _rotationMatrixTemp); Matrix.Multiply(ref _rotationMatrixTemp, ref _translationMatrixTemp, out bodyMatrix); } /// <summary> /// Gets the body rotation matrix. /// </summary> /// <returns></returns> public Matrix GetBodyRotationMatrix() { Matrix.CreateRotationZ(rotation, out _rotationMatrixTemp); return _rotationMatrixTemp; } /// <summary> /// Gets the body rotation matrix. /// </summary> /// <returns></returns> public void GetBodyRotationMatrix(out Matrix rotationMatrix) { Matrix.CreateRotationZ(rotation, out rotationMatrix); } /// <summary> /// Gets the body's position in world coordinates from local coordinates. /// </summary> /// <param name="localPosition">The local position of the body</param> /// <returns>The world position of the body</returns> public Vector2 GetWorldPosition(Vector2 localPosition) { GetBodyMatrix(out _bodyMatrixTemp); Vector2.Transform(ref localPosition, ref _bodyMatrixTemp, out _worldPositionTemp); return _worldPositionTemp; } /// <summary> /// Gets the body's position in world coordinates from local coordinates. /// </summary> /// <param name="localPosition">The local position of the body</param> /// <param name="worldPosition">The world position.</param> public void GetWorldPosition(ref Vector2 localPosition, out Vector2 worldPosition) { GetBodyMatrix(out _bodyMatrixTemp); Vector2.Transform(ref localPosition, ref _bodyMatrixTemp, out worldPosition); } /// <summary> /// Gets the body's position in local coordinates from world coordinates. /// </summary> /// <param name="worldPosition">The world position of the body</param> /// <returns>The local position of the body</returns> public Vector2 GetLocalPosition(Vector2 worldPosition) { GetBodyRotationMatrix(out _rotationMatrixTemp); Matrix.Transpose(ref _rotationMatrixTemp, out _rotationMatrixTemp); Vector2.Subtract(ref worldPosition, ref position, out _localPositionTemp); Vector2.Transform(ref _localPositionTemp, ref _rotationMatrixTemp, out _localPositionTemp); return _localPositionTemp; } /// <summary> /// Gets the body's position in local coordinates from world coordinates. /// </summary> /// <param name="worldPosition">The world position of the body</param> /// <param name="localPosition">The local position.</param> public void GetLocalPosition(ref Vector2 worldPosition, out Vector2 localPosition) { GetBodyRotationMatrix(out _rotationMatrixTemp); Matrix.Transpose(ref _rotationMatrixTemp, out _rotationMatrixTemp); Vector2.Subtract(ref worldPosition, ref position, out localPosition); Vector2.Transform(ref localPosition, ref _rotationMatrixTemp, out localPosition); } /// <summary> /// Gets the velocity at a local point. /// </summary> /// <param name="localPoint">The local point.</param> /// <returns>The velocity at the point</returns> public Vector2 GetVelocityAtLocalPoint(Vector2 localPoint) { GetVelocityAtLocalPoint(ref localPoint, out _tempVelocity); return _tempVelocity; } /// <summary> /// Gets the velocity at a local point. /// </summary> /// <param name="localPoint">The local point.</param> /// <param name="velocity">The velocity.</param> public void GetVelocityAtLocalPoint(ref Vector2 localPoint, out Vector2 velocity) { GetWorldPosition(ref localPoint, out _r1); Vector2.Subtract(ref _r1, ref position, out _r1); GetVelocityAtWorldOffset(ref _r1, out velocity); } /// <summary> /// Gets the velocity at a world point. /// </summary> /// <param name="worldPoint">The world point.</param> /// <param name="velocity">The velocity.</param> public void GetVelocityAtWorldPoint(ref Vector2 worldPoint, out Vector2 velocity) { Vector2.Subtract(ref worldPoint, ref position, out _r1); GetVelocityAtWorldOffset(ref _r1, out velocity); } #if(XNA) private Vector2 _velocityTemp = Vector2.Zero; #endif /// <summary> /// Gets the velocity at world offset. /// </summary> /// <param name="offset">The offset.</param> /// <param name="velocity">The velocity.</param> public void GetVelocityAtWorldOffset(ref Vector2 offset, out Vector2 velocity) { #if(XNA) //required by xbox velocity = _velocityTemp; #endif #region INLINED: Calculator.Cross(ref AngularVelocity, ref offset, out velocity); velocity.X = -AngularVelocity * offset.Y; velocity.Y = AngularVelocity * offset.X; #endregion #region INLINED: Vector2.Add(ref linearVelocity, ref velocity, out velocity); velocity.X = velocity.X + LinearVelocity.X; velocity.Y = velocity.Y + LinearVelocity.Y; #endregion } /// <summary> /// Gets the velocity bias at world offset. /// </summary> /// <param name="offset">The offset.</param> /// <param name="velocityBias">The velocity bias.</param> public void GetVelocityBiasAtWorldOffset(ref Vector2 offset, out Vector2 velocityBias) { #if(XNA) //required by xbox velocityBias = _velocityTemp; #endif #region INLINED: Calculator.Cross(ref angularVelocityBias, ref offset, out velocityBias); velocityBias.X = -angularVelocityBias * offset.Y; velocityBias.Y = angularVelocityBias * offset.X; #endregion #region INLINED: Vector2.Add(ref linearVelocityBias, ref velocityBias, out velocityBias); velocityBias.X = velocityBias.X + linearVelocityBias.X; velocityBias.Y = velocityBias.Y + linearVelocityBias.Y; #endregion } /// <summary> /// Adds force to the body. /// </summary> /// <param name="amount">The amount.</param> public void ApplyForce(Vector2 amount) { #region INLINE: Vector2.Add(ref this.force, ref amount, out this.force); force.X = force.X + amount.X; force.Y = force.Y + amount.Y; #endregion } /// <summary> /// Applies a force to the body. /// </summary> /// <param name="amount">The amount.</param> public void ApplyForce(ref Vector2 amount) { #region INLINE: Vector2.Add(ref this.force, ref amount, out this.force); force.X = force.X + amount.X; force.Y = force.Y + amount.Y; #endregion } /// <summary> /// Applies force at a local point. /// </summary> /// <param name="amount">The amount.</param> /// <param name="point">The point.</param> public void ApplyForceAtLocalPoint(Vector2 amount, Vector2 point) { //calculate _torque (2D cross product point X force) GetWorldPosition(ref point, out _diff); Vector2.Subtract(ref _diff, ref position, out _diff); float torque = _diff.X * amount.Y - _diff.Y * amount.X; //add to _torque _torque += torque; // add linear force force.X += amount.X; force.Y += amount.Y; } /// <summary> /// Applies force at a local point. /// </summary> /// <param name="amount">The amount.</param> /// <param name="point">The point.</param> public void ApplyForceAtLocalPoint(ref Vector2 amount, ref Vector2 point) { //calculate _torque (2D cross product point X force) GetWorldPosition(ref point, out _diff); Vector2.Subtract(ref _diff, ref position, out _diff); float torque = _diff.X * amount.Y - _diff.Y * amount.X; //add to _torque _torque += torque; // add linear force force.X += amount.X; force.Y += amount.Y; } /// <summary> /// Applies force at a world point. /// </summary> /// <param name="amount">The amount.</param> /// <param name="point">The point.</param> public void ApplyForceAtWorldPoint(Vector2 amount, Vector2 point) { Vector2.Subtract(ref point, ref position, out _diff); float torque = _diff.X * amount.Y - _diff.Y * amount.X; //add to _torque _torque += torque; // add linear force force.X += amount.X; force.Y += amount.Y; } /// <summary> /// Applies force at a world point. /// </summary> /// <param name="amount">The amount.</param> /// <param name="point">The point.</param> public void ApplyForceAtWorldPoint(ref Vector2 amount, ref Vector2 point) { Vector2.Subtract(ref point, ref position, out _diff); float torque = _diff.X * amount.Y - _diff.Y * amount.X; //add to _torque _torque += torque; // add linear force force.X += amount.X; force.Y += amount.Y; } /// <summary> /// Clears the force of the body. /// This method gets called after each update. /// </summary> public void ClearForce() { force.X = 0; force.Y = 0; } /// <summary> /// Adds a torque to the body. /// </summary> /// <param name="torque">The torque.</param> public void ApplyTorque(float torque) { _torque += torque; } /// <summary> /// Clears the torque of the body. /// This method gets called after each update. /// </summary> public void ClearTorque() { _torque = 0; } /// <summary> /// Stores all applied impulses so that they can be applied at the same time /// by the <see cref="PhysicsSimulator"/>. /// </summary> /// <param name="amount"></param> public void ApplyImpulse(Vector2 amount) { //Applying second fix from: http://www.codeplex.com/FarseerPhysics/WorkItem/View.aspx?WorkItemId=20155 //#region INLINE: Vector2.Multiply(ref impulse, inverseMass, out _dv); //_dv.X = amount.X * inverseMass; //_dv.Y = amount.Y * inverseMass; //#endregion #region INLINE: Vector2.Add(ref amount, ref impulse, out impulse); impulse.X += amount.X; impulse.Y += amount.Y; #endregion } /// <summary> /// Stores all applied impulses so that they can be applied at the same time /// by the <see cref="PhysicsSimulator"/>. /// </summary> /// <param name="amount"></param> public void ApplyImpulse(ref Vector2 amount) { //Applying second fix from: http://www.codeplex.com/FarseerPhysics/WorkItem/View.aspx?WorkItemId=20155 //#region INLINE: Vector2.Multiply(ref impulse, inverseMass, out _dv); //_dv.X = amount.X * inverseMass; //_dv.Y = amount.Y * inverseMass; //#endregion #region INLINE: Vector2.Add(ref amount, ref impulse, out impulse); impulse.X += amount.X; impulse.Y += amount.Y; #endregion } /// <summary> /// Applies then clears all the external impulses that were accumulated /// </summary> internal void ApplyImpulses() { ApplyImmediateImpulse(ref impulse); impulse.X = 0; impulse.Y = 0; } /// <summary> /// used internally only by the joints and arbiter. /// </summary> /// <param name="amount"></param> internal void ApplyImmediateImpulse(ref Vector2 amount) { if (isStatic) return; #region INLINE: Vector2.Multiply(ref impulse, inverseMass, out _dv); _dv.X = amount.X * inverseMass; _dv.Y = amount.Y * inverseMass; #endregion #region INLINE: Vector2.Add(ref _dv, ref linearVelocity, out linearVelocity); LinearVelocity.X = _dv.X + LinearVelocity.X; LinearVelocity.Y = _dv.Y + LinearVelocity.Y; #endregion } /// <summary> /// Clears the impulse of the body. /// </summary> public void ClearImpulse() { impulse.X = 0; impulse.Y = 0; } /// <summary> /// Applies angular impulse. /// </summary> /// <param name="amount">The amount.</param> public void ApplyAngularImpulse(float amount) { AngularVelocity += amount * inverseMomentOfInertia; } /// <summary> /// Applies angular impulse. /// </summary> /// <param name="amount">The amount.</param> public void ApplyAngularImpulse(ref float amount) { AngularVelocity += amount * inverseMomentOfInertia; } /// <summary> /// Use internally by the engine to integrate the velocity. /// </summary> /// <param name="dt">The delta time.</param> internal void IntegrateVelocity(float dt) { //Calculate linear drag #region INLINE: Vector2.Multiply(ref linearVelocity, -_linearDragCoefficient, out _linearDrag); _linearDrag.X = -LinearVelocity.X * LinearDragCoefficient; _linearDrag.Y = -LinearVelocity.Y * LinearDragCoefficient; #endregion //Quadratic drag for "fast" moving objects. Must be enabled first. if (IsQuadraticDragEnabled) { float num = (LinearVelocity.X * LinearVelocity.X) + (LinearVelocity.Y * LinearVelocity.Y); _speed = (float)Math.Sqrt(num); #region INLINE: Vector2.Multiply(ref linearVelocity, -_quadraticDragCoefficient * _speed, out _quadraticDrag); _quadraticDrag.X = -QuadraticDragCoefficient * _speed * LinearVelocity.X; _quadraticDrag.Y = -QuadraticDragCoefficient * _speed * LinearVelocity.Y; #endregion #region INLINE: Vector2.Add(ref _linearDrag, ref _quadraticDrag, out _totalDrag); _totalDrag.X = _linearDrag.X + _quadraticDrag.X; _totalDrag.Y = _linearDrag.Y + _quadraticDrag.Y; #endregion ApplyForce(ref _totalDrag); } else { ApplyForce(ref _linearDrag); } //Calculate rotational drag and apply it as torque _rotationalDrag = AngularVelocity * AngularVelocity * Math.Sign(AngularVelocity); _rotationalDrag *= -RotationalDragCoefficient; ApplyTorque(_rotationalDrag); //Calculate acceleration #region INLINE: Vector2.Multiply(ref force, inverseMass, out _acceleration); _acceleration.X = force.X * inverseMass; _acceleration.Y = force.Y * inverseMass; #endregion #region INLINE: Vector2.Multiply(ref _acceleration, dt, out _dv); _dv.X = _acceleration.X * dt; _dv.Y = _acceleration.Y * dt; #endregion _previousLinearVelocity = LinearVelocity; #region INLINE: Vector2.Add(ref _previousLinearVelocity, ref _dv, out linearVelocity); LinearVelocity.X = _previousLinearVelocity.X + _dv.X; LinearVelocity.Y = _previousLinearVelocity.Y + _dv.Y; #endregion //Angular velocity _dw = _torque * inverseMomentOfInertia * dt; _previousAngularVelocity = AngularVelocity; AngularVelocity = _previousAngularVelocity + _dw; } /// <summary> /// Use internally by the engine to integrate the position. /// </summary> /// <param name="dt">The delta time.</param> internal void IntegratePosition(float dt) { // //Linear // //Linear velocity _tempLinearVelocity.X = LinearVelocity.X + linearVelocityBias.X; _tempLinearVelocity.Y = LinearVelocity.Y + linearVelocityBias.Y; //Position change _tempDeltaPosition.X = _tempLinearVelocity.X * dt; _tempDeltaPosition.Y = _tempLinearVelocity.Y * dt; if (_tempDeltaPosition != Vector2.Zero) { //Save old position _previousPosition = position; //Apply position change position.X = _previousPosition.X + _tempDeltaPosition.X; position.Y = _previousPosition.Y + _tempDeltaPosition.Y; _changed = true; } //Reset linear velocity bias linearVelocityBias.X = 0; linearVelocityBias.Y = 0; // //Angular // //Angular velocity _tempAngularVelocity = AngularVelocity + angularVelocityBias; //Rotation change _tempDeltaRotation = _tempAngularVelocity * dt; if (_tempDeltaRotation != 0f) { //Save old rotation _previousRotation = rotation; //Apply rotation change rotation = _previousRotation + _tempDeltaRotation; _changed = true; //Calculate floating point remainder of rotation int z = (int)(rotation / MathHelper.TwoPi); if (rotation < 0) z--; rotation = (rotation - z * MathHelper.TwoPi); _revolutions += z; totalRotation = rotation + _revolutions * MathHelper.TwoPi; } //Reset angular velocity bias angularVelocityBias = 0; if (_changed) { if (Updated != null) { Updated(ref position, ref rotation); } } } /// <summary> /// Applies a impulse at the specified world offset. /// </summary> /// <param name="amount">The amount.</param> /// <param name="offset">The offset.</param> internal void ApplyImpulseAtWorldOffset(ref Vector2 amount, ref Vector2 offset) { #region INLINE: Vector2.Multiply(ref impulse, inverseMass, out _dv); _dv.X = amount.X * inverseMass; _dv.Y = amount.Y * inverseMass; #endregion #region INLINE: Vector2.Add(ref _dv, ref linearVelocity, out linearVelocity); LinearVelocity.X = _dv.X + LinearVelocity.X; LinearVelocity.Y = _dv.Y + LinearVelocity.Y; #endregion #region INLINE: Calculator.Cross(ref offset, ref impulse, out angularImpulse); float angularImpulse = offset.X * amount.Y - offset.Y * amount.X; #endregion angularImpulse *= inverseMomentOfInertia; AngularVelocity += angularImpulse; } /// <summary> /// Applies a bias impulse at the specified world offset. /// </summary> /// <param name="impulseBias">The impulse bias.</param> /// <param name="offset">The offset.</param> internal void ApplyBiasImpulseAtWorldOffset(ref Vector2 impulseBias, ref Vector2 offset) { #region INLINE: Vector2.Multiply(ref impulseBias, inverseMass, out _dv); _dv.X = impulseBias.X * inverseMass; _dv.Y = impulseBias.Y * inverseMass; #endregion #region INLINE: Vector2.Add(ref _dv, ref linearVelocityBias, out linearVelocityBias); linearVelocityBias.X = _dv.X + linearVelocityBias.X; linearVelocityBias.Y = _dv.Y + linearVelocityBias.Y; #endregion #region INLINE: Calculator.Cross(ref offset, ref impulseBias, out angularImpulseBias); float angularImpulseBias = offset.X * impulseBias.Y - offset.Y * impulseBias.X; #endregion angularImpulseBias *= inverseMomentOfInertia; angularVelocityBias += angularImpulseBias; } #region IDisposable Members public void Dispose() { IsDisposed = true; if (Disposed != null) { Disposed(this, EventArgs.Empty); } GC.SuppressFinalize(this); } #endregion #region GetWorldPosition variables private Vector2 _worldPositionTemp = Vector2.Zero; #endregion #region IntegeratePosition variables private float _tempAngularVelocity; private Vector2 _tempLinearVelocity; private Vector2 _tempDeltaPosition; private float _tempDeltaRotation; private bool _changed; #endregion #region IntegerateVelocity variables private Vector2 _acceleration = Vector2.Zero; private Vector2 _dv = Vector2.Zero; //change in linear velocity private float _dw; //change in angular velocity #endregion #region ApplyDrag variables //private Vector2 dragDirection = Vector2.Zero; private Vector2 _linearDrag = Vector2.Zero; private Vector2 _quadraticDrag = Vector2.Zero; private float _rotationalDrag; private float _speed; private Vector2 _totalDrag = Vector2.Zero; #endregion #region ApplyForceAtLocalPoint variables private Vector2 _diff; private Vector2 _tempVelocity = Vector2.Zero; #endregion #region GetVelocityAtPoint variables private Vector2 _r1 = Vector2.Zero; #endregion #region GetLocalPosition variables private Vector2 _localPositionTemp = Vector2.Zero; #endregion #region GetBodyMatrix variables private Matrix _bodyMatrixTemp = Matrix.Identity; private Matrix _rotationMatrixTemp = Matrix.Identity; private Matrix _translationMatrixTemp = Matrix.Identity; #endregion #region IIsDisposable Members #if(XNA) [ContentSerializerIgnore] #endif [XmlIgnore] public bool IsDisposed { get { return _isDisposed; } set { _isDisposed = value; } } #endregion } }
using System; using System.Collections.Generic; using BTDB.Buffer; using BTDB.KVDBLayer.BTreeMem; namespace BTDB.KVDBLayer { class InMemoryKeyValueDBTransaction : IKeyValueDBTransaction { readonly InMemoryKeyValueDB _keyValueDB; IBTreeRootNode _btreeRoot; readonly List<NodeIdxPair> _stack = new List<NodeIdxPair>(); byte[] _prefix; bool _writing; readonly bool _readOnly; bool _preapprovedWriting; long _prefixKeyStart; long _prefixKeyCount; long _keyIndex; public InMemoryKeyValueDBTransaction(InMemoryKeyValueDB keyValueDB, IBTreeRootNode btreeRoot, bool writing, bool readOnly) { _preapprovedWriting = writing; _readOnly = readOnly; _keyValueDB = keyValueDB; _btreeRoot = btreeRoot; _prefix = Array.Empty<byte>(); _prefixKeyStart = 0; _prefixKeyCount = -1; _keyIndex = -1; } internal IBTreeRootNode BtreeRoot => _btreeRoot; public void SetKeyPrefix(ByteBuffer prefix) { _prefix = prefix.ToByteArray(); if (_prefix.Length == 0) { _prefixKeyStart = 0; } else { _prefixKeyStart = -1; } _prefixKeyCount = -1; InvalidateCurrentKey(); } public bool FindFirstKey() { return SetKeyIndex(0); } public bool FindLastKey() { var count = GetKeyValueCount(); if (count <= 0) return false; return SetKeyIndex(count - 1); } public bool FindPreviousKey() { if (_keyIndex < 0) return FindLastKey(); if (BtreeRoot.FindPreviousKey(_stack)) { if (CheckPrefixIn(GetCurrentKeyFromStack())) { _keyIndex--; return true; } } InvalidateCurrentKey(); return false; } public bool FindNextKey() { if (_keyIndex < 0) return FindFirstKey(); if (BtreeRoot.FindNextKey(_stack)) { if (CheckPrefixIn(GetCurrentKeyFromStack())) { _keyIndex++; return true; } } InvalidateCurrentKey(); return false; } public FindResult Find(ByteBuffer key) { return BtreeRoot.FindKey(_stack, out _keyIndex, _prefix, key); } public bool CreateOrUpdateKeyValue(ReadOnlySpan<byte> key, ReadOnlySpan<byte> value) { return CreateOrUpdateKeyValue(ByteBuffer.NewAsync(key), ByteBuffer.NewAsync(value)); } public bool CreateOrUpdateKeyValue(ByteBuffer key, ByteBuffer value) { MakeWritable(); var ctx = new CreateOrUpdateCtx { KeyPrefix = _prefix, Key = key, Value = value, Stack = _stack }; BtreeRoot.CreateOrUpdate(ctx); _keyIndex = ctx.KeyIndex; if (ctx.Created && _prefixKeyCount >= 0) _prefixKeyCount++; return ctx.Created; } void MakeWritable() { if (_writing) return; if (_preapprovedWriting) { _writing = true; _preapprovedWriting = false; return; } if (_readOnly) { throw new BTDBTransactionRetryException("Cannot write from readOnly transaction"); } var oldBTreeRoot = BtreeRoot; _btreeRoot = _keyValueDB.MakeWritableTransaction(this, oldBTreeRoot); _btreeRoot.DescriptionForLeaks = _descriptionForLeaks; _writing = true; InvalidateCurrentKey(); } public long GetKeyValueCount() { if (_prefixKeyCount >= 0) return _prefixKeyCount; if (_prefix.Length == 0) { _prefixKeyCount = BtreeRoot.CalcKeyCount(); return _prefixKeyCount; } CalcPrefixKeyStart(); if (_prefixKeyStart < 0) { _prefixKeyCount = 0; return 0; } _prefixKeyCount = BtreeRoot.FindLastWithPrefix(_prefix) - _prefixKeyStart + 1; return _prefixKeyCount; } public long GetKeyIndex() { if (_keyIndex < 0) return -1; CalcPrefixKeyStart(); return _keyIndex - _prefixKeyStart; } void CalcPrefixKeyStart() { if (_prefixKeyStart >= 0) return; if (BtreeRoot.FindKey(new List<NodeIdxPair>(), out _prefixKeyStart, _prefix, ByteBuffer.NewEmpty()) == FindResult.NotFound) { _prefixKeyStart = -1; } } public bool SetKeyIndex(long index) { CalcPrefixKeyStart(); if (_prefixKeyStart < 0) { InvalidateCurrentKey(); return false; } _keyIndex = index + _prefixKeyStart; if (_keyIndex >= BtreeRoot.CalcKeyCount()) { InvalidateCurrentKey(); return false; } BtreeRoot.FillStackByIndex(_stack, _keyIndex); if (_prefixKeyCount >= 0) return true; var key = GetCurrentKeyFromStack(); if (CheckPrefixIn(key)) { return true; } InvalidateCurrentKey(); return false; } bool CheckPrefixIn(ByteBuffer key) { return BTreeRoot.KeyStartsWithPrefix(_prefix, key); } ByteBuffer GetCurrentKeyFromStack() { var nodeIdxPair = _stack[_stack.Count - 1]; return ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx); } public void InvalidateCurrentKey() { _keyIndex = -1; _stack.Clear(); } public bool IsValidKey() { return _keyIndex >= 0; } public ByteBuffer GetKey() { if (!IsValidKey()) return ByteBuffer.NewEmpty(); var wholeKey = GetCurrentKeyFromStack(); return ByteBuffer.NewAsync(wholeKey.Buffer, wholeKey.Offset + _prefix.Length, wholeKey.Length - _prefix.Length); } public ByteBuffer GetKeyIncludingPrefix() { if (!IsValidKey()) return ByteBuffer.NewEmpty(); return GetCurrentKeyFromStack(); } public ByteBuffer GetValue() { if (!IsValidKey()) return ByteBuffer.NewEmpty(); var nodeIdxPair = _stack[_stack.Count - 1]; return ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx); } public ReadOnlySpan<byte> GetValueAsReadOnlySpan() { return GetValue().AsSyncReadOnlySpan(); } void EnsureValidKey() { if (_keyIndex < 0) { throw new InvalidOperationException("Current key is not valid"); } } public void SetValue(ByteBuffer value) { EnsureValidKey(); var keyIndexBackup = _keyIndex; MakeWritable(); if (_keyIndex != keyIndexBackup) { _keyIndex = keyIndexBackup; BtreeRoot.FillStackByIndex(_stack, _keyIndex); } var nodeIdxPair = _stack[_stack.Count - 1]; ((IBTreeLeafNode)nodeIdxPair.Node).SetMemberValue(nodeIdxPair.Idx, value); } public void EraseCurrent() { EnsureValidKey(); var keyIndex = _keyIndex; MakeWritable(); InvalidateCurrentKey(); _prefixKeyCount--; BtreeRoot.EraseRange(keyIndex, keyIndex); } public void EraseAll() { EraseRange(0, long.MaxValue); } public void EraseRange(long firstKeyIndex, long lastKeyIndex) { if (firstKeyIndex < 0) firstKeyIndex = 0; if (lastKeyIndex >= GetKeyValueCount()) lastKeyIndex = _prefixKeyCount - 1; if (lastKeyIndex < firstKeyIndex) return; MakeWritable(); firstKeyIndex += _prefixKeyStart; lastKeyIndex += _prefixKeyStart; InvalidateCurrentKey(); _prefixKeyCount -= lastKeyIndex - firstKeyIndex + 1; BtreeRoot.EraseRange(firstKeyIndex, lastKeyIndex); } public bool IsWriting() { return _writing || _preapprovedWriting; } public bool IsReadOnly() { return _readOnly; } public ulong GetCommitUlong() { return BtreeRoot.CommitUlong; } public void SetCommitUlong(ulong value) { if (BtreeRoot.CommitUlong != value) { MakeWritable(); BtreeRoot.CommitUlong = value; } } public void NextCommitTemporaryCloseTransactionLog() { // There is no transaction log ... } public void Commit() { if (BtreeRoot == null) throw new BTDBException("Transaction already commited or disposed"); InvalidateCurrentKey(); var currentBtreeRoot = _btreeRoot; _btreeRoot = null; if (_preapprovedWriting) { _preapprovedWriting = false; _keyValueDB.RevertWritingTransaction(); } else if (_writing) { _keyValueDB.CommitWritingTransaction(currentBtreeRoot); _writing = false; } } public void Dispose() { if (_writing || _preapprovedWriting) { _keyValueDB.RevertWritingTransaction(); _writing = false; _preapprovedWriting = false; } _btreeRoot = null; } public long GetTransactionNumber() { return _btreeRoot.TransactionId; } public KeyValuePair<uint, uint> GetStorageSizeOfCurrentKey() { var nodeIdxPair = _stack[_stack.Count - 1]; return new KeyValuePair<uint, uint>( (uint)((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx).Length, (uint)((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx).Length); } public byte[] GetKeyPrefix() { return _prefix; } public ulong GetUlong(uint idx) { return BtreeRoot.GetUlong(idx); } public void SetUlong(uint idx, ulong value) { if (BtreeRoot.GetUlong(idx) != value) { MakeWritable(); BtreeRoot.SetUlong(idx, value); } } public uint GetUlongCount() { return BtreeRoot.GetUlongCount(); } string _descriptionForLeaks; public string DescriptionForLeaks { get { return _descriptionForLeaks; } set { _descriptionForLeaks = value; if (_preapprovedWriting || _writing) _btreeRoot.DescriptionForLeaks = value; } } public IKeyValueDB Owner => _keyValueDB; public bool RollbackAdvised { get; set; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Operations operations. /// </summary> internal partial class Operations : IServiceOperations<RecoveryServicesClient>, IOperations { /// <summary> /// Initializes a new instance of the Operations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal Operations(RecoveryServicesClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesClient /// </summary> public RecoveryServicesClient Client { get; private set; } /// <summary> /// Returns the list of available operations. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ClientDiscoveryValueForSingleApi>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2016-12-01"; string apiVersion1 = "2016-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion1", apiVersion1); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/operations").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (apiVersion1 != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion1))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ClientDiscoveryValueForSingleApi>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ClientDiscoveryValueForSingleApi>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Returns the list of available operations. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ClientDiscoveryValueForSingleApi>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ClientDiscoveryValueForSingleApi>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ClientDiscoveryValueForSingleApi>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography.ECC; using Neo.IO; using Neo.IO.Json; using Neo.Ledger; using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.SmartContract.Native; using Neo.SmartContract.Native.Tokens; using Neo.VM; using Neo.Wallets; using System; using System.Numerics; namespace Neo.UnitTests.Network.P2P.Payloads { [TestClass] public class UT_Transaction { Transaction uut; [TestInitialize] public void TestSetup() { TestBlockchain.InitializeMockNeoSystem(); uut = new Transaction(); } [TestMethod] public void Script_Get() { uut.Script.Should().BeNull(); } [TestMethod] public void Script_Set() { byte[] val = TestUtils.GetByteArray(32, 0x42); uut.Script = val; uut.Script.Length.Should().Be(32); for (int i = 0; i < val.Length; i++) { uut.Script[i].Should().Be(val[i]); } } [TestMethod] public void Gas_Get() { uut.SystemFee.Should().Be(0); } [TestMethod] public void Gas_Set() { long val = 4200000000; uut.SystemFee = val; uut.SystemFee.Should().Be(val); } [TestMethod] public void Size_Get() { uut.Script = TestUtils.GetByteArray(32, 0x42); uut.Sender = UInt160.Zero; uut.Attributes = new TransactionAttribute[0]; uut.Cosigners = new Cosigner[0]; uut.Witnesses = new[] { new Witness { InvocationScript = new byte[0], VerificationScript = new byte[0] } }; uut.Version.Should().Be(0); uut.Script.Length.Should().Be(32); uut.Script.GetVarSize().Should().Be(33); uut.Size.Should().Be(83); } [TestMethod] public void FeeIsMultiSigContract() { var walletA = TestUtils.GenerateTestWallet(); var walletB = TestUtils.GenerateTestWallet(); var snapshot = Blockchain.Singleton.GetSnapshot(); using (var unlockA = walletA.Unlock("123")) using (var unlockB = walletB.Unlock("123")) { var a = walletA.CreateAccount(); var b = walletB.CreateAccount(); var multiSignContract = Contract.CreateMultiSigContract(2, new ECPoint[] { a.GetKey().PublicKey, b.GetKey().PublicKey }); walletA.CreateAccount(multiSignContract, a.GetKey()); var acc = walletB.CreateAccount(multiSignContract, b.GetKey()); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem { Value = new Nep5AccountState().ToByteArray() }); entry.Value = new Nep5AccountState() { Balance = 10000 * NativeContract.GAS.Factor } .ToByteArray(); snapshot.Commit(); // Make transaction var tx = walletA.MakeTransaction(new TransferOutput[] { new TransferOutput() { AssetId = NativeContract.GAS.Hash, ScriptHash = acc.ScriptHash, Value = new BigDecimal(1,8) } }, acc.ScriptHash); Assert.IsNotNull(tx); // Sign var data = new ContractParametersContext(tx); Assert.IsTrue(walletA.Sign(data)); Assert.IsTrue(walletB.Sign(data)); Assert.IsTrue(data.Completed); tx.Witnesses = data.GetWitnesses(); // Fast check Assert.IsTrue(tx.VerifyWitnesses(snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using (ApplicationEngine engine = new ApplicationEngine(TriggerType.Verification, tx, snapshot, tx.NetworkFee, false)) { engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().ToBoolean()); verificationGas += engine.GasConsumed; } } var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); Assert.AreEqual(verificationGas, 2000570); Assert.AreEqual(sizeGas, 359000); Assert.AreEqual(tx.NetworkFee, 2359570); } } [TestMethod] public void FeeIsSignatureContractDetailed() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = Blockchain.Singleton.GetSnapshot(); using (var unlock = wallet.Unlock("123")) { var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem { Value = new Nep5AccountState().ToByteArray() }); entry.Value = new Nep5AccountState() { Balance = 10000 * NativeContract.GAS.Factor } .ToByteArray(); snapshot.Commit(); // Make transaction // self-transfer of 1e-8 GAS var tx = wallet.MakeTransaction(new TransferOutput[] { new TransferOutput() { AssetId = NativeContract.GAS.Hash, ScriptHash = acc.ScriptHash, Value = new BigDecimal(1,8) } }, acc.ScriptHash); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // check pre-computed network fee (already guessing signature sizes) tx.NetworkFee.Should().Be(1258270); // ---- // Sign // ---- var data = new ContractParametersContext(tx); // 'from' is always required as witness // if not included on cosigner with a scope, its scope should be considered 'CalledByEntry' data.ScriptHashes.Count.Should().Be(1); data.ScriptHashes[0].Should().BeEquivalentTo(acc.ScriptHash); // will sign tx bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); tx.Witnesses.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using (ApplicationEngine engine = new ApplicationEngine(TriggerType.Verification, tx, snapshot, tx.NetworkFee, false)) { engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().ToBoolean()); verificationGas += engine.GasConsumed; } } Assert.AreEqual(verificationGas, 1000270); // ------------------ // check tx_size cost // ------------------ Assert.AreEqual(tx.Size, 258); // will verify tx size, step by step // Part I Assert.AreEqual(Transaction.HeaderSize, 45); // Part II Assert.AreEqual(tx.Attributes.GetVarSize(), 1); Assert.AreEqual(tx.Attributes.Length, 0); Assert.AreEqual(tx.Cosigners.Length, 1); Assert.AreEqual(tx.Cosigners.GetVarSize(), 22); // Note that Data size and Usage size are different (because of first byte on GetVarSize()) Assert.AreEqual(tx.Cosigners[0].Size, 21); // Part III Assert.AreEqual(tx.Script.GetVarSize(), 82); // Part IV Assert.AreEqual(tx.Witnesses.GetVarSize(), 108); // I + II + III + IV Assert.AreEqual(tx.Size, 45 + 23 + 82 + 108); Assert.AreEqual(NativeContract.Policy.GetFeePerByte(snapshot), 1000); var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); Assert.AreEqual(sizeGas, 258000); // final check on sum: verification_cost + tx_size Assert.AreEqual(verificationGas + sizeGas, 1258270); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } } [TestMethod] public void FeeIsSignatureContract_TestScope_Global() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = Blockchain.Singleton.GetSnapshot(); // no password on this wallet using (var unlock = wallet.Unlock("")) { var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem { Value = new Nep5AccountState().ToByteArray() }); entry.Value = new Nep5AccountState() { Balance = 10000 * NativeContract.GAS.Factor } .ToByteArray(); snapshot.Commit(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.THROWIFNOT); script = sb.ToArray(); } // trying global scope var cosigners = new Cosigner[]{ new Cosigner { Account = acc.ScriptHash, Scopes = WitnessScope.Global } }; // using this... var tx = wallet.MakeTransaction(script, acc.ScriptHash, new TransactionAttribute[0], cosigners); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // ---- // Sign // ---- var data = new ContractParametersContext(tx); bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); tx.Witnesses.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using (ApplicationEngine engine = new ApplicationEngine(TriggerType.Verification, tx, snapshot, tx.NetworkFee, false)) { engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().ToBoolean()); verificationGas += engine.GasConsumed; } } // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size Assert.AreEqual(verificationGas + sizeGas, 1258270); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } } [TestMethod] public void FeeIsSignatureContract_TestScope_CurrentHash_GAS() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = Blockchain.Singleton.GetSnapshot(); // no password on this wallet using (var unlock = wallet.Unlock("")) { var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem { Value = new Nep5AccountState().ToByteArray() }); entry.Value = new Nep5AccountState() { Balance = 10000 * NativeContract.GAS.Factor } .ToByteArray(); snapshot.Commit(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.THROWIFNOT); script = sb.ToArray(); } // trying global scope var cosigners = new Cosigner[]{ new Cosigner { Account = acc.ScriptHash, Scopes = WitnessScope.CustomContracts, AllowedContracts = new[] { NativeContract.GAS.Hash } } }; // using this... var tx = wallet.MakeTransaction(script, acc.ScriptHash, new TransactionAttribute[0], cosigners); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // ---- // Sign // ---- var data = new ContractParametersContext(tx); bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); tx.Witnesses.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using (ApplicationEngine engine = new ApplicationEngine(TriggerType.Verification, tx, snapshot, tx.NetworkFee, false)) { engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().ToBoolean()); verificationGas += engine.GasConsumed; } } // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size Assert.AreEqual(verificationGas + sizeGas, 1279270); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } } [TestMethod] public void FeeIsSignatureContract_TestScope_CalledByEntry_Plus_GAS() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = Blockchain.Singleton.GetSnapshot(); // no password on this wallet using (var unlock = wallet.Unlock("")) { var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem { Value = new Nep5AccountState().ToByteArray() }); entry.Value = new Nep5AccountState() { Balance = 10000 * NativeContract.GAS.Factor } .ToByteArray(); snapshot.Commit(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.THROWIFNOT); script = sb.ToArray(); } // trying CalledByEntry together with GAS var cosigners = new Cosigner[]{ new Cosigner { Account = acc.ScriptHash, // This combination is supposed to actually be an OR, // where it's valid in both Entry and also for Custom hash provided (in any execution level) // it would be better to test this in the future including situations where a deeper call level uses this custom witness successfully Scopes = WitnessScope.CustomContracts | WitnessScope.CalledByEntry, AllowedContracts = new[] { NativeContract.GAS.Hash } } }; // using this... var tx = wallet.MakeTransaction(script, acc.ScriptHash, new TransactionAttribute[0], cosigners); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // ---- // Sign // ---- var data = new ContractParametersContext(tx); bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); tx.Witnesses.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using (ApplicationEngine engine = new ApplicationEngine(TriggerType.Verification, tx, snapshot, tx.NetworkFee, false)) { engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().ToBoolean()); verificationGas += engine.GasConsumed; } } // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size Assert.AreEqual(verificationGas + sizeGas, 1279270); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } } [TestMethod] public void FeeIsSignatureContract_TestScope_CurrentHash_NEO_FAULT() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = Blockchain.Singleton.GetSnapshot(); // no password on this wallet using (var unlock = wallet.Unlock("")) { var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem { Value = new Nep5AccountState().ToByteArray() }); entry.Value = new Nep5AccountState() { Balance = 10000 * NativeContract.GAS.Factor } .ToByteArray(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.THROWIFNOT); script = sb.ToArray(); } // trying global scope var cosigners = new Cosigner[]{ new Cosigner { Account = acc.ScriptHash, Scopes = WitnessScope.CustomContracts, AllowedContracts = new[] { NativeContract.NEO.Hash } } }; // using this... // expects FAULT on execution of 'transfer' Application script // due to lack of a valid witness validation Transaction tx = null; Assert.ThrowsException<InvalidOperationException>(() => tx = wallet.MakeTransaction(script, acc.ScriptHash, new TransactionAttribute[0], cosigners)); Assert.IsNull(tx); } } [TestMethod] public void FeeIsSignatureContract_TestScope_CurrentHash_NEO_GAS() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = Blockchain.Singleton.GetSnapshot(); // no password on this wallet using (var unlock = wallet.Unlock("")) { var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem { Value = new Nep5AccountState().ToByteArray() }); entry.Value = new Nep5AccountState() { Balance = 10000 * NativeContract.GAS.Factor } .ToByteArray(); snapshot.Commit(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.THROWIFNOT); script = sb.ToArray(); } // trying two custom hashes, for same target account var cosigners = new Cosigner[]{ new Cosigner { Account = acc.ScriptHash, Scopes = WitnessScope.CustomContracts, AllowedContracts = new[] { NativeContract.NEO.Hash, NativeContract.GAS.Hash } } }; // using this... var tx = wallet.MakeTransaction(script, acc.ScriptHash, new TransactionAttribute[0], cosigners); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // ---- // Sign // ---- var data = new ContractParametersContext(tx); bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); // only a single witness should exist tx.Witnesses.Length.Should().Be(1); // no attributes must exist tx.Attributes.Length.Should().Be(0); // one cosigner must exist tx.Cosigners.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using (ApplicationEngine engine = new ApplicationEngine(TriggerType.Verification, tx, snapshot, tx.NetworkFee, false)) { engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().ToBoolean()); verificationGas += engine.GasConsumed; } } // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size Assert.AreEqual(verificationGas + sizeGas, 1299270); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } } [TestMethod] public void FeeIsSignatureContract_TestScope_NoScopeFAULT() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = Blockchain.Singleton.GetSnapshot(); // no password on this wallet using (var unlock = wallet.Unlock("")) { var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem { Value = new Nep5AccountState().ToByteArray() }); entry.Value = new Nep5AccountState() { Balance = 10000 * NativeContract.GAS.Factor } .ToByteArray(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.THROWIFNOT); script = sb.ToArray(); } // trying with no scope var attributes = new TransactionAttribute[] { }; var cosigners = new Cosigner[] { }; // using this... // expects FAULT on execution of 'transfer' Application script // due to lack of a valid witness validation Transaction tx = null; Assert.ThrowsException<InvalidOperationException>(() => tx = wallet.MakeTransaction(script, acc.ScriptHash, attributes, cosigners)); Assert.IsNull(tx); } } [TestMethod] public void Transaction_Reverify_Hashes_Length_Unequal_To_Witnesses_Length() { var snapshot = Blockchain.Singleton.GetSnapshot(); Transaction txSimple = new Transaction { Version = 0x00, Nonce = 0x01020304, Sender = UInt160.Zero, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, Attributes = new TransactionAttribute[0] { }, Cosigners = new Cosigner[] { new Cosigner { Account = UInt160.Parse("0x0001020304050607080900010203040506070809"), Scopes = WitnessScope.Global } }, Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[0] { } }; UInt160[] hashes = txSimple.GetScriptHashesForVerifying(snapshot); Assert.AreEqual(2, hashes.Length); Assert.IsFalse(txSimple.Reverify(snapshot, BigInteger.Zero)); } [TestMethod] public void Transaction_Serialize_Deserialize_Simple() { // good and simple transaction Transaction txSimple = new Transaction { Version = 0x00, Nonce = 0x01020304, Sender = UInt160.Zero, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, Attributes = new TransactionAttribute[0] { }, Cosigners = new Cosigner[0] { }, Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[0] { } }; byte[] sTx = txSimple.ToArray(); // detailed hexstring info (basic checking) sTx.ToHexString().Should().Be("00" + // version "04030201" + // nonce "0000000000000000000000000000000000000000" + // sender "00e1f50500000000" + // system fee (1 GAS) "0100000000000000" + // network fee (1 satoshi) "04030201" + // timelimit "00" + // no attributes "00" + // no cosigners "0151" + // push1 script "00"); // no witnesses // try to deserialize Transaction tx2 = Neo.IO.Helper.AsSerializable<Transaction>(sTx); tx2.Version.Should().Be(0x00); tx2.Nonce.Should().Be(0x01020304); tx2.Sender.Should().Be(UInt160.Zero); tx2.SystemFee.Should().Be(0x0000000005f5e100); // 1 GAS (long)BigInteger.Pow(10, 8) tx2.NetworkFee.Should().Be(0x0000000000000001); tx2.ValidUntilBlock.Should().Be(0x01020304); tx2.Attributes.Should().BeEquivalentTo(new TransactionAttribute[0] { }); tx2.Cosigners.Should().BeEquivalentTo(new Cosigner[0] { }); tx2.Script.Should().BeEquivalentTo(new byte[] { (byte)OpCode.PUSH1 }); tx2.Witnesses.Should().BeEquivalentTo(new Witness[0] { }); } [TestMethod] public void Transaction_Serialize_Deserialize_DistinctCosigners() { // cosigners must be distinct (regarding account) Transaction txDoubleCosigners = new Transaction { Version = 0x00, Nonce = 0x01020304, Sender = UInt160.Zero, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, Attributes = new TransactionAttribute[0] { }, Cosigners = new Cosigner[] { new Cosigner { Account = UInt160.Parse("0x0001020304050607080900010203040506070809"), Scopes = WitnessScope.Global }, new Cosigner { Account = UInt160.Parse("0x0001020304050607080900010203040506070809"), // same account as above Scopes = WitnessScope.CalledByEntry // different scope, but still, same account (cannot do that) } }, Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[0] { } }; byte[] sTx = txDoubleCosigners.ToArray(); // no need for detailed hexstring here (see basic tests for it) sTx.ToHexString().Should().Be("0004030201000000000000000000000000000000000000000000e1f505000000000100000000000000040302010002090807060504030201000908070605040302010000090807060504030201000908070605040302010001015100"); // back to transaction (should fail, due to non-distinct cosigners) Transaction tx2 = null; Assert.ThrowsException<FormatException>(() => tx2 = Neo.IO.Helper.AsSerializable<Transaction>(sTx) ); Assert.IsNull(tx2); } [TestMethod] public void Transaction_Serialize_Deserialize_MaxSizeCosigners() { // cosigners must respect count int maxCosigners = 16; // -------------------------------------- // this should pass (respecting max size) var cosigners1 = new Cosigner[maxCosigners]; for (int i = 0; i < cosigners1.Length; i++) { string hex = i.ToString("X4"); while (hex.Length < 40) hex = hex.Insert(0, "0"); cosigners1[i] = new Cosigner { Account = UInt160.Parse(hex) }; } Transaction txCosigners1 = new Transaction { Version = 0x00, Nonce = 0x01020304, Sender = UInt160.Zero, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, Attributes = new TransactionAttribute[0] { }, Cosigners = cosigners1, // max + 1 (should fail) Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[0] { } }; byte[] sTx1 = txCosigners1.ToArray(); // back to transaction (should fail, due to non-distinct cosigners) Transaction tx1 = Neo.IO.Helper.AsSerializable<Transaction>(sTx1); Assert.IsNotNull(tx1); // ---------------------------- // this should fail (max + 1) var cosigners = new Cosigner[maxCosigners + 1]; for (var i = 0; i < maxCosigners + 1; i++) { string hex = i.ToString("X4"); while (hex.Length < 40) hex = hex.Insert(0, "0"); cosigners[i] = new Cosigner { Account = UInt160.Parse(hex) }; } Transaction txCosigners = new Transaction { Version = 0x00, Nonce = 0x01020304, Sender = UInt160.Zero, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, Attributes = new TransactionAttribute[0] { }, Cosigners = cosigners, // max + 1 (should fail) Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[0] { } }; byte[] sTx2 = txCosigners.ToArray(); // back to transaction (should fail, due to non-distinct cosigners) Transaction tx2 = null; Assert.ThrowsException<FormatException>(() => tx2 = Neo.IO.Helper.AsSerializable<Transaction>(sTx2) ); Assert.IsNull(tx2); } [TestMethod] public void FeeIsSignatureContract_TestScope_Global_Default() { // Global is supposed to be default Cosigner cosigner = new Cosigner(); cosigner.Scopes.Should().Be(WitnessScope.Global); var wallet = TestUtils.GenerateTestWallet(); var snapshot = Blockchain.Singleton.GetSnapshot(); // no password on this wallet using (var unlock = wallet.Unlock("")) { var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem { Value = new Nep5AccountState().ToByteArray() }); entry.Value = new Nep5AccountState() { Balance = 10000 * NativeContract.GAS.Factor } .ToByteArray(); snapshot.Commit(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.THROWIFNOT); script = sb.ToArray(); } // default to global scope var cosigners = new Cosigner[]{ new Cosigner { Account = acc.ScriptHash } }; // using this... var tx = wallet.MakeTransaction(script, acc.ScriptHash, new TransactionAttribute[0], cosigners); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // ---- // Sign // ---- var data = new ContractParametersContext(tx); bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); tx.Witnesses.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using (ApplicationEngine engine = new ApplicationEngine(TriggerType.Verification, tx, snapshot, tx.NetworkFee, false)) { engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().ToBoolean()); verificationGas += engine.GasConsumed; } } // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size Assert.AreEqual(verificationGas + sizeGas, 1258270); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } } [TestMethod] public void ToJson() { uut.Script = TestUtils.GetByteArray(32, 0x42); uut.Sender = UInt160.Zero; uut.SystemFee = 4200000000; uut.Attributes = new TransactionAttribute[] { }; uut.Cosigners = new Cosigner[] { }; uut.Witnesses = new[] { new Witness { InvocationScript = new byte[0], VerificationScript = new byte[0] } }; JObject jObj = uut.ToJson(); jObj.Should().NotBeNull(); jObj["hash"].AsString().Should().Be("0x11e3ee692015f0cd3cb8b6db7a4fc37568540f020cb9ca497a9917c81f20b62f"); jObj["size"].AsNumber().Should().Be(83); jObj["version"].AsNumber().Should().Be(0); ((JArray)jObj["attributes"]).Count.Should().Be(0); ((JArray)jObj["cosigners"]).Count.Should().Be(0); jObj["net_fee"].AsString().Should().Be("0"); jObj["script"].AsString().Should().Be("QiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA="); jObj["sys_fee"].AsString().Should().Be("4200000000"); } } }
// 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 Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked001.checked001 { // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myClass { public int GetMaxInt() { return int.MaxValue; } } public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myClass(); int x = 0; try { checked { x = (int)d.GetMaxInt() + 1; } } catch (System.OverflowException) { return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked002.checked002 { // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myClass { public int GetMaxInt { get { return int.MaxValue; } set { } } } public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myClass(); int x = 0; try { checked { x = (int)d.GetMaxInt++; } } catch (System.OverflowException) { if (x == 0) { return 0; } else { return 1; } } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked003.checked003 { public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = int.MaxValue; byte x = 0; try { checked { //this will not throw, because we don't pass the fact that we are in a checked context x = (byte)d; } } catch (System.OverflowException) { if (x == 0) { return 0; } else { return 1; } } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked004.checked004 { public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = int.MaxValue; int x = 0; try { checked { //This will not work by our current design because we will introduce an implicit conversion to byte x = d + 1; } } catch (System.OverflowException) { if (x == 0) { return 0; } else { return 1; } } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked005.checked005 { public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { int rez = 0, tests = 0; bool exception = false; //signals if the exception is thrown dynamic d = null; dynamic d2 = null; // ++ on byte in checked context tests++; exception = false; d = byte.MaxValue; try { checked { d++; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // -- on char in checked context tests++; exception = false; d = char.MinValue; try { char rchar = checked(d--); } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // - on ushort in checked context tests++; exception = false; d = ushort.MaxValue; try { checked { ushort rez2 = (ushort)-d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // + on sbyte and int tests++; exception = false; d = sbyte.MaxValue; d2 = int.MaxValue; try { checked { int rez2 = d + d2; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // - on uint and ushort tests++; exception = false; d = uint.MaxValue; d2 = ushort.MinValue; try { checked { uint rez3 = d2 - d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // -= on ushort and ushort tests++; exception = false; d = ushort.MaxValue; d2 = ushort.MinValue; try { checked { d2 -= d; exception = true; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // * on char and long tests++; exception = false; d = char.MaxValue; d2 = long.MinValue; try { checked { long rez3 = d2 * d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // / on char and long tests++; exception = false; d = int.MinValue; d2 = -1; try { long rez4 = checked(d / d2); } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from int to byte tests++; exception = false; d = int.MaxValue; try { checked { byte b = (byte)d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from float to char tests++; exception = false; d = float.MaxValue; try { checked { char b = (char)d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from float to char tests++; exception = false; d = double.MaxValue; try { checked { ushort b = (ushort)d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } return rez == tests ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked006.checked006 { public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { int rez = 0, tests = 0; bool exception = true; //signals if the exception is thrown dynamic d = null; dynamic d2 = null; // ++ on byte in unchecked context tests++; exception = true; d = byte.MaxValue; try { unchecked { d++; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // -- on char in unchecked context tests++; exception = true; d = char.MinValue; try { char rchar = unchecked(d--); } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // - on ushort in unchecked context tests++; exception = true; d = ushort.MaxValue; try { unchecked { ushort rez2 = (ushort)-d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // + on sbyte and int tests++; exception = true; d = sbyte.MaxValue; d2 = int.MaxValue; try { unchecked { int rez2 = d + d2; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // - on uint and ushort tests++; exception = true; d = uint.MaxValue; d2 = ushort.MinValue; try { unchecked { uint rez3 = d2 - d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // -= on uint and ushort tests++; exception = true; d = ushort.MaxValue; d2 = ushort.MinValue; try { unchecked { d2 -= d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // * on char and long tests++; exception = true; d = char.MaxValue; d2 = long.MinValue; try { unchecked { long rez3 = d2 * d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // / on char and long -> it is implemented such that this will throw even in an unchecked context. tests++; exception = false; d = int.MinValue; d2 = -1; try { long rez4 = unchecked(d / d2); } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from int to byte tests++; exception = true; d = int.MaxValue; try { unchecked { byte b = (byte)d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from float to char tests++; exception = true; d = float.MaxValue; try { unchecked { char b = (char)d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from float to char tests++; exception = true; d = double.MaxValue; try { unchecked { ushort b = (ushort)d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } return rez == tests ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked008.checked008 { // <Title>Tests checked block</Title> // <Description> Compiler not passing checked flag in complex operators // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=warning>\(16,17\).*CS0649</Expects> //<Expects Status=warning>\(17,11\).*CS0414</Expects> //<Expects Status=warning>\(18,20\).*CS0414</Expects> //<Expects Status=success></Expects> // <Code> public class Test { public byte X; private sbyte _X1 = sbyte.MinValue; private ushort _Y = ushort.MinValue; protected short Y1 = short.MaxValue; internal uint Z = 0; protected internal ulong Q = ulong.MaxValue; protected long C = long.MinValue; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int ret = 0; dynamic a = new Test(); try { var v0 = checked(a.X1 -= 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("byte"); // expected } try { var v1 = checked(a.X1 -= 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("sbyte"); // expected } try { var v2 = checked(a.Y -= 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("ushort"); // expected } try { var v2 = checked(a.Y1 += 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("short"); // expected } try { var v3 = checked(a.Z -= 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("uint"); // expected } try { var v4 = checked(a.Q += 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("ulong max"); // expected } try { var v5 = checked(a.C -= 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("long min"); // expected } System.Console.WriteLine(ret); return ret == 0 ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.do001.do001 { // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; do { x++; if (x > 2) return 0; } while ((bool)d); return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.do002.do002 { // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public static bool operator true(myIf f) { return true; } public static bool operator false(myIf f) { return false; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; do { x++; if (x > 2) return 0; } while (d); return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.do003.do003 { // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool MyMethod() { return true; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; do { x++; if (x > 2) return 0; } while (d.MyMethod()); return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if001.if001 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if ((bool)d) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if002.if002 { // <Title>Tests if statements</Title> // <Description> // Remove the comments when the exception is known // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static implicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if (d) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if003.if003 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public static bool operator true(myIf f) { return true; } public static bool operator false(myIf f) { return false; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if (d) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if004.if004 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if ((bool)d) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if005.if005 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } public static bool operator true(myIf f) { return false; } public static bool operator false(myIf f) { return true; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if ((bool)d) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if006.if006 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public bool MyMethod() { return this.value; } public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if (d.MyMethod()) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if007.if007 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public object MyMethod() { return this.value; } public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if (d.MyMethod()) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if008.if008 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public object MyMethod() { Test.Status = 1; return !this.value; } public static explicit operator bool (myIf f) { return f.value; } } public class Test { public static int Status = 0; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if ((bool)d || (bool)d.MyMethod()) { if (Test.Status == 0) //We should have short-circuited the second call return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if009.if009 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public object MyMethod() { Test.Status = 1; return !this.value; } public static explicit operator bool (myIf f) { return f.value; } } public class Test { public static int Status = 0; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if ((bool)d | (bool)d.MyMethod()) { if (Test.Status == 1) //We should have short-circuited the second call return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if010.if010 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); bool boo = true; if ((bool)d && (bool)boo) { return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.switch001.switch001 { public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = "foo"; switch ((string)d) { case "foo": return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.switch002.switch002 { public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = 1; switch ((int?)d) { case 1: return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary001.ternary001 { // <Title>Tests ternary operator statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); return (bool)d ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary002.ternary002 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public static bool operator true(myIf f) { return true; } public static bool operator false(myIf f) { return false; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); return d ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary003.ternary003 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static implicit operator bool (myIf f) { return f.value; } public static bool operator true(myIf f) { return false; } public static bool operator false(myIf f) { return true; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); return d ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary004.ternary004 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public bool MyMethod() { return this.value; } public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); return d.MyMethod() ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary005.ternary005 { // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); bool boo = true; return ((bool)d && (bool)boo) ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unchecked001.unchecked001 { // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myClass { public int GetMaxInt() { return int.MaxValue; } } public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myClass(); int x = 0; try { unchecked { x = (int)d.GetMaxInt() + 1; } } catch (System.OverflowException) { return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unchecked002.unchecked002 { // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myClass { public int GetMaxInt() { return int.MaxValue; } } public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myClass(); int x = 0; try { unchecked { x = (int)d.GetMaxInt() * 3; } } catch (System.OverflowException) { return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unchecked003.unchecked003 { public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { unchecked { dynamic c_byte = (byte?)(-123); var rez = c_byte == (byte?)-123; return rez ? 0 : 1; } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unsfe001.unsfe001 { // <Title>If def</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Foo { public void Set() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { { dynamic d = new Foo(); d.Set(); } if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.while001.while001 { // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static implicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; while (d) { x++; if (x > 2) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.while002.while002 { // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public static bool operator true(myIf f) { return true; } public static bool operator false(myIf f) { return false; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; while (d) { x++; if (x > 2) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.while003.while003 { // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool MyMethod() { return true; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; while (d.MyMethod()) { x++; if (x > 2) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield001.yield001 { // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class MyClass { public IEnumerable<int> Foo() { dynamic d = 1; yield return d; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass d = new MyClass(); foreach (var item in d.Foo()) { if (item != 1) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield002.yield002 { // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class MyClass { public IEnumerable<dynamic> Foo() { dynamic d = 1; yield return d; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass d = new MyClass(); foreach (var item in d.Foo()) { if ((int)item != 1) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield003.yield003 { // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class MyClass { public IEnumerable<dynamic> Foo() { object d = 1; yield return d; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass d = new MyClass(); foreach (var item in d.Foo()) { if ((int)item != 1) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield004.yield004 { // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class MyClass { public IEnumerable<object> Foo() { dynamic d = 1; yield return d; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass d = new MyClass(); foreach (var item in d.Foo()) { if ((int)item != 1) return 1; } return 0; } } // </Code> }
// *********************************************************************** // Copyright (c) 2008 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 NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { /// <summary> /// ThrowsConstraint is used to test the exception thrown by /// a delegate by applying a constraint to it. /// </summary> public class ThrowsConstraint : PrefixConstraint { private Exception caughtException; /// <summary> /// Initializes a new instance of the <see cref="ThrowsConstraint"/> class, /// using a constraint to be applied to the exception. /// </summary> /// <param name="baseConstraint">A constraint to apply to the caught exception.</param> public ThrowsConstraint(IConstraint baseConstraint) : base(baseConstraint) { } /// <summary> /// Get the actual exception thrown - used by Assert.Throws. /// </summary> public Exception ActualException { get { return caughtException; } } #region Constraint Overrides /// <summary> /// Gets text describing a constraint /// </summary> public override string Description { get { return BaseConstraint.Description; } } /// <summary> /// Executes the code of the delegate and captures any exception. /// If a non-null base constraint was provided, it applies that /// constraint to the exception. /// </summary> /// <param name="actual">A delegate representing the code to be tested</param> /// <returns>True if an exception is thrown and the constraint succeeds, otherwise false</returns> public override ConstraintResult ApplyTo<TActual>(TActual actual) { //TestDelegate code = actual as TestDelegate; //if (code == null) // throw new ArgumentException( // string.Format("The actual value must be a TestDelegate but was {0}", actual.GetType().Name), "actual"); //caughtException = null; //try //{ // code(); //} //catch (Exception ex) //{ // caughtException = ex; //} caughtException = ExceptionInterceptor.Intercept(actual); return new ThrowsConstraintResult( this, caughtException, caughtException != null ? BaseConstraint.ApplyTo(caughtException) : null); } /// <summary> /// Converts an ActualValueDelegate to a TestDelegate /// before calling the primary overload. /// </summary> /// <param name="del"></param> /// <returns></returns> public override ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del) { //TestDelegate testDelegate = new TestDelegate(delegate { del(); }); //return ApplyTo((object)testDelegate); return ApplyTo(new GenericInvocationDescriptor<TActual>(del)); } #endregion #region Nested Result Class private class ThrowsConstraintResult : ConstraintResult { private readonly ConstraintResult baseResult; public ThrowsConstraintResult(ThrowsConstraint constraint, Exception caughtException, ConstraintResult baseResult) : base(constraint, caughtException) { if (caughtException != null && baseResult.IsSuccess) Status = ConstraintStatus.Success; else Status = ConstraintStatus.Failure; this.baseResult = baseResult; } /// <summary> /// Write the actual value for a failing constraint test to a /// MessageWriter. This override only handles the special message /// used when an exception is expected but none is thrown. /// </summary> /// <param name="writer">The writer on which the actual value is displayed</param> public override void WriteActualValueTo(MessageWriter writer) { if (ActualValue == null) writer.Write("no exception thrown"); else baseResult.WriteActualValueTo(writer); } } #endregion #region ExceptionInterceptor internal class ExceptionInterceptor { private ExceptionInterceptor() { } internal static Exception Intercept(object invocation) { var invocationDescriptor = GetInvocationDescriptor(invocation); #if ASYNC if (AsyncInvocationRegion.IsAsyncOperation(invocationDescriptor.Delegate)) { using (var region = AsyncInvocationRegion.Create(invocationDescriptor.Delegate)) { try { object result = invocationDescriptor.Invoke(); region.WaitForPendingOperationsToComplete(result); return null; } catch (Exception ex) { return ex; } } } else #endif { using (new TestExecutionContext.IsolatedContext()) { try { invocationDescriptor.Invoke(); return null; } catch (Exception ex) { return ex; } } } } private static IInvocationDescriptor GetInvocationDescriptor(object actual) { var invocationDescriptor = actual as IInvocationDescriptor; if (invocationDescriptor == null) { var testDelegate = actual as TestDelegate; if (testDelegate != null) { invocationDescriptor = new VoidInvocationDescriptor(testDelegate); } #if ASYNC else { var asyncTestDelegate = actual as AsyncTestDelegate; if (asyncTestDelegate != null) { invocationDescriptor = new GenericInvocationDescriptor<System.Threading.Tasks.Task>(() => asyncTestDelegate()); } } #endif } if (invocationDescriptor == null) throw new ArgumentException( String.Format( "The actual value must be a TestDelegate or AsyncTestDelegate but was {0}", actual.GetType().Name), "actual"); return invocationDescriptor; } } #endregion #region InvocationDescriptor internal class GenericInvocationDescriptor<T> : IInvocationDescriptor { private readonly ActualValueDelegate<T> _del; public GenericInvocationDescriptor(ActualValueDelegate<T> del) { _del = del; } public object Invoke() { return _del(); } public Delegate Delegate { get { return _del; } } } private interface IInvocationDescriptor { Delegate Delegate { get; } object Invoke(); } private class VoidInvocationDescriptor : IInvocationDescriptor { private readonly TestDelegate _del; public VoidInvocationDescriptor(TestDelegate del) { _del = del; } public object Invoke() { _del(); return null; } public Delegate Delegate { get { return _del; } } } #endregion } }
// // MonoTests.System.Xml.XPathNavigatorCommonTests // // Author: // Atsushi Enomoto <ginga@kit.hi-ho.ne.jp> // // (C) 2003 Atsushi Enomoto // using System; using System.Xml; using System.Xml.XPath; using NUnit.Framework; namespace MonoTests.System.Xml { [TestFixture] public class XPathNavigatorCommonTests : Assertion { XmlDocument document; XPathNavigator nav; XPathDocument xpathDocument; [SetUp] public void GetReady () { document = new XmlDocument (); } private XPathNavigator GetXmlDocumentNavigator (string xml) { document.LoadXml (xml); return document.CreateNavigator (); } private XPathNavigator GetXPathDocumentNavigator (XmlNode node) { XmlNodeReader xr = new XmlNodeReader (node); xpathDocument = new XPathDocument (xr); return xpathDocument.CreateNavigator (); } private void AssertNavigator (XPathNavigator nav, XPathNodeType type, string prefix, string localName, string ns, string name, string value, bool hasAttributes, bool hasChildren, bool isEmptyElement) { AssertEquals ("NodeType", type, nav.NodeType); AssertEquals ("Prefix", prefix, nav.Prefix); AssertEquals ("LocalName", localName, nav.LocalName); AssertEquals ("Namespace", ns, nav.NamespaceURI); AssertEquals ("Name", name, nav.Name); AssertEquals ("Value", value, nav.Value); AssertEquals ("HasAttributes", hasAttributes, nav.HasAttributes); AssertEquals ("HasChildren", hasChildren, nav.HasChildren); AssertEquals ("IsEmptyElement", isEmptyElement, nav.IsEmptyElement); } [Test] public void DocumentWithXmlDeclaration () { string xml = "<?xml version=\"1.0\" standalone=\"yes\"?><foo>bar</foo>"; nav = GetXmlDocumentNavigator (xml); DocumentWithXmlDeclaration (nav); nav = GetXPathDocumentNavigator (document); DocumentWithXmlDeclaration (nav); } public void DocumentWithXmlDeclaration (XPathNavigator nav) { nav.MoveToFirstChild (); AssertNavigator (nav, XPathNodeType.Element, "", "foo", "", "foo", "bar", false, true, false); } [Test] public void DocumentWithProcessingInstruction () { string xml = "<?xml-stylesheet href='foo.xsl' type='text/xsl' ?><foo />"; nav = GetXmlDocumentNavigator (xml); DocumentWithProcessingInstruction (nav); nav = GetXPathDocumentNavigator (document); DocumentWithProcessingInstruction (nav); } public void DocumentWithProcessingInstruction (XPathNavigator nav) { Assert (nav.MoveToFirstChild ()); AssertNavigator (nav, XPathNodeType.ProcessingInstruction, "", "xml-stylesheet", "", "xml-stylesheet", "href='foo.xsl' type='text/xsl' ", false, false, false); Assert (!nav.MoveToFirstChild ()); } [Test] public void XmlRootElementOnly () { string xml = "<foo />"; nav = GetXmlDocumentNavigator (xml); XmlRootElementOnly (nav); nav = GetXPathDocumentNavigator (document); XmlRootElementOnly (nav); } private void XmlRootElementOnly (XPathNavigator nav) { AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "", false, true, false); Assert (nav.MoveToFirstChild ()); AssertNavigator (nav, XPathNodeType.Element, "", "foo", "", "foo", "", false, false, true); Assert (!nav.MoveToFirstChild ()); Assert (!nav.MoveToNext ()); Assert (!nav.MoveToPrevious ()); nav.MoveToRoot (); AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "", false, true, false); Assert (!nav.MoveToNext ()); } [Test] public void XmlSimpleTextContent () { string xml = "<foo>Test.</foo>"; nav = GetXmlDocumentNavigator (xml); XmlSimpleTextContent (nav); nav = GetXPathDocumentNavigator (document); XmlSimpleTextContent (nav); } private void XmlSimpleTextContent (XPathNavigator nav) { AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "Test.", false, true, false); Assert (nav.MoveToFirstChild ()); AssertNavigator (nav, XPathNodeType.Element, "", "foo", "", "foo", "Test.", false, true, false); Assert (!nav.MoveToNext ()); Assert (!nav.MoveToPrevious ()); Assert (nav.MoveToFirstChild ()); AssertNavigator (nav, XPathNodeType.Text, "", "", "", "", "Test.", false, false, false); Assert (nav.MoveToParent ()); AssertNavigator (nav, XPathNodeType.Element, "", "foo", "", "foo", "Test.", false, true, false); Assert (nav.MoveToParent ()); AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "Test.", false, true, false); nav.MoveToFirstChild (); nav.MoveToFirstChild (); nav.MoveToRoot (); AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "Test.", false, true, false); Assert (!nav.MoveToNext ()); } [Test] public void XmlSimpleElementContent () { string xml = "<foo><bar /></foo>"; nav = GetXmlDocumentNavigator (xml); XmlSimpleElementContent (nav); nav = GetXPathDocumentNavigator (document); XmlSimpleElementContent (nav); } private void XmlSimpleElementContent (XPathNavigator nav) { AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "", false, true, false); Assert (nav.MoveToFirstChild ()); AssertNavigator (nav, XPathNodeType.Element, "", "foo", "", "foo", "", false, true, false); Assert (!nav.MoveToNext ()); Assert (!nav.MoveToPrevious ()); Assert (nav.MoveToFirstChild ()); AssertNavigator (nav, XPathNodeType.Element, "", "bar", "", "bar", "", false, false, true); Assert (nav.MoveToParent ()); AssertNavigator (nav, XPathNodeType.Element, "", "foo", "", "foo", "", false, true, false); nav.MoveToRoot (); AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "", false, true, false); Assert (!nav.MoveToNext ()); } [Test] public void XmlTwoElementsContent () { string xml = "<foo><bar /><baz /></foo>"; nav = GetXmlDocumentNavigator (xml); XmlTwoElementsContent (nav); nav = GetXPathDocumentNavigator (document); XmlTwoElementsContent (nav); } private void XmlTwoElementsContent (XPathNavigator nav) { AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "", false, true, false); Assert (nav.MoveToFirstChild ()); AssertNavigator (nav, XPathNodeType.Element, "", "foo", "", "foo", "", false, true, false); Assert (!nav.MoveToNext ()); Assert (!nav.MoveToPrevious ()); Assert (nav.MoveToFirstChild ()); AssertNavigator (nav, XPathNodeType.Element, "", "bar", "", "bar", "", false, false, true); Assert (!nav.MoveToFirstChild ()); Assert (nav.MoveToNext ()); AssertNavigator (nav, XPathNodeType.Element, "", "baz", "", "baz", "", false, false, true); Assert (!nav.MoveToFirstChild ()); Assert (nav.MoveToPrevious ()); AssertNavigator (nav, XPathNodeType.Element, "", "bar", "", "bar", "", false, false, true); nav.MoveToRoot (); AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "", false, true, false); Assert (!nav.MoveToNext ()); } [Test] public void XmlElementWithAttributes () { string xml = "<img src='foo.png' alt='image Fooooooo!' />"; nav = GetXmlDocumentNavigator (xml); XmlElementWithAttributes (nav); nav = GetXPathDocumentNavigator (document); XmlElementWithAttributes (nav); } private void XmlElementWithAttributes (XPathNavigator nav) { nav.MoveToFirstChild (); AssertNavigator (nav, XPathNodeType.Element, "", "img", "", "img", "", true, false, true); Assert (!nav.MoveToNext ()); Assert (!nav.MoveToPrevious ()); Assert (nav.MoveToFirstAttribute ()); AssertNavigator (nav, XPathNodeType.Attribute, "", "src", "", "src", "foo.png", false, false, false); Assert (!nav.MoveToFirstAttribute ()); // On attributes, it fails. Assert (nav.MoveToNextAttribute ()); AssertNavigator (nav, XPathNodeType.Attribute, "", "alt", "", "alt", "image Fooooooo!", false, false, false); Assert (!nav.MoveToNextAttribute ()); Assert (nav.MoveToParent ()); AssertNavigator (nav, XPathNodeType.Element, "", "img", "", "img", "", true, false, true); Assert (nav.MoveToAttribute ("alt", "")); AssertNavigator (nav, XPathNodeType.Attribute, "", "alt", "", "alt", "image Fooooooo!", false, false, false); Assert (!nav.MoveToAttribute ("src", "")); // On attributes, it fails. Assert (nav.MoveToParent ()); Assert (nav.MoveToAttribute ("src", "")); AssertNavigator (nav, XPathNodeType.Attribute, "", "src", "", "src", "foo.png", false, false, false); nav.MoveToRoot (); AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "", false, true, false); } [Test] public void XmlNamespaceNode () { string xml = "<html xmlns='http://www.w3.org/1999/xhtml'><body>test.</body></html>"; nav = GetXmlDocumentNavigator (xml); XmlNamespaceNode (nav); nav = GetXPathDocumentNavigator (document); XmlNamespaceNode (nav); } private void XmlNamespaceNode (XPathNavigator nav) { string xhtml = "http://www.w3.org/1999/xhtml"; string xmlNS = "http://www.w3.org/XML/1998/namespace"; nav.MoveToFirstChild (); AssertNavigator (nav, XPathNodeType.Element, "", "html", xhtml, "html", "test.", false, true, false); Assert (nav.MoveToFirstNamespace (XPathNamespaceScope.Local)); AssertNavigator (nav, XPathNodeType.Namespace, "", "", "", "", xhtml, false, false, false); // Test difference between Local, ExcludeXml and All. Assert (!nav.MoveToNextNamespace (XPathNamespaceScope.Local)); Assert (!nav.MoveToNextNamespace (XPathNamespaceScope.ExcludeXml)); // LAMESPEC: MS.NET 1.0 XmlDocument seems to have some bugs around here. // see http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q316808 #if true Assert (nav.MoveToNextNamespace (XPathNamespaceScope.All)); AssertNavigator (nav, XPathNodeType.Namespace, "", "xml", "", "xml", xmlNS, false, false, false); Assert (!nav.MoveToNextNamespace (XPathNamespaceScope.All)); #endif // Test to check if MoveToRoot() resets Namespace node status. nav.MoveToRoot (); AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "test.", false, true, false); nav.MoveToFirstChild (); // Test without XPathNamespaceScope argument. Assert (nav.MoveToFirstNamespace ()); Assert (nav.MoveToNextNamespace ()); AssertNavigator (nav, XPathNodeType.Namespace, "", "xml", "", "xml", xmlNS, false, false, false); // Test MoveToParent() Assert (nav.MoveToParent ()); AssertNavigator (nav, XPathNodeType.Element, "", "html", xhtml, "html", "test.", false, true, false); nav.MoveToFirstChild (); // body // Test difference between Local and ExcludeXml Assert (!nav.MoveToFirstNamespace (XPathNamespaceScope.Local)); Assert (nav.MoveToFirstNamespace (XPathNamespaceScope.ExcludeXml)); AssertNavigator (nav, XPathNodeType.Namespace, "", "", "", "", xhtml, false, false, false); Assert (nav.MoveToNextNamespace (XPathNamespaceScope.All)); AssertNavigator (nav, XPathNodeType.Namespace, "", "xml", "", "xml", xmlNS, false, false, false); Assert (nav.MoveToParent ()); AssertNavigator (nav, XPathNodeType.Element, "", "body", xhtml, "body", "test.", false, true, false); nav.MoveToRoot (); AssertNavigator (nav, XPathNodeType.Root, "", "", "", "", "test.", false, true, false); } [Test] public void MoveToNamespaces () { string xml = "<a xmlns:x='urn:x'><b xmlns:y='urn:y'/><c/><d><e attr='a'/></d></a>"; nav = GetXmlDocumentNavigator (xml); MoveToNamespaces (nav); nav = GetXPathDocumentNavigator (document); MoveToNamespaces (nav); } private void MoveToNamespaces (XPathNavigator nav) { XPathNodeIterator iter = nav.Select ("//e"); iter.MoveNext (); nav.MoveTo (iter.Current); AssertEquals ("e", nav.Name); nav.MoveToFirstNamespace (); AssertEquals ("x", nav.Name); nav.MoveToNextNamespace (); AssertEquals ("xml", nav.Name); } [Test] public void IsDescendant () { string xml = "<a><b/><c/><d><e attr='a'/></d></a>"; nav = GetXmlDocumentNavigator (xml); IsDescendant (nav); nav = GetXPathDocumentNavigator (document); IsDescendant (nav); } private void IsDescendant (XPathNavigator nav) { XPathNavigator tmp = nav.Clone (); XPathNodeIterator iter = nav.Select ("//e"); iter.MoveNext (); Assert (nav.MoveTo (iter.Current)); Assert (nav.MoveToFirstAttribute ()); AssertEquals ("attr", nav.Name); AssertEquals ("", tmp.Name); Assert (tmp.IsDescendant (nav)); Assert (!nav.IsDescendant (tmp)); tmp.MoveToFirstChild (); AssertEquals ("a", tmp.Name); Assert (tmp.IsDescendant (nav)); Assert (!nav.IsDescendant (tmp)); tmp.MoveTo (iter.Current); AssertEquals ("e", tmp.Name); Assert (tmp.IsDescendant (nav)); Assert (!nav.IsDescendant (tmp)); } [Test] public void LiterallySplittedText () { string xml = "<root><![CDATA[test]]> string</root>"; nav = GetXmlDocumentNavigator (xml); LiterallySplittedText (nav); nav = GetXPathDocumentNavigator (document); LiterallySplittedText (nav); } private void LiterallySplittedText (XPathNavigator nav) { nav.MoveToFirstChild (); nav.MoveToFirstChild (); AssertEquals (XPathNodeType.Text, nav.NodeType); AssertEquals ("test string", nav.Value); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Akka.Streams.Kafka.Dsl; using Akka.Streams.Kafka.Helpers; using Akka.Streams.Kafka.Messages; using Akka.Streams.Kafka.Settings; using Akka.Streams.Stage; using Akka.Streams.Supervision; using Confluent.Kafka; namespace Akka.Streams.Kafka.Stages { /// <summary> /// Stage used by <see cref="KafkaProducer.TransactionalFlow{K,V}"/> /// </summary> internal class TransactionalProducerStage<K, V, TPassThrough> : GraphStage<FlowShape<IEnvelope<K, V, TPassThrough>, Task<IResults<K, V, TPassThrough>>>>, IProducerStage<K, V, TPassThrough, IEnvelope<K, V, TPassThrough>, IResults<K, V, TPassThrough>> { private readonly ProducerSettings<K, V> _settings; public TimeSpan FlushTimeout => _settings.FlushTimeout; public bool CloseProducerOnStop { get; } public Func<Action<IProducer<K, V>, Error>, IProducer<K, V>> ProducerProvider { get; } public override FlowShape<IEnvelope<K, V, TPassThrough>, Task<IResults<K, V, TPassThrough>>> Shape { get; } public Inlet<IEnvelope<K, V, TPassThrough>> In { get; } = new Inlet<IEnvelope<K, V, TPassThrough>>("kafka.transactional.producer.in"); public Outlet<Task<IResults<K, V, TPassThrough>>> Out { get; } = new Outlet<Task<IResults<K, V, TPassThrough>>>("kafka.transactional.producer.out"); /// <summary> /// TransactionalProducerStage /// </summary> public TransactionalProducerStage(bool closeProducerOnStop, ProducerSettings<K, V> settings) { _settings = settings; CloseProducerOnStop = closeProducerOnStop; ProducerProvider = errorHandler => _settings.CreateKafkaProducer(errorHandler); Shape = new FlowShape<IEnvelope<K, V, TPassThrough>, Task<IResults<K, V, TPassThrough>>>(In, Out); } /// <inheritdoc /> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) { return new TransactionalProducerStageLogic<K, V, TPassThrough>(this, inheritedAttributes, _settings.EosCommitInterval); } } internal class TransactionalProducerStageLogic<K, V, TPassThrough> : DefaultProducerStageLogic<K, V, TPassThrough, IEnvelope<K, V, TPassThrough>, IResults<K, V, TPassThrough>> { private const string CommitSchedulerKey = "commit"; private readonly TransactionalProducerStage<K, V, TPassThrough> _stage; private readonly TimeSpan _commitInterval; private readonly Decider _decider; private readonly TimeSpan _messageDrainInterval = TimeSpan.FromMilliseconds(10); private ITransactionBatch _batchOffsets = new EmptyTransactionBatch(); private bool _demandSuspended = false; private readonly Action _onInternalCommitCallback; public TransactionalProducerStageLogic( TransactionalProducerStage<K, V, TPassThrough> stage, Attributes attributes, TimeSpan commitInterval) : base(stage, attributes) { _stage = stage; _commitInterval = commitInterval; var supervisionStrategy = attributes.GetAttribute<ActorAttributes.SupervisionStrategy>(null); _decider = supervisionStrategy != null ? supervisionStrategy.Decider : Deciders.StoppingDecider; _onInternalCommitCallback = GetAsyncCallback(() => ScheduleOnce(CommitSchedulerKey, commitInterval)); } public override void PreStart() { base.PreStart(); InitTransactions(); BeginTransaction(); ResumeDemand(tryToPull: false); ScheduleOnce(CommitSchedulerKey, _commitInterval); } private void ResumeDemand(bool tryToPull = true) { SetHandler(_stage.Out, onPull: () => TryPull(_stage.In)); _demandSuspended = false; if (tryToPull && IsAvailable(_stage.Out) && !HasBeenPulled(_stage.In)) { TryPull(_stage.In); } } private void SuspendDemand() { if (!_demandSuspended) { // suspend demand while a commit is in process so we can drain any outstanding message acknowledgements SetHandler(_stage.Out, onPull: () => { }); } _demandSuspended = true; } protected override void OnTimer(object timerKey) { if (timerKey.Equals(CommitSchedulerKey)) MaybeCommitTransaction(); } private void MaybeCommitTransaction(bool beginNewTransaction = true) { var awaitingConf = AwaitingConfirmation.Current; if (_batchOffsets is NonemptyTransactionBatch nonemptyTransactionBatch && awaitingConf == 0) { CommitTransaction(nonemptyTransactionBatch, beginNewTransaction); } else if (awaitingConf > 0) { SuspendDemand(); ScheduleOnce(CommitSchedulerKey, _messageDrainInterval); } else { ScheduleOnce(CommitSchedulerKey, _commitInterval); } } protected override void PostSend(IEnvelope<K, V, TPassThrough> msg) { var marker = msg.PassThrough as PartitionOffsetCommittedMarker; if (marker != null) _batchOffsets = _batchOffsets.Updated(marker); } public override void OnCompletionSuccess() { Log.Debug("Comitting final transaction before shutdown"); CancelTimer(CommitSchedulerKey); MaybeCommitTransaction(beginNewTransaction: false); base.OnCompletionSuccess(); } public override void OnCompletionFailure(Exception ex) { Log.Debug("Aborting transaction due to stage failure"); AbortTransaction(); _batchOffsets.CommittingFailed(); base.OnCompletionFailure(ex); } private void CommitTransaction(NonemptyTransactionBatch batch, bool beginNewTransaction) { var groupId = batch.GroupId; Log.Debug("Committing transaction for consumer group '{0}' with offsets: {1}", groupId, batch.Offsets); var offsetMap = batch.OffsetMap(); // TODO: Add producer work with transactions /* scala code: producer.sendOffsetsToTransaction(offsetMap.asJava, group) producer.commitTransaction() */ Log.Debug("Committed transaction for consumer group '{0}' with offsets: {1}", groupId, batch.Offsets); _batchOffsets = new EmptyTransactionBatch(); batch.InternalCommit().ContinueWith(t => { _onInternalCommitCallback.Invoke(); }); if (beginNewTransaction) { BeginTransaction(); ResumeDemand(); } } private void InitTransactions() { Log.Debug("Iinitializing transactions"); // TODO: Add producer work with transactions // producer.initTransactions() } private void BeginTransaction() { Log.Debug("Beginning new transaction"); // TODO: Add producer work with transactions // producer.beginTransaction() } private void AbortTransaction() { Log.Debug("Aborting transaction"); // TODO: Add producer work with transactions // producer.abortTransaction() } private interface ITransactionBatch { ITransactionBatch Updated(PartitionOffsetCommittedMarker partitionOffset); void CommittingFailed(); } private class EmptyTransactionBatch : ITransactionBatch { public ITransactionBatch Updated(PartitionOffsetCommittedMarker partitionOffset) => new NonemptyTransactionBatch(partitionOffset); public void CommittingFailed() { } } private class NonemptyTransactionBatch : ITransactionBatch { private readonly PartitionOffsetCommittedMarker _head; private readonly IImmutableDictionary<GroupTopicPartition, Offset> _tail; private readonly ICommittedMarker _committedMarker; public IImmutableDictionary<GroupTopicPartition, Offset> Offsets { get; } public string GroupId { get; } public NonemptyTransactionBatch(PartitionOffsetCommittedMarker head, IImmutableDictionary<GroupTopicPartition, Offset> tail = null) { _head = head; _tail = tail ?? ImmutableDictionary<GroupTopicPartition, Offset>.Empty; _committedMarker = head.CommittedMarker; GroupId = head.GroupId; var previousHighest = _tail.GetValueOrDefault(head.GroupTopicPartition, new Offset(-1)).Value; var highestOffset = new Offset(Math.Max(head.Offset, previousHighest)); Offsets = _tail.AddRange(new []{ new KeyValuePair<GroupTopicPartition, Offset>(head.GroupTopicPartition, highestOffset) }); } /// <inheritdoc /> public ITransactionBatch Updated(PartitionOffsetCommittedMarker partitionOffset) { if (partitionOffset.GroupId != GroupId) throw new ArgumentException($"Transaction batch must contain messages from exactly 1 consumer group. {partitionOffset.GroupId} != {GroupId}"); if (!partitionOffset.CommittedMarker.Equals(_committedMarker)) throw new ArgumentException("Transaction batch must contain messages from a single source"); return new NonemptyTransactionBatch(partitionOffset, Offsets); } /// <inheritdoc /> public void CommittingFailed() => _committedMarker.Failed(); public IImmutableDictionary<TopicPartition, OffsetAndMetadata> OffsetMap() { return Offsets.ToImmutableDictionary( pair => new TopicPartition(pair.Key.Topic, pair.Key.Partition), pair => new OffsetAndMetadata(pair.Value.Value + 1, string.Empty) ); } public Task InternalCommit() => _committedMarker.Committed(OffsetMap()); } } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Collections; using OpenADK.Library; using OpenADK.Library.Infra; using OpenADK.Library.Tools.Cfg; using OpenADK.Util; using OpenADK.Library.uk; namespace Library.Examples.Chameleon { /// <summary> /// Chameleon is a universal subscribing and logging agent. /// </summary> public class Chameleon : Agent, IQueryResults { private AgentConfig fCfg; private static AdkConsoleWait sWaitMutex; private ObjectLogger fLogger; private string fRequestState = Guid.NewGuid().ToString(); public Chameleon() : base("Chameleon") { } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static void Main(string[] args) { try { Adk.Debug = AdkDebugFlags.Moderate; Adk.Initialize(SifVersion.LATEST,SIFVariant.SIF_UK, (int)SdoLibraryType.All); Chameleon agent; agent = new Chameleon(); // Start agent... agent.StartAgent(args); Console.WriteLine("Agent is running (Press Ctrl-C to stop)"); sWaitMutex = new AdkConsoleWait(); sWaitMutex.WaitForExit(); // Always shutdown the agent on exit agent.Shutdown(ProvisioningFlags.None); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> Initialize and start the agent /// </summary> /// <param name="args">Command-line arguments (run with no arguments to display help) /// </param> public virtual void StartAgent(string[] args) { Console.WriteLine("Initializing agent..."); // Read the configuration file fCfg = new AgentConfig(); Console.Out.WriteLine("Reading configuration file..."); fCfg.Read("agent.cfg", false); // Override the SourceId passed to the constructor with the SourceId // specified in the configuration file this.Id = fCfg.SourceId; // Inform the ADK of the version of SIF specified in the sifVersion= // attribute of the <agent> element SifVersion version = fCfg.Version; Adk.SifVersion = version; // Now call the superclass initialize once the configuration file has been read base.Initialize(); // Ask the AgentConfig instance to "apply" all configuration settings // to this Agent; for example, all <property> elements that are children // of the root <agent> node are parsed and applied to this Agent's // AgentProperties object; all <zone> elements are parsed and registered // with the Agent's ZoneFactory, and so on. // fCfg.Apply(this, true); // Create the logging object fLogger = new ObjectLogger(this); Query zoneQuery = new Query(InfraDTD.SIF_ZONESTATUS); zoneQuery.AddFieldRestriction(InfraDTD.SIF_ZONESTATUS_SIF_PROVIDERS); //zoneQuery.AddFieldRestriction( SifDtd.SIF_ZONESTATUS_SIF_SIFNODES ); zoneQuery.UserData = fRequestState; ITopic zoneTopic = TopicFactory.GetInstance(InfraDTD.SIF_ZONESTATUS); zoneTopic.SetQueryResults(this); // Now, connect to all zones and just get the zone status foreach (IZone zone in this.ZoneFactory.GetAllZones()) { if (getChameleonProperty(zone, "logRaw", false)) { zone.Properties.KeepMessageContent = true; zone.AddMessagingListener(fLogger); } zone.Connect(ProvisioningFlags.Register); zoneTopic.Join(zone); } Console.WriteLine(); Console.WriteLine("Requesting SIF_ZoneStatus from all zones..."); zoneTopic.Query(zoneQuery); } public override ISubscriber GetSubscriber(SifContext context,IElementDef objectType) { return fLogger; } public override IQueryResults GetQueryResults(SifContext context, IElementDef objectType) { return fLogger; } public void OnQueryPending(IMessageInfo info, IZone zone) { Adk.Log.Info ( string.Format ("Requested {0} from {1}", ((SifMessageInfo)info).SIFRequestObjectType.Name, zone.ZoneId)); } public bool getChameleonProperty(IZone zone, string propertyName, bool defaultValue) { bool retValue = true; try { retValue = zone.Properties.GetProperty("chameleon." + propertyName, defaultValue); } catch (Exception ex) { Log.Warn(ex.Message, ex); } return retValue; } public void OnQueryResults(IDataObjectInputStream data, SIF_Error error, IZone zone, IMessageInfo info) { SifMessageInfo smi = (SifMessageInfo)info; if (!(fRequestState.Equals(smi.SIFRequestInfo.UserData))) { // This is a SIF_ZoneStatus response from a previous invocation of the agent return; } if (data.Available) { SIF_ZoneStatus zoneStatus = data.ReadDataObject() as SIF_ZoneStatus; AsyncUtils.QueueTaskToThreadPool(new zsDelegate(_processSIF_ZoneStatus), zoneStatus, zone); } } private delegate void zsDelegate(SIF_ZoneStatus zoneStatus, IZone zone); private void _processSIF_ZoneStatus(SIF_ZoneStatus zoneStatus, IZone zone) { if (zoneStatus == null) { return; } bool sync = getChameleonProperty(zone, "sync", false); bool events = getChameleonProperty(zone, "logEvents", true); bool logEntry = getChameleonProperty(zone, "sifLogEntrySupport", false); ArrayList objectDefs = new ArrayList(); SIF_Providers providers = zoneStatus.SIF_Providers; if (providers != null) { foreach (SIF_Provider p in providers) { foreach (SIF_Object obj in p.SIF_ObjectList) { // Lookup the topic for each provided object in the zone IElementDef def = Adk.Dtd.LookupElementDef(obj.ObjectName); if (def != null) { objectDefs.Add(def); ITopic topic = TopicFactory.GetInstance(def); if (topic.GetSubscriber() == null) { if (events) { topic.SetSubscriber(fLogger, new SubscriptionOptions( )); } if (sync) { topic.SetQueryResults(fLogger); } } } } } } if (logEntry) { ITopic sifLogEntryTopic = TopicFactory.GetInstance(InfraDTD.SIF_LOGENTRY); sifLogEntryTopic.SetSubscriber(fLogger, new SubscriptionOptions( )); } foreach (ITopic topic in TopicFactory.GetAllTopics( SifContext.DEFAULT )) { try { // Join the topic to each zone ( causes the agent to subscribe to the joined objects ) // TODO: Add an "isJoinedTo()" API to topic so that it doesn't throw an exception if (topic.ObjectType != InfraDTD.SIF_ZONESTATUS.Name) { topic.Join(zone); } } catch (Exception ex) { zone.Log.Error(ex.Message, ex); } } if (sync) { if (objectDefs.Count == 0) { zone.ServerLog.Log (LogLevel.WARNING, "No objects are being provided in this zone", null, "1001"); } string syncObjects = zone.Properties.GetProperty("chameleon.syncObjects"); foreach (IElementDef def in objectDefs) { if (def.IsSupported(Adk.SifVersion)) { if (syncObjects == null || (syncObjects.Length > 0 && syncObjects.IndexOf(def.Name) > -1)) { Query q = new Query(def); // Query by specific parameters string condition = zone.Properties.GetProperty ("chameleon.syncConditions." + def.Name); if (condition != null && condition.Length > 0) { // The condition should be in the format "path=value" e.g "@RefId=123412341...1234|@Name=asdfasdf" String[] queryConditions = condition.Split('|'); foreach (String cond in queryConditions) { string[] conds = cond.Split('='); if (conds.Length == 2) { q.AddCondition(conds[0], "EQ", conds[1]); } } } if (logEntry) { zone.ServerLog.Log (LogLevel.INFO, "Requesting " + q.ObjectType.Name + " from the zone", q.ToXml(Adk.SifVersion), "1002"); } zone.Query(q); } } else { String debug = "Will not request " + def.Name + " because it is not supported in " + Adk.SifVersion.ToString(); Console.WriteLine(debug); zone.ServerLog.Log(LogLevel.WARNING, debug, null, "1001"); } } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using Validation; namespace System.Collections.Immutable { /// <summary> /// An immutable unordered hash set implementation. /// </summary> /// <typeparam name="T">The type of elements in the set.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableHashSetDebuggerProxy<>))] public sealed partial class ImmutableHashSet<T> : IImmutableSet<T>, IHashKeyCollection<T>, IReadOnlyCollection<T>, ICollection<T>, ISet<T>, ICollection, IStrongEnumerable<T, ImmutableHashSet<T>.Enumerator> { /// <summary> /// An empty immutable hash set with the default comparer for <typeparamref name="T"/>. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly ImmutableHashSet<T> Empty = new ImmutableHashSet<T>(SortedInt32KeyNode<HashBucket>.EmptyNode, EqualityComparer<T>.Default, 0); /// <summary> /// The singleton delegate that freezes the contents of hash buckets when the root of the data structure is frozen. /// </summary> private static readonly Action<KeyValuePair<int, HashBucket>> FreezeBucketAction = (kv) => kv.Value.Freeze(); /// <summary> /// The equality comparer used to hash the elements in the collection. /// </summary> private readonly IEqualityComparer<T> equalityComparer; /// <summary> /// The number of elements in this collection. /// </summary> private readonly int count; /// <summary> /// The sorted dictionary that this hash set wraps. The key is the hash code and the value is the bucket of all items that hashed to it. /// </summary> private readonly SortedInt32KeyNode<HashBucket> root; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashSet&lt;T&gt;"/> class. /// </summary> /// <param name="equalityComparer">The equality comparer.</param> internal ImmutableHashSet(IEqualityComparer<T> equalityComparer) : this(SortedInt32KeyNode<HashBucket>.EmptyNode, equalityComparer, 0) { } /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashSet&lt;T&gt;"/> class. /// </summary> /// <param name="root">The sorted set that this set wraps.</param> /// <param name="equalityComparer">The equality comparer used by this instance.</param> /// <param name="count">The number of elements in this collection.</param> private ImmutableHashSet(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count) { Requires.NotNull(root, "root"); Requires.NotNull(equalityComparer, "equalityComparer"); root.Freeze(FreezeBucketAction); this.root = root; this.count = count; this.equalityComparer = equalityComparer; } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public ImmutableHashSet<T> Clear() { Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>().IsEmpty); return this.IsEmpty ? this : ImmutableHashSet<T>.Empty.WithComparer(this.equalityComparer); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public int Count { get { return this.count; } } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public bool IsEmpty { get { return this.Count == 0; } } #region IHashKeyCollection<T> Properties /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public IEqualityComparer<T> KeyComparer { get { return this.equalityComparer; } } #endregion #region IImmutableSet<T> Properties /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Clear() { return this.Clear(); } #endregion #region ICollection Properties /// <summary> /// See ICollection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { return this; } } /// <summary> /// See the ICollection interface. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { // This is immutable, so it is always thread-safe. return true; } } #endregion /// <summary> /// Gets the root node (for testing purposes). /// </summary> internal IBinaryTree Root { get { return this.root; } } /// <summary> /// Gets a data structure that captures the current state of this map, as an input into a query or mutating function. /// </summary> private MutationInput Origin { get { return new MutationInput(this); } } #region Public methods /// <summary> /// Creates a collection with the same contents as this collection that /// can be efficiently mutated across multiple operations using standard /// mutable interfaces. /// </summary> /// <remarks> /// This is an O(1) operation and results in only a single (small) memory allocation. /// The mutable collection that is returned is *not* thread-safe. /// </remarks> [Pure] public Builder ToBuilder() { // We must not cache the instance created here and return it to various callers. // Those who request a mutable collection must get references to the collection // that version independently of each other. return new Builder(this); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> Add(T item) { Requires.NotNullAllowStructs(item, "item"); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); var result = Add(item, this.Origin); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public ImmutableHashSet<T> Remove(T item) { Requires.NotNullAllowStructs(item, "item"); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); var result = Remove(item, this.Origin); return result.Finalize(this); } /// <summary> /// Searches the set for a given value and returns the equal value it finds, if any. /// </summary> /// <param name="equalValue">The value to search for.</param> /// <param name="actualValue">The value from the set that the search found, or the original value if the search yielded no match.</param> /// <returns>A value indicating whether the search was successful.</returns> /// <remarks> /// This can be useful when you want to reuse a previously stored reference instead of /// a newly constructed one (so that more sharing of references can occur) or to look up /// a value that has more complete data than the value you currently have, although their /// comparer functions indicate they are equal. /// </remarks> [Pure] public bool TryGetValue(T equalValue, out T actualValue) { Requires.NotNullAllowStructs(equalValue, "value"); int hashCode = this.equalityComparer.GetHashCode(equalValue); HashBucket bucket; if (this.root.TryGetValue(hashCode, out bucket)) { return bucket.TryExchange(equalValue, this.equalityComparer, out actualValue); } actualValue = equalValue; return false; } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> Union(IEnumerable<T> other) { Requires.NotNull(other, "other"); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); return this.Union(other, avoidWithComparer: false); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> Intersect(IEnumerable<T> other) { Requires.NotNull(other, "other"); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); var result = Intersect(other, this.Origin); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public ImmutableHashSet<T> Except(IEnumerable<T> other) { Requires.NotNull(other, "other"); var result = Except(other, this.equalityComparer, this.root); return result.Finalize(this); } /// <summary> /// Produces a set that contains elements either in this set or a given sequence, but not both. /// </summary> /// <param name="other">The other sequence of items.</param> /// <returns>The new set.</returns> [Pure] public ImmutableHashSet<T> SymmetricExcept(IEnumerable<T> other) { Requires.NotNull(other, "other"); Contract.Ensures(Contract.Result<IImmutableSet<T>>() != null); var result = SymmetricExcept(other, this.Origin); return result.Finalize(this); } /// <summary> /// Checks whether a given sequence of items entirely describe the contents of this set. /// </summary> /// <param name="other">The sequence of items to check against this set.</param> /// <returns>A value indicating whether the sets are equal.</returns> [Pure] public bool SetEquals(IEnumerable<T> other) { Requires.NotNull(other, "other"); if (object.ReferenceEquals(this, other)) { return true; } return SetEquals(other, this.Origin); } /// <summary> /// Determines whether the current set is a property (strict) subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct subset of other; otherwise, false.</returns> [Pure] public bool IsProperSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsProperSubsetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a correct superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct superset of other; otherwise, false.</returns> [Pure] public bool IsProperSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsProperSupersetOf(other, this.Origin); } /// <summary> /// Determines whether a set is a subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a subset of other; otherwise, false.</returns> [Pure] public bool IsSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsSubsetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> [Pure] public bool IsSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsSupersetOf(other, this.Origin); } /// <summary> /// Determines whether the current set overlaps with the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set and other share at least one common element; otherwise, false.</returns> [Pure] public bool Overlaps(IEnumerable<T> other) { Requires.NotNull(other, "other"); return Overlaps(other, this.Origin); } #endregion #region IImmutableSet<T> Methods /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Add(T item) { return this.Add(item); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Remove(T item) { return this.Remove(item); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Union(IEnumerable<T> other) { return this.Union(other); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Intersect(IEnumerable<T> other) { return this.Intersect(other); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Except(IEnumerable<T> other) { return this.Except(other); } /// <summary> /// Produces a set that contains elements either in this set or a given sequence, but not both. /// </summary> /// <param name="other">The other sequence of items.</param> /// <returns>The new set.</returns> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.SymmetricExcept(IEnumerable<T> other) { return this.SymmetricExcept(other); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public bool Contains(T item) { Requires.NotNullAllowStructs(item, "item"); return Contains(item, this.Origin); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> WithComparer(IEqualityComparer<T> equalityComparer) { Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == this.equalityComparer) { return this; } else { var result = new ImmutableHashSet<T>(equalityComparer); result = result.Union(this, avoidWithComparer: true); return result; } } #endregion #region ISet<T> Members /// <summary> /// See <see cref="ISet{T}"/> /// </summary> bool ISet<T>.Add(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.ExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.IntersectWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.SymmetricExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.UnionWith(IEnumerable<T> other) { throw new NotSupportedException(); } #endregion #region ICollection<T> members /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> bool ICollection<T>.IsReadOnly { get { return true; } } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<T>.CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (T item in this) { array[arrayIndex++] = item; } } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> void ICollection<T>.Add(T item) { throw new NotSupportedException(); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<T>.Clear() { throw new NotSupportedException(); } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } #endregion #region ICollection Methods /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); if (this.count == 0) { return; } int[] indices = new int[1]; // SetValue takes a params array; lifting out the implicit allocation from the loop foreach (T item in this) { indices[0] = arrayIndex++; array.SetValue(item, indices); } } #endregion #region IEnumerable<T> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this.root); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Static query and manipulator methods /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsSupersetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (!Contains(item, origin)) { return false; } } return true; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Add(T item, MutationInput origin) { Requires.NotNullAllowStructs(item, "item"); OperationResult result; int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket = origin.Root.GetValueOrDefault(hashCode); var newBucket = bucket.Add(item, origin.EqualityComparer, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin.Root, 0); } var newRoot = UpdateRoot(origin.Root, hashCode, newBucket); Debug.Assert(result == OperationResult.SizeChanged); return new MutationResult(newRoot, 1 /*result == OperationResult.SizeChanged ? 1 : 0*/); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Remove(T item, MutationInput origin) { Requires.NotNullAllowStructs(item, "item"); var result = OperationResult.NoChangeRequired; int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket; var newRoot = origin.Root; if (origin.Root.TryGetValue(hashCode, out bucket)) { var newBucket = bucket.Remove(item, origin.EqualityComparer, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin.Root, 0); } newRoot = UpdateRoot(origin.Root, hashCode, newBucket); } return new MutationResult(newRoot, result == OperationResult.SizeChanged ? -1 : 0); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool Contains(T item, MutationInput origin) { int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { return bucket.Contains(item, origin.EqualityComparer); } return false; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Union(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); int count = 0; var newRoot = origin.Root; foreach (var item in other.GetEnumerableDisposable<T, Enumerator>()) { int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket = newRoot.GetValueOrDefault(hashCode); OperationResult result; var newBucket = bucket.Add(item, origin.EqualityComparer, out result); if (result == OperationResult.SizeChanged) { newRoot = UpdateRoot(newRoot, hashCode, newBucket); count++; } } return new MutationResult(newRoot, count); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool Overlaps(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return false; } foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (Contains(item, origin)) { return true; } } return false; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool SetEquals(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); var otherSet = new HashSet<T>(other, origin.EqualityComparer); if (origin.Count != otherSet.Count) { return false; } int matches = 0; foreach (T item in otherSet) { if (!Contains(item, origin)) { return false; } matches++; } return matches == origin.Count; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static SortedInt32KeyNode<HashBucket> UpdateRoot(SortedInt32KeyNode<HashBucket> root, int hashCode, HashBucket newBucket) { bool mutated; if (newBucket.IsEmpty) { return root.Remove(hashCode, out mutated); } else { bool replacedExistingValue; return root.SetItem(hashCode, newBucket, EqualityComparer<HashBucket>.Default, out replacedExistingValue, out mutated); } } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Intersect(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); var newSet = SortedInt32KeyNode<HashBucket>.EmptyNode; int count = 0; foreach (var item in other.GetEnumerableDisposable<T, Enumerator>()) { if (Contains(item, origin)) { var result = Add(item, new MutationInput(newSet, origin.EqualityComparer, count)); newSet = result.Root; count += result.Count; } } return new MutationResult(newSet, count, CountType.FinalValue); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Except(IEnumerable<T> other, IEqualityComparer<T> equalityComparer, SortedInt32KeyNode<HashBucket> root) { Requires.NotNull(other, "other"); Requires.NotNull(equalityComparer, "equalityComparer"); Requires.NotNull(root, "root"); int count = 0; var newRoot = root; foreach (var item in other.GetEnumerableDisposable<T, Enumerator>()) { int hashCode = equalityComparer.GetHashCode(item); HashBucket bucket; if (newRoot.TryGetValue(hashCode, out bucket)) { OperationResult result; HashBucket newBucket = bucket.Remove(item, equalityComparer, out result); if (result == OperationResult.SizeChanged) { count--; newRoot = UpdateRoot(newRoot, hashCode, newBucket); } } } return new MutationResult(newRoot, count); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> [Pure] private static MutationResult SymmetricExcept(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); var otherAsSet = Empty.Union(other); int count = 0; var result = SortedInt32KeyNode<HashBucket>.EmptyNode; foreach (T item in new NodeEnumerable(origin.Root)) { if (!otherAsSet.Contains(item)) { var mutationResult = Add(item, new MutationInput(result, origin.EqualityComparer, count)); result = mutationResult.Root; count += mutationResult.Count; } } foreach (T item in otherAsSet) { if (!Contains(item, origin)) { var mutationResult = Add(item, new MutationInput(result, origin.EqualityComparer, count)); result = mutationResult.Root; count += mutationResult.Count; } } return new MutationResult(result, count, CountType.FinalValue); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsProperSubsetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return other.Any(); } // To determine whether everything we have is also in another sequence, // we enumerate the sequence and "tag" whether it's in this collection, // then consider whether every element in this collection was tagged. // Since this collection is immutable we cannot directly tag. So instead // we simply count how many "hits" we have and ensure it's equal to the // size of this collection. Of course for this to work we need to ensure // the uniqueness of items in the given sequence, so we create a set based // on the sequence first. var otherSet = new HashSet<T>(other, origin.EqualityComparer); if (origin.Count >= otherSet.Count) { return false; } int matches = 0; bool extraFound = false; foreach (T item in otherSet) { if (Contains(item, origin)) { matches++; } else { extraFound = true; } if (matches == origin.Count && extraFound) { return true; } } return false; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsProperSupersetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return false; } int matchCount = 0; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { matchCount++; if (!Contains(item, origin)) { return false; } } return origin.Count > matchCount; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsSubsetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return true; } // To determine whether everything we have is also in another sequence, // we enumerate the sequence and "tag" whether it's in this collection, // then consider whether every element in this collection was tagged. // Since this collection is immutable we cannot directly tag. So instead // we simply count how many "hits" we have and ensure it's equal to the // size of this collection. Of course for this to work we need to ensure // the uniqueness of items in the given sequence, so we create a set based // on the sequence first. var otherSet = new HashSet<T>(other, origin.EqualityComparer); int matches = 0; foreach (T item in otherSet) { if (Contains(item, origin)) { matches++; } } return matches == origin.Count; } #endregion /// <summary> /// Wraps the specified data structure with an immutable collection wrapper. /// </summary> /// <param name="root">The root of the data structure.</param> /// <param name="equalityComparer">The equality comparer.</param> /// <param name="count">The number of elements in the data structure.</param> /// <returns>The immutable collection.</returns> private static ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count) { Requires.NotNull(root, "root"); Requires.NotNull(equalityComparer, "equalityComparer"); Requires.Range(count >= 0, "count"); return new ImmutableHashSet<T>(root, equalityComparer, count); } /// <summary> /// Wraps the specified data structure with an immutable collection wrapper. /// </summary> /// <param name="root">The root of the data structure.</param> /// <param name="adjustedCountIfDifferentRoot">The adjusted count if the root has changed.</param> /// <returns>The immutable collection.</returns> private ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, int adjustedCountIfDifferentRoot) { return (root != this.root) ? new ImmutableHashSet<T>(root, this.equalityComparer, adjustedCountIfDifferentRoot) : this; } /// <summary> /// Bulk adds entries to the set. /// </summary> /// <param name="items">The entries to add.</param> /// <param name="avoidWithComparer"><c>true</c> when being called from ToHashSet to avoid StackOverflow.</param> [Pure] private ImmutableHashSet<T> Union(IEnumerable<T> items, bool avoidWithComparer) { Requires.NotNull(items, "items"); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); // Some optimizations may apply if we're an empty set. if (this.IsEmpty && !avoidWithComparer) { // If the items being added actually come from an ImmutableHashSet<T>, // reuse that instance if possible. var other = items as ImmutableHashSet<T>; if (other != null) { return other.WithComparer(this.KeyComparer); } } var result = Union(items, this.Origin); return result.Finalize(this); } } }
namespace PokerTell.Repository.Tests.NHibernate { using System; using global::NHibernate; using Infrastructure.Interfaces.Repository; using Moq; using NUnit.Framework; using PokerTell.Repository.NHibernate; using UnitTests; using UnitTests.Tools; public class TransactionManagerTests : TestWithLog { StubBuilder _stub; Mock<ISessionFactoryManager> _sessionFactoryStub; Mock<ISession> _sessionStub; Mock<IStatelessSession> _statelessSessionStub; Mock<ITransaction> _transactionMock; [SetUp] public void _Init() { _stub = new StubBuilder(); _transactionMock = new Mock<ITransaction>(); _sessionStub = new Mock<ISession>(); _sessionStub .SetupGet(s => s.Transaction) .Returns(_transactionMock.Object); _statelessSessionStub = new Mock<IStatelessSession>(); _statelessSessionStub .SetupGet(ss => ss.Transaction) .Returns(_transactionMock.Object); _sessionFactoryStub = new Mock<ISessionFactoryManager>(); _sessionFactoryStub .SetupGet(sf => sf.CurrentSession) .Returns(_sessionStub.Object); _sessionFactoryStub .Setup(sf => sf.OpenStatelessSession()) .Returns(_statelessSessionStub.Object); } [Test] public void Execute_NoError_BindsSession() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); sut.Execute(() => { }); sut.SessionWasBound.ShouldBeTrue(); } [Test] public void ExecuteRetrieval_NoError_BindsSession() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); sut.Execute(() => 1); sut.SessionWasBound.ShouldBeTrue(); } [Test] public void Execute_Error_BindsSession() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); NotLogged(() => sut.Execute(() => { throw new Exception(); })); sut.SessionWasBound.ShouldBeTrue(); } [Test] public void ExecuteRetrieval_Error_BindsSession() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); NotLogged(() => sut.Execute<int>(() => { throw new Exception(); })); sut.SessionWasBound.ShouldBeTrue(); } [Test] public void ExecuteRetrieval_Error_ReturnsDefaultOfTResult() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); int result = 1; NotLogged(() => result = sut.Execute<int>(() => { throw new Exception(); })); result.ShouldBeEqualTo(0); } [Test] public void ExecuteRetrieval_NoError_ReturnsResultOfAction() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); const int resultOfAction = 1; int result = 0; NotLogged(() => result = sut.Execute(() => resultOfAction)); result.ShouldBeEqualTo(resultOfAction); } [Test] public void Execute_Always_BeginsTransactionUsingSessionFromSessionFactoryManager() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); sut.Execute(() => { }); _sessionStub.Verify(s => s.BeginTransaction()); } [Test] public void Execute_NoError_CommitsTransaction() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); sut.Execute(() => { }); _transactionMock.Verify(tx => tx.Commit()); } [Test] public void Execute_Error_DoesNotCommitTransaction() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); NotLogged(() => sut.Execute(() => { throw new Exception(); })); _transactionMock.Verify(tx => tx.Commit(), Times.Never()); } [Test] public void Execute_Error_RollsBackTransaction() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); NotLogged(() => sut.Execute(() => { throw new Exception(); })); _transactionMock.Verify(tx => tx.Rollback()); } [Test] public void Execute_NoError_UnbindsSession() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); sut.Execute(() => { }); sut.SessionWasUnbound.ShouldBeTrue(); } [Test] public void ExecuteRetrieval_NoError_UnbindsSession() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); sut.Execute(() => 0); sut.SessionWasUnbound.ShouldBeTrue(); } [Test] public void Execute_Error_UnbindsSession() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); NotLogged(() => sut.Execute(() => { throw new Exception(); })); sut.SessionWasUnbound.ShouldBeTrue(); } [Test] public void ExecuteRetrieval_Error_UnbindsSession() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); NotLogged(() => sut.Execute<int>(() => { throw new Exception(); })); sut.SessionWasUnbound.ShouldBeTrue(); } [Test] public void BatchExecute_Always_OpensStatelessSession() { var sessionFactoryMock = _sessionFactoryStub; var sut = new TransactionManagerMock(sessionFactoryMock.Object); sut.BatchExecute(s => { }); sessionFactoryMock.Verify(sf => sf.OpenStatelessSession()); } [Test] public void BatchExecute_NoError_CommitsTransaction() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); sut.BatchExecute(s => { }); _transactionMock.Verify(tx => tx.Commit()); } [Test] public void BatchExecute_Error_DoesNotCommitTransaction() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); NotLogged(() => sut.BatchExecute(s => { throw new Exception(); })); _transactionMock.Verify(tx => tx.Commit(), Times.Never()); } [Test] public void BatchExecute_Error_RollsBackTransaction() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); NotLogged(() => sut.BatchExecute(s => { throw new Exception(); })); _transactionMock.Verify(tx => tx.Rollback()); } [Test] public void BatchExecute_Always_ExecutesAction() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); bool actionWasExecuted = false; sut.BatchExecute(s => actionWasExecuted = true); actionWasExecuted.ShouldBeTrue(); } [Test] public void Execute_Always_ExecutesAction() { var sut = new TransactionManagerMock(_sessionFactoryStub.Object); bool actionWasExecuted = false; sut.Execute(() => actionWasExecuted = true); actionWasExecuted.ShouldBeTrue(); } } internal class TransactionManagerMock : TransactionManager { public TransactionManagerMock(ISessionFactoryManager sessionFactoryManager) : base(sessionFactoryManager) { SessionWasBound = false; SessionWasUnbound = false; } public bool SessionWasBound; public bool SessionWasUnbound; protected override void OpenAndBindSession() { SessionWasBound = true; } protected override void UnbindSession() { SessionWasUnbound = 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.Net; using System.Reflection; using System.Threading; using log4net; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Client; namespace OpenSim.Tests.Common.Mock { public class TestClient : IClientAPI, IClientCore { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // Mock testing variables public List<ImageDataPacket> sentdatapkt = new List<ImageDataPacket>(); public List<ImagePacketPacket> sentpktpkt = new List<ImagePacketPacket>(); EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing"); // TODO: This is a really nasty (and temporary) means of telling the test client which scene to invoke setup // methods on when a teleport is requested public Scene TeleportTargetScene; private TestClient TeleportSceneClient; private IScene m_scene; // disable warning: public events, part of the public API #pragma warning disable 67 public event Action<IClientAPI> OnLogout; public event ObjectPermissions OnObjectPermissions; public event MoneyTransferRequest OnMoneyTransferRequest; public event ParcelBuy OnParcelBuy; public event Action<IClientAPI> OnConnectionClosed; public event ImprovedInstantMessage OnInstantMessage; public event ChatMessage OnChatFromClient; public event TextureRequest OnRequestTexture; public event RezObject OnRezObject; public event ModifyTerrain OnModifyTerrain; public event BakeTerrain OnBakeTerrain; public event SetAppearance OnSetAppearance; public event AvatarNowWearing OnAvatarNowWearing; public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv; public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv; public event UUIDNameRequest OnDetachAttachmentIntoInv; public event ObjectAttach OnObjectAttach; public event ObjectDeselect OnObjectDetach; public event ObjectDrop OnObjectDrop; public event StartAnim OnStartAnim; public event StopAnim OnStopAnim; public event LinkObjects OnLinkObjects; public event DelinkObjects OnDelinkObjects; public event RequestMapBlocks OnRequestMapBlocks; public event RequestMapName OnMapNameRequest; public event TeleportLocationRequest OnTeleportLocationRequest; public event TeleportLandmarkRequest OnTeleportLandmarkRequest; public event DisconnectUser OnDisconnectUser; public event RequestAvatarProperties OnRequestAvatarProperties; public event SetAlwaysRun OnSetAlwaysRun; public event DeRezObject OnDeRezObject; public event Action<IClientAPI> OnRegionHandShakeReply; public event GenericCall2 OnRequestWearables; public event GenericCall2 OnCompleteMovementToRegion; public event UpdateAgent OnAgentUpdate; public event AgentRequestSit OnAgentRequestSit; public event AgentSit OnAgentSit; public event AvatarPickerRequest OnAvatarPickerRequest; public event Action<IClientAPI> OnRequestAvatarsData; public event AddNewPrim OnAddPrim; public event RequestGodlikePowers OnRequestGodlikePowers; public event GodKickUser OnGodKickUser; public event ObjectDuplicate OnObjectDuplicate; public event GrabObject OnGrabObject; public event DeGrabObject OnDeGrabObject; public event MoveObject OnGrabUpdate; public event SpinStart OnSpinStart; public event SpinObject OnSpinUpdate; public event SpinStop OnSpinStop; public event ViewerEffectEventHandler OnViewerEffect; public event FetchInventory OnAgentDataUpdateRequest; public event TeleportLocationRequest OnSetStartLocationRequest; public event UpdateShape OnUpdatePrimShape; public event ObjectExtraParams OnUpdateExtraParams; public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily; public event ObjectSelect OnObjectSelect; public event ObjectRequest OnObjectRequest; public event GenericCall7 OnObjectDescription; public event GenericCall7 OnObjectName; public event GenericCall7 OnObjectClickAction; public event GenericCall7 OnObjectMaterial; public event UpdatePrimFlags OnUpdatePrimFlags; public event UpdatePrimTexture OnUpdatePrimTexture; public event UpdateVector OnUpdatePrimGroupPosition; public event UpdateVector OnUpdatePrimSinglePosition; public event UpdatePrimRotation OnUpdatePrimGroupRotation; public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition; public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; public event UpdateVector OnUpdatePrimScale; public event UpdateVector OnUpdatePrimGroupScale; public event StatusChange OnChildAgentStatus; public event GenericCall2 OnStopMovement; public event Action<UUID> OnRemoveAvatar; public event CreateNewInventoryItem OnCreateNewInventoryItem; public event CreateInventoryFolder OnCreateNewInventoryFolder; public event UpdateInventoryFolder OnUpdateInventoryFolder; public event MoveInventoryFolder OnMoveInventoryFolder; public event RemoveInventoryFolder OnRemoveInventoryFolder; public event RemoveInventoryItem OnRemoveInventoryItem; public event FetchInventoryDescendents OnFetchInventoryDescendents; public event PurgeInventoryDescendents OnPurgeInventoryDescendents; public event FetchInventory OnFetchInventory; public event RequestTaskInventory OnRequestTaskInventory; public event UpdateInventoryItem OnUpdateInventoryItem; public event CopyInventoryItem OnCopyInventoryItem; public event MoveInventoryItem OnMoveInventoryItem; public event UDPAssetUploadRequest OnAssetUploadRequest; public event RequestTerrain OnRequestTerrain; public event RequestTerrain OnUploadTerrain; public event XferReceive OnXferReceive; public event RequestXfer OnRequestXfer; public event ConfirmXfer OnConfirmXfer; public event AbortXfer OnAbortXfer; public event RezScript OnRezScript; public event UpdateTaskInventory OnUpdateTaskInventory; public event MoveTaskInventory OnMoveTaskItem; public event RemoveTaskInventory OnRemoveTaskItem; public event RequestAsset OnRequestAsset; public event GenericMessage OnGenericMessage; public event UUIDNameRequest OnNameFromUUIDRequest; public event UUIDNameRequest OnUUIDGroupNameRequest; public event ParcelPropertiesRequest OnParcelPropertiesRequest; public event ParcelDivideRequest OnParcelDivideRequest; public event ParcelJoinRequest OnParcelJoinRequest; public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; public event ParcelAbandonRequest OnParcelAbandonRequest; public event ParcelGodForceOwner OnParcelGodForceOwner; public event ParcelReclaim OnParcelReclaim; public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest; public event ParcelAccessListRequest OnParcelAccessListRequest; public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest; public event ParcelSelectObjects OnParcelSelectObjects; public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; public event ParcelDeedToGroup OnParcelDeedToGroup; public event ObjectDeselect OnObjectDeselect; public event RegionInfoRequest OnRegionInfoRequest; public event EstateCovenantRequest OnEstateCovenantRequest; public event EstateChangeInfo OnEstateChangeInfo; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay; public event FriendActionDelegate OnApproveFriendRequest; public event FriendActionDelegate OnDenyFriendRequest; public event FriendshipTermination OnTerminateFriendship; public event EconomyDataRequest OnEconomyDataRequest; public event MoneyBalanceRequest OnMoneyBalanceRequest; public event UpdateAvatarProperties OnUpdateAvatarProperties; public event ObjectIncludeInSearch OnObjectIncludeInSearch; public event UUIDNameRequest OnTeleportHomeRequest; public event ScriptAnswer OnScriptAnswer; public event RequestPayPrice OnRequestPayPrice; public event ObjectSaleInfo OnObjectSaleInfo; public event ObjectBuy OnObjectBuy; public event BuyObjectInventory OnBuyObjectInventory; public event AgentSit OnUndo; public event ForceReleaseControls OnForceReleaseControls; public event GodLandStatRequest OnLandStatRequest; public event RequestObjectPropertiesFamily OnObjectGroupRequest; public event DetailedEstateDataRequest OnDetailedEstateDataRequest; public event SetEstateFlagsRequest OnSetEstateFlagsRequest; public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture; public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture; public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights; public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest; public event SetRegionTerrainSettings OnSetRegionTerrainSettings; public event EstateRestartSimRequest OnEstateRestartSimRequest; public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest; public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest; public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest; public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest; public event EstateDebugRegionRequest OnEstateDebugRegionRequest; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest; public event ScriptReset OnScriptReset; public event GetScriptRunning OnGetScriptRunning; public event SetScriptRunning OnSetScriptRunning; public event UpdateVector OnAutoPilotGo; public event TerrainUnacked OnUnackedTerrain; public event RegionHandleRequest OnRegionHandleRequest; public event ParcelInfoRequest OnParcelInfoRequest; public event ActivateGesture OnActivateGesture; public event DeactivateGesture OnDeactivateGesture; public event ObjectOwner OnObjectOwner; public event DirPlacesQuery OnDirPlacesQuery; public event DirFindQuery OnDirFindQuery; public event DirLandQuery OnDirLandQuery; public event DirPopularQuery OnDirPopularQuery; public event DirClassifiedQuery OnDirClassifiedQuery; public event EventInfoRequest OnEventInfoRequest; public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime; public event MapItemRequest OnMapItemRequest; public event OfferCallingCard OnOfferCallingCard; public event AcceptCallingCard OnAcceptCallingCard; public event DeclineCallingCard OnDeclineCallingCard; public event SoundTrigger OnSoundTrigger; public event StartLure OnStartLure; public event TeleportLureRequest OnTeleportLureRequest; public event NetworkStats OnNetworkStatsUpdate; public event ClassifiedInfoRequest OnClassifiedInfoRequest; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate; public event ClassifiedDelete OnClassifiedDelete; public event ClassifiedDelete OnClassifiedGodDelete; public event EventNotificationAddRequest OnEventNotificationAddRequest; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest; public event EventGodDelete OnEventGodDelete; public event ParcelDwellRequest OnParcelDwellRequest; public event UserInfoRequest OnUserInfoRequest; public event UpdateUserInfo OnUpdateUserInfo; public event RetrieveInstantMessages OnRetrieveInstantMessages; public event PickDelete OnPickDelete; public event PickGodDelete OnPickGodDelete; public event PickInfoUpdate OnPickInfoUpdate; public event AvatarNotesUpdate OnAvatarNotesUpdate; public event MuteListRequest OnMuteListRequest; public event AvatarInterestUpdate OnAvatarInterestUpdate; public event PlacesQuery OnPlacesQuery; #pragma warning restore 67 /// <value> /// This agent's UUID /// </value> private UUID m_agentId; /// <value> /// The last caps seed url that this client was given. /// </value> public string CapsSeedUrl; private Vector3 startPos = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 2); public virtual Vector3 StartPos { get { return startPos; } set { } } public virtual UUID AgentId { get { return m_agentId; } } public UUID SessionId { get { return UUID.Zero; } } public UUID SecureSessionId { get { return UUID.Zero; } } public virtual string FirstName { get { return m_firstName; } } private string m_firstName; public virtual string LastName { get { return m_lastName; } } private string m_lastName; public virtual String Name { get { return FirstName + " " + LastName; } } public bool IsActive { get { return true; } set { } } public UUID ActiveGroupId { get { return UUID.Zero; } } public string ActiveGroupName { get { return String.Empty; } } public ulong ActiveGroupPowers { get { return 0; } } public bool IsGroupMember(UUID groupID) { return false; } public ulong GetGroupPowers(UUID groupID) { return 0; } public virtual int NextAnimationSequenceNumber { get { return 1; } } public IScene Scene { get { return m_scene; } } public bool SendLogoutPacketWhenClosing { set { } } private uint m_circuitCode; public uint CircuitCode { get { return m_circuitCode; } set { m_circuitCode = value; } } /// <summary> /// Constructor /// </summary> /// <param name="agentData"></param> /// <param name="scene"></param> public TestClient(AgentCircuitData agentData, IScene scene) { m_agentId = agentData.AgentID; m_firstName = agentData.firstname; m_lastName = agentData.lastname; m_circuitCode = agentData.circuitcode; m_scene = scene; CapsSeedUrl = agentData.CapsPath; } /// <summary> /// Attempt a teleport to the given region. /// </summary> /// <param name="regionHandle"></param> /// <param name="position"></param> /// <param name="lookAt"></param> public void Teleport(ulong regionHandle, Vector3 position, Vector3 lookAt) { OnTeleportLocationRequest(this, regionHandle, position, lookAt, 16); } public void CompleteMovement() { OnCompleteMovementToRegion(); } public virtual void ActivateGesture(UUID assetId, UUID gestureId) { } public virtual void SendWearables(AvatarWearable[] wearables, int serial) { } public virtual void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry) { } public virtual void Kick(string message) { } public virtual void SendStartPingCheck(byte seq) { } public virtual void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data) { } public virtual void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { } public virtual void SendKillObject(ulong regionHandle, uint localID) { } public virtual void SetChildAgentThrottle(byte[] throttle) { } public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; } public virtual void SendAnimations(UUID[] animations, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { } public virtual void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { } public virtual void SendChatMessage(byte[] message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { } public void SendInstantMessage(GridInstantMessage im) { } public void SendGenericMessage(string method, List<string> message) { } public virtual void SendLayerData(float[] map) { } public virtual void SendLayerData(int px, int py, float[] map) { } public virtual void SendLayerData(int px, int py, float[] map, bool track) { } public virtual void SendWindData(Vector2[] windSpeeds) { } public virtual void SendCloudData(float[] cloudCover) { } public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { } public virtual AgentCircuitData RequestClientInfo() { AgentCircuitData agentData = new AgentCircuitData(); agentData.AgentID = AgentId; agentData.SessionID = UUID.Zero; agentData.SecureSessionID = UUID.Zero; agentData.circuitcode = m_circuitCode; agentData.child = false; agentData.firstname = m_firstName; agentData.lastname = m_lastName; ICapabilitiesModule capsModule = m_scene.RequestModuleInterface<ICapabilitiesModule>(); agentData.CapsPath = capsModule.GetCapsPath(m_agentId); agentData.ChildrenCapSeeds = new Dictionary<ulong, string>(capsModule.GetChildrenSeeds(m_agentId)); return agentData; } public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { m_log.DebugFormat("[TEST CLIENT]: Processing inform client of neighbour"); // In response to this message, we are going to make a teleport to the scene we've previous been told // about by test code (this needs to be improved). AgentCircuitData newAgent = RequestClientInfo(); // Stage 2: add the new client as a child agent to the scene TeleportSceneClient = new TestClient(newAgent, TeleportTargetScene); TeleportTargetScene.AddNewClient(TeleportSceneClient); } public virtual void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL) { m_log.DebugFormat("[TEST CLIENT]: Received SendRegionTeleport"); CapsSeedUrl = capsURL; TeleportSceneClient.CompleteMovement(); //TeleportTargetScene.AgentCrossing(newAgent.AgentID, new Vector3(90, 90, 90), false); } public virtual void SendTeleportFailed(string reason) { m_log.DebugFormat("[TEST CLIENT]: Teleport failed with reason {0}", reason); } public virtual void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL) { // This is supposed to send a packet to the client telling it's ready to start region crossing. // Instead I will just signal I'm ready, mimicking the communication behavior. // It's ugly, but avoids needless communication setup. This is used in ScenePresenceTests.cs. // Arthur V. wh.Set(); } public virtual void SendMapBlock(List<MapBlockData> mapBlocks, uint flag) { } public virtual void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags) { } public virtual void SendTeleportLocationStart() { } public virtual void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance) { } public virtual void SendPayPrice(UUID objectID, int[] payPrice) { } public virtual void SendAvatarData(ulong regionHandle, string firstName, string lastName, string grouptitle, UUID avatarID, uint avatarLocalID, Vector3 Pos, byte[] textureEntry, uint parentID, Quaternion rotation) { } public virtual void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, Vector3 position, Vector3 velocity, Quaternion rotation, UUID agentid) { } public virtual void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations) { } public virtual void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID) { } public virtual void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) { } public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, Vector3 pos, Vector3 vel, Vector3 acc, Quaternion rotation, Vector3 rvel, uint flags, UUID objectID, UUID ownerID, string text, byte[] color, uint parentID, byte[] particleSystem, byte clickAction, byte material) { } public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, Vector3 pos, Vector3 vel, Vector3 acc, Quaternion rotation, Vector3 rvel, uint flags, UUID objectID, UUID ownerID, string text, byte[] color, uint parentID, byte[] particleSystem, byte clickAction, byte material, byte[] textureanimation, bool attachment, uint AttachmentPoint, UUID AssetId, UUID SoundId, double SoundVolume, byte SoundFlags, double SoundRadius) { } public virtual void SendPrimTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, Vector3 position, Quaternion rotation, Vector3 velocity, Vector3 rotationalvelocity, byte state, UUID AssetId, UUID ownerID, int attachPoint) { } public void FlushPrimUpdates() { } public virtual void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, bool fetchFolders, bool fetchItems) { } public virtual void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { } public virtual void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackID) { } public virtual void SendRemoveInventoryItem(UUID itemID) { } public virtual void SendBulkUpdateInventory(InventoryNodeBase node) { } public UUID GetDefaultAnimation(string name) { return UUID.Zero; } public void SendTakeControls(int controls, bool passToAgent, bool TakeControls) { } public virtual void SendTaskInventory(UUID taskID, short serial, byte[] fileName) { } public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data) { } public virtual void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { } public virtual void SendNameReply(UUID profileId, string firstname, string lastname) { } public virtual void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID) { } public virtual void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags) { } public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain) { } public void SendAttachedSoundGainChange(UUID objectID, float gain) { } public void SendAlertMessage(string message) { } public void SendAgentAlertMessage(string message, bool modal) { } public void SendSystemAlertMessage(string message) { } public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { } public virtual void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args) { if (OnRegionHandShakeReply != null) { OnRegionHandShakeReply(this); } if (OnCompleteMovementToRegion != null) { OnCompleteMovementToRegion(); } } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) { } public void SendConfirmXfer(ulong xferID, uint PacketID) { } public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName) { } public void SendInitiateDownload(string simFileName, string clientFileName) { } public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { ImageDataPacket im = new ImageDataPacket(); im.Header.Reliable = false; im.ImageID.Packets = numParts; im.ImageID.ID = ImageUUID; if (ImageSize > 0) im.ImageID.Size = ImageSize; im.ImageData.Data = ImageData; im.ImageID.Codec = imageCodec; im.Header.Zerocoded = true; sentdatapkt.Add(im); } public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData) { ImagePacketPacket im = new ImagePacketPacket(); im.Header.Reliable = false; im.ImageID.Packet = partNumber; im.ImageID.ID = imageUuid; im.ImageData.Data = imageData; sentpktpkt.Add(im); } public void SendImageNotFound(UUID imageid) { } public void SendShutdownConnectionNotice() { } public void SendSimStats(SimStats stats) { } public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType,int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description) { } public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice) { } public void SendAgentOffline(UUID[] agentIDs) { } public void SendAgentOnline(UUID[] agentIDs) { } public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook) { } public void SendAdminResponse(UUID Token, uint AdminLevel) { } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { } public bool AddMoney(int debit) { return false; } public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong time, uint dlen, uint ylen, float phase) { } public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks) { } public void SendViewerTime(int phase) { } public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) { } public void SetDebugPacketLevel(int newDebug) { } public void InPacket(object NewPack) { } public void ProcessInPacket(Packet NewPack) { } public void Close(bool ShutdownCircuit) { m_scene.RemoveClient(AgentId); } public void Start() { } public void Stop() { } public void SendBlueBoxMessage(UUID FromAvatarID, String FromAvatarName, String Message) { } public void SendLogoutPacket() { } public void Terminate() { } public EndPoint GetClientEP() { return null; } public ClientInfo GetClientInfo() { return null; } public void SetClientInfo(ClientInfo info) { } public void SendScriptQuestion(UUID objectID, string taskName, string ownerName, UUID itemID, int question) { } public void SendHealth(float health) { } public void SendEstateManagersList(UUID invoice, UUID[] EstateManagers, uint estateID) { } public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID) { } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { } public void SendEstateCovenantInformation(UUID covenant) { } public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner) { } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { } public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID) { } public void SendForceClientSelectObjects(List<uint> objectIDs) { } public void SendCameraConstraint(Vector4 ConstraintPlane) { } public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount) { } public void SendLandParcelOverlay(byte[] data, int sequence_id) { } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { } public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { } public void SendGroupNameReply(UUID groupLLUID, string GroupName) { } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia) { } public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running) { } public void SendAsset(AssetRequestToClient req) { } public void SendTexture(AssetBase TextureAsset) { } public void SendSetFollowCamProperties (UUID objectID, SortedDictionary<int, float> parameters) { } public void SendClearFollowCamProperties (UUID objectID) { } public void SendRegionHandle (UUID regoinID, ulong handle) { } public void SendParcelInfo (RegionInfo info, LandData land, UUID parcelID, uint x, uint y) { } public void SetClientOption(string option, string value) { } public string GetClientOption(string option) { return string.Empty; } public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt) { } public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data) { } public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data) { } public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data) { } public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data) { } public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data) { } public void SendDirLandReply(UUID queryID, DirLandReplyData[] data) { } public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data) { } public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { } public void KillEndDone() { } public void SendEventInfoReply (EventData info) { } public void SendOfferCallingCard (UUID destID, UUID transactionID) { } public void SendAcceptCallingCard (UUID transactionID) { } public void SendDeclineCallingCard (UUID transactionID) { } public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) { } public void SendJoinGroupReply(UUID groupID, bool success) { } public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool succss) { } public void SendLeaveGroupReply(UUID groupID, bool success) { } public void SendTerminateFriend(UUID exFriendID) { } public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) { //throw new NotImplementedException(); return false; } public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name) { } public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { } public void SendAgentDropGroup(UUID groupID) { } public void SendAvatarNotesReply(UUID targetID, string text) { } public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks) { } public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds) { } public void SendParcelDwellReply(int localID, UUID parcelID, float dwell) { } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { } public void SendCreateGroupReply(UUID groupID, bool success, string message) { } public void RefreshGroupMembership() { } public void SendUseCachedMuteList() { } public void SendMuteListUpdate(string filename) { } public void SendPickInfoReply(UUID pickID,UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled) { } public bool TryGet<T>(out T iface) { iface = default(T); return false; } public T Get<T>() { return default(T); } public void Disconnect(string reason) { } public void Disconnect() { } } }
namespace Epi.Windows.Analysis.Dialogs { partial class DeleteFileTableDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DeleteFileTableDialog)); this.gbxDelete = new System.Windows.Forms.GroupBox(); this.rdbView = new System.Windows.Forms.RadioButton(); this.rdbTable = new System.Windows.Forms.RadioButton(); this.rdbFiles = new System.Windows.Forms.RadioButton(); this.btnEllipse = new System.Windows.Forms.Button(); this.txtFileName = new System.Windows.Forms.TextBox(); this.lblFileName = new System.Windows.Forms.Label(); this.cbkRunSilent = new System.Windows.Forms.CheckBox(); this.btnHelp = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnSaveOnly = new System.Windows.Forms.Button(); this.cmbTableName = new System.Windows.Forms.ComboBox(); this.lblTableName = new System.Windows.Forms.Label(); this.cbxSaveDataTables = new System.Windows.Forms.CheckBox(); this.lblDatabase = new System.Windows.Forms.Label(); this.lblViewName = new System.Windows.Forms.Label(); this.lblDataFormat = new System.Windows.Forms.Label(); this.cmbDataFormats = new System.Windows.Forms.ComboBox(); this.gbxDelete.SuspendLayout(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); // // gbxDelete // this.gbxDelete.Controls.Add(this.rdbView); this.gbxDelete.Controls.Add(this.rdbTable); this.gbxDelete.Controls.Add(this.rdbFiles); this.gbxDelete.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.gbxDelete, "gbxDelete"); this.gbxDelete.Name = "gbxDelete"; this.gbxDelete.TabStop = false; // // rdbView // resources.ApplyResources(this.rdbView, "rdbView"); this.rdbView.Name = "rdbView"; this.rdbView.Click += new System.EventHandler(this.RadioButtonClick); // // rdbTable // resources.ApplyResources(this.rdbTable, "rdbTable"); this.rdbTable.Name = "rdbTable"; this.rdbTable.Click += new System.EventHandler(this.RadioButtonClick); // // rdbFiles // this.rdbFiles.Checked = true; resources.ApplyResources(this.rdbFiles, "rdbFiles"); this.rdbFiles.Name = "rdbFiles"; this.rdbFiles.TabStop = true; this.rdbFiles.Click += new System.EventHandler(this.RadioButtonClick); // // btnEllipse // resources.ApplyResources(this.btnEllipse, "btnEllipse"); this.btnEllipse.Name = "btnEllipse"; this.btnEllipse.Click += new System.EventHandler(this.btnEllipse_Click); // // txtFileName // resources.ApplyResources(this.txtFileName, "txtFileName"); this.txtFileName.Name = "txtFileName"; this.txtFileName.TextChanged += new System.EventHandler(this.txtFileName_TextChanged); this.txtFileName.Leave += new System.EventHandler(this.txtFileName_Leave); // // lblFileName // this.lblFileName.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblFileName, "lblFileName"); this.lblFileName.Name = "lblFileName"; // // cbkRunSilent // resources.ApplyResources(this.cbkRunSilent, "cbkRunSilent"); this.cbkRunSilent.Name = "cbkRunSilent"; // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnSaveOnly // resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly"); this.btnSaveOnly.Name = "btnSaveOnly"; // // cmbTableName // this.cmbTableName.Items.AddRange(new object[] { resources.GetString("cmbTableName.Items"), resources.GetString("cmbTableName.Items1"), resources.GetString("cmbTableName.Items2")}); resources.ApplyResources(this.cmbTableName, "cmbTableName"); this.cmbTableName.Name = "cmbTableName"; this.cmbTableName.SelectedValueChanged += new System.EventHandler(this.TableNameValidate); this.cmbTableName.TextChanged += new System.EventHandler(this.TableNameValidate); this.cmbTableName.Leave += new System.EventHandler(this.TableNameValidate); // // lblTableName // this.lblTableName.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblTableName, "lblTableName"); this.lblTableName.Name = "lblTableName"; // // cbxSaveDataTables // resources.ApplyResources(this.cbxSaveDataTables, "cbxSaveDataTables"); this.cbxSaveDataTables.Name = "cbxSaveDataTables"; // // lblDatabase // resources.ApplyResources(this.lblDatabase, "lblDatabase"); this.lblDatabase.Name = "lblDatabase"; // // lblViewName // resources.ApplyResources(this.lblViewName, "lblViewName"); this.lblViewName.Name = "lblViewName"; // // lblDataFormat // resources.ApplyResources(this.lblDataFormat, "lblDataFormat"); this.lblDataFormat.Name = "lblDataFormat"; // // cmbDataFormats // this.cmbDataFormats.FormattingEnabled = true; resources.ApplyResources(this.cmbDataFormats, "cmbDataFormats"); this.cmbDataFormats.Name = "cmbDataFormats"; this.cmbDataFormats.SelectedIndexChanged += new System.EventHandler(this.cmbDataFormats_SelectedIndexChanged); // // DeleteFileTableDialog // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.cmbDataFormats); this.Controls.Add(this.lblDataFormat); this.Controls.Add(this.cbxSaveDataTables); this.Controls.Add(this.lblTableName); this.Controls.Add(this.cmbTableName); this.Controls.Add(this.btnSaveOnly); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnClear); this.Controls.Add(this.cbkRunSilent); this.Controls.Add(this.lblFileName); this.Controls.Add(this.btnEllipse); this.Controls.Add(this.gbxDelete); this.Controls.Add(this.txtFileName); this.Controls.Add(this.lblDatabase); this.Controls.Add(this.lblViewName); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DeleteFileTableDialog"; this.ShowIcon = false; this.gbxDelete.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox gbxDelete; private System.Windows.Forms.RadioButton rdbFiles; private System.Windows.Forms.RadioButton rdbTable; private System.Windows.Forms.RadioButton rdbView; private System.Windows.Forms.Button btnEllipse; private System.Windows.Forms.TextBox txtFileName; private System.Windows.Forms.CheckBox cbkRunSilent; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnSaveOnly; private System.Windows.Forms.Label lblTableName; private System.Windows.Forms.ComboBox cmbTableName; private System.Windows.Forms.CheckBox cbxSaveDataTables; private System.Windows.Forms.Label lblFileName; private System.Windows.Forms.Label lblDatabase; private System.Windows.Forms.Label lblViewName; private System.Windows.Forms.Label lblDataFormat; private System.Windows.Forms.ComboBox cmbDataFormats; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using Microsoft.Its.Recipes; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Its.Domain.Serialization { public static class Serializer { private static readonly Lazy<Func<JsonSerializerSettings, JsonSerializerSettings>> cloneSettings = new Lazy<Func<JsonSerializerSettings, JsonSerializerSettings>>( () => MappingExpression.From<JsonSerializerSettings> .ToNew<JsonSerializerSettings>() .Compile()); private static readonly Lazy<JsonSerializerSettings> diagnosticSettings = new Lazy<JsonSerializerSettings>(() => { var jsonSerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, MissingMemberHandling = MissingMemberHandling.Ignore, NullValueHandling = NullValueHandling.Include, ContractResolver = new OptionalContractResolver(), DefaultValueHandling = DefaultValueHandling.Include, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Error = (sender, args) => args.ErrorContext.Handled = true }; AddConverter(new OptionalConverter()); AddConverter(new UriConverter()); return jsonSerializerSettings; }); private static readonly ConcurrentDictionary<string, Func<StoredEvent, IEvent>> deserializers = new ConcurrentDictionary<string, Func<StoredEvent, IEvent>>(); private static JsonSerializerSettings settings; public static JsonSerializerSettings Settings { get { return settings; } set { if (value == null) { ConfigureDefault(); return; } settings = value; } } static Serializer() { ConfigureDefault(); } public static void ConfigureDefault() { Settings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, ContractResolver = new OptionalContractResolver(), DefaultValueHandling = DefaultValueHandling.Include, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, DateParseHandling = DateParseHandling.DateTimeOffset }; AddConverter(new OptionalConverter()); AddConverter(new UriConverter()); } public static void AddConverter(JsonConverter converter) { Settings.Converters.Add(converter); } public static void AddPrimitiveConverter<T>( Func<T, object> serialize, Func<object, T> deserialize) { if (!Settings.Converters.Any(c => c is PrimitiveConverter<T>)) { Settings.Converters.Add(new PrimitiveConverter<T>(serialize, deserialize)); } } public static JsonSerializerSettings CloneSettings() { return cloneSettings.Value(Settings); } public static string ToJson<T>(this T obj, Formatting formatting = Formatting.None) { return JsonConvert.SerializeObject(obj, formatting, Settings); } internal static string ToDiagnosticJson<T>(this T obj) { return JsonConvert.SerializeObject(obj, Formatting.Indented, diagnosticSettings.Value); } public static T FromJsonTo<T>(this string json) { return JsonConvert.DeserializeObject<T>(json, Settings); } /// <summary> /// Deserializes a domain event. /// </summary> /// <param name="aggregateName">Name of the aggregate.</param> /// <param name="eventName">Name of the event type.</param> /// <param name="aggregateId">The aggregate identifier.</param> /// <param name="sequenceNumber">The sequence number of the event.</param> /// <param name="timestamp">The timestamp of the event.</param> /// <param name="body">The body of the event.</param> /// <param name="uniqueEventId">The unique event identifier.</param> /// <param name="serializerSettings">The serializer settings used when deserializing the event body.</param> /// <param name="etag">The ETag of the event.</param> /// <returns></returns> public static IEvent DeserializeEvent(string aggregateName, string eventName, Guid aggregateId, long sequenceNumber, DateTimeOffset timestamp, string body, dynamic uniqueEventId = null, JsonSerializerSettings serializerSettings = null, string etag = null) { var deserializerKey = aggregateName + ":" + eventName; var deserializer = deserializers.GetOrAdd(deserializerKey, _ => { var aggregateType = AggregateType.KnownTypes.SingleOrDefault(t => t.Name == aggregateName); if (aggregateType != null) { serializerSettings = serializerSettings ?? Settings; IEnumerable<Type> eventTypes = typeof (Event<>).MakeGenericType(aggregateType).Member().KnownTypes; // some events contain specialized names, e.g. CommandScheduled:DoSomething. the latter portion is not interesting from a serialization standpoint, so we strip it off. var eventNameComponents = eventName.Split(':'); eventName = eventNameComponents.First(); var eventType = eventTypes.SingleOrDefault(t => t.GetCustomAttributes(false) .OfType<EventNameAttribute>() .FirstOrDefault() .IfNotNull() .Then( att => att.EventName == eventName) .Else(() => // strip off generic specifications from the type name t.Name.Split('`').First() == eventName)); if (eventType != null) { if (typeof(IScheduledCommand).IsAssignableFrom(eventType)) { var commandType = Command.FindType(aggregateType, eventNameComponents.Last()); if (commandType == null) { return UseAnonymousEvent(serializerSettings, aggregateType); } } return e => { var deserializedEvent = (IEvent) JsonConvert.DeserializeObject(e.Body, eventType, serializerSettings); var dEvent = deserializedEvent as Event; if (dEvent != null) { dEvent.AggregateId = e.AggregateId; dEvent.SequenceNumber = e.SequenceNumber; dEvent.Timestamp = e.Timestamp; dEvent.ETag = e.ETag; } return deserializedEvent; }; } // even if the domain no longer cares about some old event type, anonymous events are returned as placeholders in the EventSequence return UseAnonymousEvent(serializerSettings, aggregateType); } return e => { dynamic deserializeObject = JsonConvert.DeserializeObject(e.Body, serializerSettings); var dynamicEvent = new DynamicEvent(deserializeObject) { EventStreamName = e.StreamName, EventTypeName = e.EventTypeName, AggregateId = e.AggregateId, SequenceNumber = e.SequenceNumber, Timestamp = e.Timestamp, ETag = e.ETag }; return dynamicEvent; }; }); var @event = deserializer( new StoredEvent { StreamName = aggregateName, EventTypeName = eventName, Body = body, AggregateId = aggregateId, SequenceNumber = sequenceNumber, Timestamp = timestamp, ETag = etag }); if (uniqueEventId != null) { @event.IfTypeIs<IHaveExtensibleMetada>() .Then(e => e.Metadata.AbsoluteSequenceNumber = uniqueEventId); } return @event; } private static Func<StoredEvent, IEvent> UseAnonymousEvent(JsonSerializerSettings serializerSettings, Type aggregateType) { return e => { var anonymousEvent = (Event) JsonConvert.DeserializeObject(e.Body, typeof (AnonymousEvent<>).MakeGenericType(aggregateType), serializerSettings); anonymousEvent.AggregateId = e.AggregateId; anonymousEvent.SequenceNumber = e.SequenceNumber; anonymousEvent.Timestamp = e.Timestamp; anonymousEvent.ETag = e.ETag; ((dynamic) anonymousEvent).Body = e.Body; return anonymousEvent; }; } public static IEnumerable<IEvent> FromJsonToEvents(string json) { JArray jsonEvents = JArray.Parse(json); return jsonEvents.OfType<JObject>() .Select(o => new { o.Properties().Single().Name, o.Properties().Single().Value }) .Select(nameAndBody => { var split = nameAndBody.Name.Split('.'); var aggregateTypeName = split[0]; var eventTypeName = split[1]; var aggregateType = AggregateType.KnownTypes .SingleOrDefault(t => t.Name == aggregateTypeName); return new { EventType = Event.KnownTypesForAggregateType(aggregateType) .SingleOrDefault(t => Equals(t.Name, eventTypeName)), Body = nameAndBody.Value.ToString() }; }) .Where(typeAndBody => typeAndBody.EventType != null) .Select(typeAndBody => JsonConvert.DeserializeObject(typeAndBody.Body, typeAndBody.EventType, Settings)) .Cast<IEvent>(); } private struct StoredEvent { public string StreamName; public string EventTypeName; public string Body; public Guid AggregateId; public long SequenceNumber; public DateTimeOffset Timestamp; public string ETag { get; set; } } } }
using AutoBogus.Util; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Binder = Bogus.Binder; namespace AutoBogus { /// <summary> /// A class for binding generated instances. /// </summary> public class AutoBinder : Binder, IAutoBinder { /// <summary> /// Creates an instance of <typeparamref name="TType"/>. /// </summary> /// <typeparam name="TType">The type of instance to create.</typeparam> /// <param name="context">The <see cref="AutoGenerateContext"/> instance for the generate request.</param> /// <returns>The created instance of <typeparamref name="TType"/>.</returns> public virtual TType CreateInstance<TType>(AutoGenerateContext context) { if (context != null) { var type = typeof(TType); var constructor = GetConstructor<TType>(); if (constructor != null) { // If a constructor is found generate values for each of the parameters var parameters = (from p in constructor.GetParameters() let g = GetParameterGenerator(type, p, context) select g.Generate(context)).ToArray(); return (TType)constructor.Invoke(parameters); } } return default; } /// <summary> /// Populates the provided instance with generated values. /// </summary> /// <typeparam name="TType">The type of instance to populate.</typeparam> /// <param name="instance">The instance to populate.</param> /// <param name="context">The <see cref="AutoGenerateContext"/> instance for the generate request.</param> /// <param name="members">An optional collection of members to populate. If null, all writable instance members are populated.</param> /// <remarks> /// Due to the boxing nature of value types, the <paramref name="instance"/> parameter is an object. This means the populated /// values are applied to the provided instance and not a copy. /// </remarks> public virtual void PopulateInstance<TType>(object instance, AutoGenerateContext context, IEnumerable<MemberInfo> members = null) { var type = typeof(TType); // We can only populate non-null instances if (instance == null || context == null) { return; } // Iterate the members and bind a generated value var autoMembers = GetMembersToPopulate(type, members); foreach (var member in autoMembers) { if (member.Type != null) { // Check if the member has a skip config or the type has already been generated as a parent // If so skip this generation otherwise track it for use later in the object tree if (ShouldSkip(member.Type, $"{type.FullName}.{member.Name}", context)) { continue; } context.ParentType = type; context.GenerateType = member.Type; context.GenerateName = member.Name; context.TypesStack.Push(member.Type); // Generate a random value and bind it to the instance var generator = AutoGeneratorFactory.GetGenerator(context); var value = generator.Generate(context); try { if (!member.IsReadOnly) { member.Setter.Invoke(instance, value); } else if (ReflectionHelper.IsDictionary(member.Type)) { PopulateDictionary(value, instance, member); } else if (ReflectionHelper.IsCollection(member.Type)) { PopulateCollection(value, instance, member); } } catch { } // Remove the current type from the type stack so siblings can be created context.TypesStack.Pop(); } } } private bool ShouldSkip(Type type, string path, AutoGenerateContext context) { // Skip if the type is found if (context.Config.SkipTypes.Contains(type)) { return true; } // Skip if the path is found if (context.Config.SkipPaths.Contains(path)) { return true; } //check if tree depth is reached var treeDepth = context.Config.TreeDepth.Invoke(context); if (treeDepth.HasValue && context.TypesStack.Count() >= treeDepth) return true; // Finally check if the recursive depth has been reached var count = context.TypesStack.Count(t => t == type); var recursiveDepth = context.Config.RecursiveDepth.Invoke(context); return count >= recursiveDepth; } private ConstructorInfo GetConstructor<TType>() { var type = typeof(TType); var constructors = type.GetConstructors(); // For dictionaries and enumerables locate a constructor that is used for populating as well if (ReflectionHelper.IsDictionary(type)) { return ResolveTypedConstructor(typeof(IDictionary<,>), constructors); } if (ReflectionHelper.IsEnumerable(type)) { return ResolveTypedConstructor(typeof(IEnumerable<>), constructors); } // Attempt to find a default constructor // If one is not found, simply use the first in the list var defaultConstructor = (from c in constructors let p = c.GetParameters() where p.Count() == 0 select c).SingleOrDefault(); return defaultConstructor ?? constructors.FirstOrDefault(); } private ConstructorInfo ResolveTypedConstructor(Type type, IEnumerable<ConstructorInfo> constructors) { // Find the first constructor that matches the passed generic definition return (from c in constructors let p = c.GetParameters() where p.Count() == 1 let m = p.Single() where ReflectionHelper.IsGenericType(m.ParameterType) let d = ReflectionHelper.GetGenericTypeDefinition(m.ParameterType) where d == type select c).SingleOrDefault(); } private IAutoGenerator GetParameterGenerator(Type type, ParameterInfo parameter, AutoGenerateContext context) { context.ParentType = type; context.GenerateType = parameter.ParameterType; context.GenerateName = parameter.Name; return AutoGeneratorFactory.GetGenerator(context); } private IEnumerable<AutoMember> GetMembersToPopulate(Type type, IEnumerable<MemberInfo> members) { // If a list of members is provided, no others should be populated if (members != null) { return members.Select(member => new AutoMember(member)); } // Get the baseline members resolved by Bogus var autoMembers = (from m in GetMembers(type) select new AutoMember(m.Value)).ToList(); foreach (var member in type.GetMembers(BindingFlags)) { // Then check if any other members can be populated var autoMember = new AutoMember(member); if (!autoMembers.Any(baseMember => autoMember.Name == baseMember.Name)) { // A readonly dictionary or collection member can use the Add() method if (autoMember.IsReadOnly && ReflectionHelper.IsDictionary(autoMember.Type)) { autoMembers.Add(autoMember); } else if (autoMember.IsReadOnly && ReflectionHelper.IsCollection(autoMember.Type)) { autoMembers.Add(autoMember); } } } return autoMembers; } private void PopulateDictionary(object value, object parent, AutoMember member) { var instance = member.Getter(parent); var argTypes = GetAddMethodArgumentTypes(member.Type); var addMethod = GetAddMethod(member.Type, argTypes); if (instance != null && addMethod != null && value is IDictionary dictionary) { foreach (var key in dictionary.Keys) { addMethod.Invoke(instance, new[] { key, dictionary[key] }); } } } private void PopulateCollection(object value, object parent, AutoMember member) { var instance = member.Getter(parent); var argTypes = GetAddMethodArgumentTypes(member.Type); var addMethod = GetAddMethod(member.Type, argTypes); if (instance != null && addMethod != null && value is ICollection collection) { foreach (var item in collection) { addMethod.Invoke(instance, new[] { item }); } } } private MethodInfo GetAddMethod(Type type, Type[] argTypes) { // First try directly on the type var method = type.GetMethod("Add", argTypes); if (method == null) { // Then traverse the type interfaces return (from i in type.GetInterfaces() let m = GetAddMethod(i, argTypes) where m != null select m).FirstOrDefault(); } return method; } private Type[] GetAddMethodArgumentTypes(Type type) { var types = new[] { typeof(object) }; if (ReflectionHelper.IsGenericType(type)) { var generics = ReflectionHelper.GetGenericArguments(type); types = generics.ToArray(); } return types; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Expressions.Cpp2; using Microsoft.TemplateEngine.Core.Operations; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Config; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Localization; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros.Config; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects { public class SimpleConfigModel : IRunnableProjectConfig { private static readonly string NameSymbolName = "name"; private static readonly string[] IncludePatternDefaults = new[] { "**/*" }; private static readonly string[] ExcludePatternDefaults = new[] { "**/[Bb]in/**", "**/[Oo]bj/**", "**/" + RunnableProjectGenerator.TemplateConfigDirectoryName + "/**", "**/*.filelist", "**/*.user", "**/*.lock.json" }; private static readonly string[] CopyOnlyPatternDefaults = new[] { "**/node_modules/**" }; private static readonly Dictionary<string, string> RenameDefaults = new Dictionary<string, string>(StringComparer.Ordinal); public SimpleConfigModel() { Sources = new[] { new ExtendedFileSource() }; } private IReadOnlyDictionary<string, Parameter> _parameters; private IReadOnlyList<FileSourceMatchInfo> _sources; private IGlobalRunConfig _operationConfig; private IReadOnlyList<KeyValuePair<string, IGlobalRunConfig>> _specialOperationConfig; private Parameter _nameParameter; public IFile SourceFile { get; set; } public string Author { get; set; } public IReadOnlyList<string> Classifications { get; set; } public string DefaultName { get; set; } public string Description { get; set; } public string GroupIdentity { get; set; } public int Precedence { get; set; } public IReadOnlyList<Guid> Guids { get; set; } public string Name { get; set; } public IReadOnlyList<string> ShortNameList { get; set; } public string SourceName { get; set; } public IReadOnlyList<ExtendedFileSource> Sources { get; set; } public IReadOnlyDictionary<string, ISymbolModel> Symbols { get; set; } public IReadOnlyList<IPostActionModel> PostActionModel { get; set; } public IReadOnlyList<ICreationPathModel> PrimaryOutputs { get; set; } public string GeneratorVersions { get; set; } public IReadOnlyDictionary<string, IBaselineInfo> BaselineInfo { get; set; } public bool HasScriptRunningPostActions { get; set; } public DateTime? ConfigTimestampUtc { get; set; } private IReadOnlyDictionary<string, string> _tagsDeprecated; public IReadOnlyDictionary<string, ICacheTag> Tags { get { Dictionary<string, ICacheTag> tags = new Dictionary<string, ICacheTag>(); foreach (KeyValuePair<string, ParameterSymbol> tagParameter in TagDetails) { string defaultValue; if (string.IsNullOrEmpty(tagParameter.Value.DefaultValue) && (tagParameter.Value.Choices.Count == 1)) { defaultValue = tagParameter.Value.Choices.Keys.First(); } else { defaultValue = tagParameter.Value.DefaultValue; } ICacheTag cacheTag = new CacheTag(tagParameter.Value.Description, tagParameter.Value.Choices, defaultValue, tagParameter.Value.DefaultIfOptionWithoutValue); tags.Add(tagParameter.Key, cacheTag); } return tags; } } private IReadOnlyDictionary<string, ParameterSymbol> _tagDetails; // Converts "choice" datatype parameter symbols to tags public IReadOnlyDictionary<string, ParameterSymbol> TagDetails { get { if (_tagDetails == null) { Dictionary<string, ParameterSymbol> tempTagDetails = new Dictionary<string, ParameterSymbol>(); foreach (KeyValuePair<string, ISymbolModel> symbolInfo in Symbols) { ParameterSymbol tagSymbol = symbolInfo.Value as ParameterSymbol; if (tagSymbol != null && tagSymbol.DataType == "choice") { tempTagDetails.Add(symbolInfo.Key, tagSymbol); } } _tagDetails = tempTagDetails; } return _tagDetails; } } private IReadOnlyDictionary<string, ICacheParameter> _cacheParameters; // Converts non-choice parameter symbols to cache parameters public IReadOnlyDictionary<string, ICacheParameter> CacheParameters { get { if (_cacheParameters == null) { Dictionary<string, ICacheParameter> cacheParameters = new Dictionary<string, ICacheParameter>(); foreach (KeyValuePair<string, ISymbolModel> symbol in Symbols) { if (symbol.Value is ParameterSymbol param && param.DataType != "choice") { ICacheParameter cacheParam = new CacheParameter(param.DataType, param.DefaultValue, param.Description, param.DefaultIfOptionWithoutValue); cacheParameters.Add(symbol.Key, cacheParam); } } _cacheParameters = cacheParameters; } return _cacheParameters; } } IReadOnlyList<string> IRunnableProjectConfig.Classifications => Classifications; public IReadOnlyDictionary<string, IValueForm> Forms { get; private set; } public string Identity { get; set; } private static readonly string DefaultPlaceholderFilename = "-.-"; private string _placeholderValue; private IReadOnlyList<string> _ignoreFileNames; private bool _isPlaceholderFileNameCustomized; public string PlaceholderFilename { get { return _placeholderValue; } set { _placeholderValue = value ?? DefaultPlaceholderFilename; if (value != null) { _isPlaceholderFileNameCustomized = true; } } } public IReadOnlyList<string> IgnoreFileNames { get { return _ignoreFileNames ?? (_isPlaceholderFileNameCustomized ? new[] { PlaceholderFilename } : new[] { PlaceholderFilename, "_._" }); } set { _ignoreFileNames = value; } } IReadOnlyDictionary<string, Parameter> IRunnableProjectConfig.Parameters { get { if (_parameters == null) { Dictionary<string, Parameter> parameters = new Dictionary<string, Parameter>(); if (Symbols != null) { foreach (KeyValuePair<string, ISymbolModel> symbol in Symbols) { if (string.Equals(symbol.Value.Type, ParameterSymbol.TypeName, StringComparison.Ordinal) || string.Equals(symbol.Value.Type, DerivedSymbol.TypeName, StringComparison.Ordinal)) { BaseValueSymbol baseSymbol = (BaseValueSymbol)symbol.Value; bool isName = baseSymbol.Binding == NameSymbolName; parameters[symbol.Key] = new Parameter { DefaultValue = baseSymbol.DefaultValue ?? (!baseSymbol.IsRequired ? baseSymbol.Replaces : null), Description = baseSymbol.Description, IsName = isName, IsVariable = true, Name = symbol.Key, FileRename = baseSymbol.FileRename, Requirement = baseSymbol.IsRequired ? TemplateParameterPriority.Required : isName ? TemplateParameterPriority.Implicit : TemplateParameterPriority.Optional, Type = baseSymbol.Type, DataType = baseSymbol.DataType }; if (string.Equals(symbol.Value.Type, ParameterSymbol.TypeName, StringComparison.Ordinal)) { parameters[symbol.Key].Choices = ((ParameterSymbol)symbol.Value).Choices; parameters[symbol.Key].DefaultIfOptionWithoutValue = ((ParameterSymbol)symbol.Value).DefaultIfOptionWithoutValue; } } } } _parameters = parameters; } return _parameters; } } private Parameter NameParameter { get { if (_nameParameter == null) { IRunnableProjectConfig cfg = this; foreach (Parameter p in cfg.Parameters.Values) { if (p.IsName) { _nameParameter = p; break; } } } return _nameParameter; } } IReadOnlyList<FileSourceMatchInfo> IRunnableProjectConfig.Sources { get { if (_sources == null) { List<FileSourceMatchInfo> sources = new List<FileSourceMatchInfo>(); foreach (ExtendedFileSource source in Sources) { IReadOnlyList<string> includePattern = JTokenAsFilenameToReadOrArrayToCollection(source.Include, SourceFile, IncludePatternDefaults); IReadOnlyList<string> excludePattern = JTokenAsFilenameToReadOrArrayToCollection(source.Exclude, SourceFile, ExcludePatternDefaults); IReadOnlyList<string> copyOnlyPattern = JTokenAsFilenameToReadOrArrayToCollection(source.CopyOnly, SourceFile, CopyOnlyPatternDefaults); FileSourceEvaluable topLevelEvaluable = new FileSourceEvaluable(includePattern, excludePattern, copyOnlyPattern); IReadOnlyDictionary<string, string> renamePatterns = new Dictionary<string, string>(source.Rename ?? RenameDefaults, StringComparer.Ordinal); FileSourceMatchInfo matchInfo = new FileSourceMatchInfo( source.Source ?? "./", source.Target ?? "./", topLevelEvaluable, renamePatterns, new List<FileSourceEvaluable>()); sources.Add(matchInfo); } if (sources.Count == 0) { IReadOnlyList<string> includePattern = IncludePatternDefaults; IReadOnlyList<string> excludePattern = ExcludePatternDefaults; IReadOnlyList<string> copyOnlyPattern = CopyOnlyPatternDefaults; FileSourceEvaluable topLevelEvaluable = new FileSourceEvaluable(includePattern, excludePattern, copyOnlyPattern); FileSourceMatchInfo matchInfo = new FileSourceMatchInfo( "./", "./", topLevelEvaluable, new Dictionary<string, string>(StringComparer.Ordinal), new List<FileSourceEvaluable>()); sources.Add(matchInfo); } _sources = sources; } return _sources; } } private readonly Dictionary<Guid, string> _guidToGuidPrefixMap = new Dictionary<Guid, string>(); // operation info read from the config private ICustomFileGlobModel CustomOperations = new CustomFileGlobModel(); IGlobalRunConfig IRunnableProjectConfig.OperationConfig { get { if (_operationConfig == null) { SpecialOperationConfigParams defaultOperationParams = new SpecialOperationConfigParams(string.Empty, "//", "C++", ConditionalType.CLineComments); _operationConfig = ProduceOperationSetup(defaultOperationParams, true, CustomOperations); } return _operationConfig; } } private class SpecialOperationConfigParams { public SpecialOperationConfigParams(string glob, string flagPrefix, string evaluatorName, ConditionalType type) { EvaluatorName = evaluatorName; Glob = glob; FlagPrefix = flagPrefix; ConditionalStyle = type; } public string Glob { get; } public string EvaluatorName { get; } public string FlagPrefix { get; } public ConditionalType ConditionalStyle { get; } public string VariableFormat { get; set; } private static readonly SpecialOperationConfigParams _Defaults = new SpecialOperationConfigParams(string.Empty, string.Empty, "C++", ConditionalType.None); public static SpecialOperationConfigParams Defaults { get { return _Defaults; } } } // file -> replacements public IReadOnlyDictionary<string, IReadOnlyList<IOperationProvider>> LocalizationOperations { get; private set; } private IReadOnlyList<ICustomFileGlobModel> SpecialCustomSetup = new List<ICustomFileGlobModel>(); IReadOnlyList<KeyValuePair<string, IGlobalRunConfig>> IRunnableProjectConfig.SpecialOperationConfig { get { if (_specialOperationConfig == null) { List<SpecialOperationConfigParams> defaultSpecials = new List<SpecialOperationConfigParams> { new SpecialOperationConfigParams("**/*.js", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.es", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.es6", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.ts", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.json", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.jsonld", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.hjson", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.json5", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.geojson", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.topojson", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.bowerrc", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.npmrc", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.job", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.postcssrc", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.babelrc", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.csslintrc", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.eslintrc", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.jade-lintrc", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.pug-lintrc", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.jshintrc", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.stylelintrc", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.yarnrc", "//", "C++", ConditionalType.CLineComments), new SpecialOperationConfigParams("**/*.css.min", "/*", "C++", ConditionalType.CBlockComments), new SpecialOperationConfigParams("**/*.css", "/*", "C++", ConditionalType.CBlockComments), new SpecialOperationConfigParams("**/*.cshtml", "@*", "C++", ConditionalType.Razor), new SpecialOperationConfigParams("**/*.razor", "@*", "C++", ConditionalType.Razor), new SpecialOperationConfigParams("**/*.vbhtml", "@*", "VB", ConditionalType.Razor), new SpecialOperationConfigParams("**/*.cs", "//", "C++", ConditionalType.CNoComments), new SpecialOperationConfigParams("**/*.fs", "//", "C++", ConditionalType.CNoComments), new SpecialOperationConfigParams("**/*.c", "//", "C++", ConditionalType.CNoComments), new SpecialOperationConfigParams("**/*.cpp", "//", "C++", ConditionalType.CNoComments), new SpecialOperationConfigParams("**/*.cxx", "//", "C++", ConditionalType.CNoComments), new SpecialOperationConfigParams("**/*.h", "//", "C++", ConditionalType.CNoComments), new SpecialOperationConfigParams("**/*.hpp", "//", "C++", ConditionalType.CNoComments), new SpecialOperationConfigParams("**/*.hxx", "//", "C++", ConditionalType.CNoComments), new SpecialOperationConfigParams("**/*.*proj", "<!--/", "MSBUILD", ConditionalType.MSBuild), new SpecialOperationConfigParams("**/*.*proj.user", "<!--/", "MSBUILD", ConditionalType.MSBuild), new SpecialOperationConfigParams("**/*.pubxml", "<!--/", "MSBUILD", ConditionalType.MSBuild), new SpecialOperationConfigParams("**/*.pubxml.user", "<!--/", "MSBUILD", ConditionalType.MSBuild), new SpecialOperationConfigParams("**/*.msbuild", "<!--/", "MSBUILD", ConditionalType.MSBuild), new SpecialOperationConfigParams("**/*.targets", "<!--/", "MSBUILD", ConditionalType.MSBuild), new SpecialOperationConfigParams("**/*.props", "<!--/", "MSBUILD", ConditionalType.MSBuild), new SpecialOperationConfigParams("**/*.svg", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.*htm", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.*html", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.jsp", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.asp", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.aspx", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/app.config", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/web.config", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/web.*.config", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/packages.config", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.nuspec", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.xslt", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.xsd", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.vsixmanifest", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.vsct", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.storyboard", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.axml", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.plist", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.xib", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.strings", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.bat", "rem --:", "C++", ConditionalType.RemLineComment), new SpecialOperationConfigParams("**/*.cmd", "rem --:", "C++", ConditionalType.RemLineComment), new SpecialOperationConfigParams("**/nginx.conf", "#--", "C++", ConditionalType.HashSignLineComment), new SpecialOperationConfigParams("**/robots.txt", "#--", "C++", ConditionalType.HashSignLineComment), new SpecialOperationConfigParams("**/*.sh", "#--", "C++", ConditionalType.HashSignLineComment), new SpecialOperationConfigParams("**/*.haml", "-#", "C++", ConditionalType.HamlLineComment), new SpecialOperationConfigParams("**/*.jsx", "{/*", "C++", ConditionalType.JsxBlockComment), new SpecialOperationConfigParams("**/*.tsx", "{/*", "C++", ConditionalType.JsxBlockComment), new SpecialOperationConfigParams("**/*.xml", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.resx", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.bas", "'", "VB", ConditionalType.VB), new SpecialOperationConfigParams("**/*.vb", "'", "VB", ConditionalType.VB), new SpecialOperationConfigParams("**/*.xaml", "<!--", "C++", ConditionalType.Xml), new SpecialOperationConfigParams("**/*.sln", "#-", "C++", ConditionalType.HashSignLineComment) }; List<KeyValuePair<string, IGlobalRunConfig>> specialOperationConfig = new List<KeyValuePair<string, IGlobalRunConfig>>(); // put the custom configs first in the list HashSet<string> processedGlobs = new HashSet<string>(); foreach (ICustomFileGlobModel customGlobModel in SpecialCustomSetup) { if (customGlobModel.ConditionResult) { // only add the special if the condition is true SpecialOperationConfigParams defaultParams = defaultSpecials.Where(x => x.Glob == customGlobModel.Glob).FirstOrDefault(); if (defaultParams == null) { defaultParams = SpecialOperationConfigParams.Defaults; } IGlobalRunConfig runConfig = ProduceOperationSetup(defaultParams, false, customGlobModel); specialOperationConfig.Add(new KeyValuePair<string, IGlobalRunConfig>(customGlobModel.Glob, runConfig)); } // mark this special as already processed, so it doesn't get included with the defaults // even if the special was skipped due to its custom condition. processedGlobs.Add(customGlobModel.Glob); } // add the remaining default configs in the order specified above foreach (SpecialOperationConfigParams defaultParams in defaultSpecials) { if (processedGlobs.Contains(defaultParams.Glob)) { // this one was already setup due to a custom config continue; } IGlobalRunConfig runConfig = ProduceOperationSetup(defaultParams, false, null); specialOperationConfig.Add(new KeyValuePair<string, IGlobalRunConfig>(defaultParams.Glob, runConfig)); } _specialOperationConfig = specialOperationConfig; } return _specialOperationConfig; } } public IEngineEnvironmentSettings EnvironmentSettings { get; private set; } private IGlobalRunConfig ProduceOperationSetup(SpecialOperationConfigParams defaultModel, bool generateMacros, ICustomFileGlobModel customGlobModel = null) { List<IOperationProvider> operations = new List<IOperationProvider>(); // TODO: if we allow custom config to specify a built-in conditional type, decide what to do. if (defaultModel.ConditionalStyle != ConditionalType.None) { operations.AddRange(ConditionalConfig.ConditionalSetup(defaultModel.ConditionalStyle, defaultModel.EvaluatorName, true, true, null)); } if (customGlobModel == null || string.IsNullOrEmpty(customGlobModel.FlagPrefix)) { // these conditions may need to be separated - if there is custom info, but the flag prefix was not provided, we might want to raise a warning / error operations.AddRange(FlagsConfig.FlagsDefaultSetup(defaultModel.FlagPrefix)); } else { operations.AddRange(FlagsConfig.FlagsDefaultSetup(customGlobModel.FlagPrefix)); } IVariableConfig variableConfig; if (customGlobModel != null) { variableConfig = customGlobModel.VariableFormat; } else { variableConfig = VariableConfig.DefaultVariableSetup(defaultModel.VariableFormat); } List<IMacroConfig> macros = null; List<IMacroConfig> computedMacros = new List<IMacroConfig>(); List<IReplacementTokens> macroGeneratedReplacements = new List<IReplacementTokens>(); if (generateMacros) { macros = ProduceMacroConfig(computedMacros); } if (Symbols != null) { foreach (KeyValuePair<string, ISymbolModel> symbol in Symbols) { if (symbol.Value is DerivedSymbol derivedSymbol) { if (generateMacros) { macros.Add(new ProcessValueFormMacroConfig(derivedSymbol.ValueSource, symbol.Key, derivedSymbol.DataType, derivedSymbol.ValueTransform, Forms)); } } if (symbol.Value.Replaces != null) { string sourceVariable = null; if (string.Equals(symbol.Value.Type, SymbolModelConverter.BindSymbolTypeName, StringComparison.Ordinal)) { if (string.IsNullOrWhiteSpace(symbol.Value.Binding)) { EnvironmentSettings.Host.LogMessage($"Binding wasn't specified for bind-type symbol {symbol.Key}"); } else { //Since this is a bind symbol, don't replace the literal with this symbol's value, // replace it with the value of the bound symbol sourceVariable = symbol.Value.Binding; } } else { //Replace the literal value in the "replaces" property with the evaluated value of the symbol sourceVariable = symbol.Key; } if (sourceVariable != null) { if (symbol.Value is BaseValueSymbol p) { foreach (string formName in p.Forms.GlobalForms) { if (Forms.TryGetValue(formName, out IValueForm valueForm)) { string symbolName = symbol.Key + "{-VALUE-FORMS-}" + formName; string processedReplacement = valueForm.Process(Forms, p.Replaces); GenerateReplacementsForParameter(symbol, processedReplacement, symbolName, macroGeneratedReplacements); if (generateMacros) { macros.Add(new ProcessValueFormMacroConfig(symbol.Key, symbolName, "string", formName, Forms)); } } else { EnvironmentSettings.Host.LogDiagnosticMessage($"Unable to find a form called '{formName}'", "Authoring"); } } } else { GenerateReplacementsForParameter(symbol, symbol.Value.Replaces, sourceVariable, macroGeneratedReplacements); } } } } } foreach (KeyValuePair<Guid, string> map in _guidToGuidPrefixMap) { foreach (char format in GuidMacroConfig.DefaultFormats) { string newGuid = char.IsUpper(format) ? map.Key.ToString(format.ToString()).ToUpperInvariant() : map.Key.ToString(format.ToString()).ToLowerInvariant(); macroGeneratedReplacements.Add(new ReplacementTokens(map.Value + "-" + format, newGuid.TokenConfig())); } } IReadOnlyList<ICustomOperationModel> customOperationConfig; if (customGlobModel != null && customGlobModel.Operations != null) { customOperationConfig = customGlobModel.Operations; } else { customOperationConfig = new List<ICustomOperationModel>(); } foreach (IOperationProvider p in operations.ToList()) { if (!string.IsNullOrEmpty(p.Id)) { string prefix = (customGlobModel == null || string.IsNullOrEmpty(customGlobModel.FlagPrefix)) ? defaultModel.FlagPrefix : customGlobModel.FlagPrefix; string on = $"{prefix}+:{p.Id}"; string off = $"{prefix}-:{p.Id}"; string onNoEmit = $"{prefix}+:{p.Id}:noEmit"; string offNoEmit = $"{prefix}-:{p.Id}:noEmit"; operations.Add(new SetFlag(p.Id, on.TokenConfig(), off.TokenConfig(), onNoEmit.TokenConfig(), offNoEmit.TokenConfig(), null, true)); } } GlobalRunConfig config = new GlobalRunConfig() { Operations = operations, VariableSetup = variableConfig, Macros = macros, ComputedMacros = computedMacros, Replacements = macroGeneratedReplacements, CustomOperations = customOperationConfig, }; return config; } private void GenerateReplacementsForParameter(KeyValuePair<string, ISymbolModel> symbol, string replaces, string sourceVariable, List<IReplacementTokens> macroGeneratedReplacements) { TokenConfig replacementConfig = replaces.TokenConfigBuilder(); if (symbol.Value.ReplacementContexts.Count > 0) { foreach (IReplacementContext context in symbol.Value.ReplacementContexts) { TokenConfig builder = replacementConfig; if (!string.IsNullOrEmpty(context.OnlyIfAfter)) { builder = builder.OnlyIfAfter(context.OnlyIfAfter); } if (!string.IsNullOrEmpty(context.OnlyIfBefore)) { builder = builder.OnlyIfBefore(context.OnlyIfBefore); } macroGeneratedReplacements.Add(new ReplacementTokens(sourceVariable, builder)); } } else { macroGeneratedReplacements.Add(new ReplacementTokens(sourceVariable, replacementConfig)); } } private List<IMacroConfig> ProduceMacroConfig(List<IMacroConfig> computedMacroConfigs) { List<IMacroConfig> generatedMacroConfigs = new List<IMacroConfig>(); if (Guids != null) { int guidCount = 0; foreach (Guid guid in Guids) { int id = guidCount++; string replacementId = "guid" + id; generatedMacroConfigs.Add(new GuidMacroConfig(replacementId, "string", null)); _guidToGuidPrefixMap[guid] = replacementId; } } if (Symbols != null) { foreach (KeyValuePair<string, ISymbolModel> symbol in Symbols) { if (string.Equals(symbol.Value.Type, ComputedSymbol.TypeName, StringComparison.Ordinal)) { ComputedSymbol computed = (ComputedSymbol) symbol.Value; string value = computed.Value; string evaluator = computed.Evaluator; string dataType = computed.DataType; computedMacroConfigs.Add(new EvaluateMacroConfig(symbol.Key, dataType, value, evaluator)); } else if (string.Equals(symbol.Value.Type, GeneratedSymbol.TypeName, StringComparison.Ordinal)) { GeneratedSymbol symbolInfo = (GeneratedSymbol)symbol.Value; string type = symbolInfo.Generator; string variableName = symbol.Key; Dictionary<string, JToken> configParams = new Dictionary<string, JToken>(); foreach (KeyValuePair<string, JToken> parameter in symbolInfo.Parameters) { configParams.Add(parameter.Key, parameter.Value); } string dataType = symbolInfo.DataType; if (string.Equals(dataType, "choice", StringComparison.OrdinalIgnoreCase)) { dataType = "string"; } generatedMacroConfigs.Add(new GeneratedSymbolDeferredMacroConfig(type, dataType, variableName, configParams)); } } } return generatedMacroConfigs; } // If the token is a string: // check if its a valid file in the same directory as the sourceFile. // If so, read that files content as the exclude list. // Otherwise returns an array containing the string value as its only entry. // Otherwise, interpret the token as an array and return the content. private static IReadOnlyList<string> JTokenAsFilenameToReadOrArrayToCollection(JToken token, IFile sourceFile, string[] defaultSet) { if (token == null) { return defaultSet; } if (token.Type == JTokenType.String) { string tokenValue = token.ToString(); if ((tokenValue.IndexOfAny(Path.GetInvalidPathChars()) != -1) || !sourceFile.Parent.FileInfo(tokenValue).Exists) { return new List<string>(new[] { tokenValue }); } else { using (Stream excludeList = sourceFile.Parent.FileInfo(token.ToString()).OpenRead()) using (TextReader reader = new StreamReader(excludeList, Encoding.UTF8, true, 4096, true)) { return reader.ReadToEnd().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); } } } return token.ArrayAsStrings(); } private static IReadOnlyList<string> JTokenStringOrArrayToCollection(JToken token, string[] defaultSet) { if (token == null) { return defaultSet; } if (token.Type == JTokenType.String) { string tokenValue = token.ToString(); return new List<string>() { tokenValue }; } return token.ArrayAsStrings(); } public void Evaluate(IParameterSet parameters, IVariableCollection rootVariableCollection, IFileSystemInfo configFile) { bool stable = Symbols == null; Dictionary<string, bool> computed = new Dictionary<string, bool>(); while (!stable) { stable = true; foreach (KeyValuePair<string, ISymbolModel> symbol in Symbols) { if (string.Equals(symbol.Value.Type, ComputedSymbol.TypeName, StringComparison.Ordinal)) { ComputedSymbol sym = (ComputedSymbol)symbol.Value; bool value = Cpp2StyleEvaluatorDefinition.EvaluateFromString(EnvironmentSettings, sym.Value, rootVariableCollection); stable &= computed.TryGetValue(symbol.Key, out bool currentValue) && currentValue == value; rootVariableCollection[symbol.Key] = value; computed[symbol.Key] = value; } else if (string.Equals(symbol.Value.Type, SymbolModelConverter.BindSymbolTypeName, StringComparison.Ordinal)) { if (parameters.TryGetRuntimeValue(EnvironmentSettings, symbol.Value.Binding, out object bindValue) && bindValue != null) { rootVariableCollection[symbol.Key] = RunnableProjectGenerator.InferTypeAndConvertLiteral(bindValue.ToString()); } } } } // evaluate the file glob (specials) conditions // the result is needed for SpecialOperationConfig foreach (ICustomFileGlobModel fileGlobModel in SpecialCustomSetup) { fileGlobModel.EvaluateCondition(EnvironmentSettings, rootVariableCollection); } parameters.ResolvedValues.TryGetValue(NameParameter, out object resolvedNameParamValue); _sources = EvaluateSources(parameters, rootVariableCollection, configFile, resolvedNameParamValue); // evaluate the conditions and resolve the paths for the PrimaryOutputs foreach (ICreationPathModel pathModel in PrimaryOutputs) { pathModel.EvaluateCondition(EnvironmentSettings, rootVariableCollection); if (pathModel.ConditionResult) { foreach (FileSourceMatchInfo sourceInfo in _sources) { if (sourceInfo.Renames.TryGetValue(pathModel.PathOriginal, out string targetPath)) { pathModel.PathResolved = targetPath; } //Don't overwrite an already resolved output value else if (string.IsNullOrEmpty(pathModel.PathResolved)) { pathModel.PathResolved = pathModel.PathOriginal; } } } } } private List<FileSourceMatchInfo> EvaluateSources(IParameterSet parameters, IVariableCollection rootVariableCollection, IFileSystemInfo configFile, object resolvedNameParamValue) { List<FileSourceMatchInfo> sources = new List<FileSourceMatchInfo>(); foreach (ExtendedFileSource source in Sources) { if (!string.IsNullOrEmpty(source.Condition) && !Cpp2StyleEvaluatorDefinition.EvaluateFromString(EnvironmentSettings, source.Condition, rootVariableCollection)) { continue; } IReadOnlyList<string> topIncludePattern = JTokenAsFilenameToReadOrArrayToCollection(source.Include, SourceFile, IncludePatternDefaults).ToList(); IReadOnlyList<string> topExcludePattern = JTokenAsFilenameToReadOrArrayToCollection(source.Exclude, SourceFile, ExcludePatternDefaults).ToList(); IReadOnlyList<string> topCopyOnlyPattern = JTokenAsFilenameToReadOrArrayToCollection(source.CopyOnly, SourceFile, CopyOnlyPatternDefaults).ToList(); FileSourceEvaluable topLevelPatterns = new FileSourceEvaluable(topIncludePattern, topExcludePattern, topCopyOnlyPattern); Dictionary<string, string> fileRenamesFromSource = new Dictionary<string, string>(source.Rename ?? RenameDefaults, StringComparer.Ordinal); List<FileSourceEvaluable> modifierList = new List<FileSourceEvaluable>(); if (source.Modifiers != null) { foreach (SourceModifier modifier in source.Modifiers) { if (string.IsNullOrEmpty(modifier.Condition) || Cpp2StyleEvaluatorDefinition.EvaluateFromString(EnvironmentSettings, modifier.Condition, rootVariableCollection)) { IReadOnlyList<string> modifierIncludes = JTokenAsFilenameToReadOrArrayToCollection(modifier.Include, SourceFile, new string[0]); IReadOnlyList<string> modifierExcludes = JTokenAsFilenameToReadOrArrayToCollection(modifier.Exclude, SourceFile, new string[0]); IReadOnlyList<string> modifierCopyOnly = JTokenAsFilenameToReadOrArrayToCollection(modifier.CopyOnly, SourceFile, new string[0]); FileSourceEvaluable modifierPatterns = new FileSourceEvaluable(modifierIncludes, modifierExcludes, modifierCopyOnly); modifierList.Add(modifierPatterns); if (modifier.Rename != null) { foreach (JProperty property in modifier.Rename.Properties()) { fileRenamesFromSource[property.Name] = property.Value.Value<string>(); } } } } } string sourceDirectory = source.Source ?? "./"; string targetDirectory = source.Target ?? "./"; IReadOnlyDictionary<string, string> allRenamesForSource = AugmentRenames(configFile, sourceDirectory, ref targetDirectory, resolvedNameParamValue, parameters, fileRenamesFromSource); FileSourceMatchInfo sourceMatcher = new FileSourceMatchInfo( sourceDirectory, targetDirectory, topLevelPatterns, allRenamesForSource, modifierList); sources.Add(sourceMatcher); } if (Sources.Count == 0) { IReadOnlyList<string> includePattern = IncludePatternDefaults; IReadOnlyList<string> excludePattern = ExcludePatternDefaults; IReadOnlyList<string> copyOnlyPattern = CopyOnlyPatternDefaults; FileSourceEvaluable topLevelPatterns = new FileSourceEvaluable(includePattern, excludePattern, copyOnlyPattern); string targetDirectory = string.Empty; Dictionary<string, string> fileRenamesFromSource = new Dictionary<string, string>(StringComparer.Ordinal); IReadOnlyDictionary<string, string> allRenamesForSource = AugmentRenames(configFile, "./", ref targetDirectory, resolvedNameParamValue, parameters, fileRenamesFromSource); FileSourceMatchInfo sourceMatcher = new FileSourceMatchInfo( "./", "./", topLevelPatterns, allRenamesForSource, new List<FileSourceEvaluable>()); sources.Add(sourceMatcher); } return sources; } private IReadOnlyDictionary<string, string> AugmentRenames(IFileSystemInfo configFile, string sourceDirectory, ref string targetDirectory, object resolvedNameParamValue, IParameterSet parameters, Dictionary<string, string> fileRenames) { return FileRenameGenerator.AugmentFileRenames(EnvironmentSettings, SourceName, configFile, sourceDirectory, ref targetDirectory, resolvedNameParamValue, parameters, fileRenames); } private static ISymbolModel SetupDefaultNameSymbol(string sourceName) { StringBuilder nameSymbolConfigBuilder = new StringBuilder(512); nameSymbolConfigBuilder.AppendLine(@" { ""binding"": """ + NameSymbolName + @""", ""type"": """ + ParameterSymbol.TypeName + @""", ""description"": ""The default name symbol"", ""datatype"": ""string"", ""forms"": { ""global"": [ """ + IdentityValueForm.FormName + @""", """ + DefaultSafeNameValueFormModel.FormName + @""", """ + DefaultLowerSafeNameValueFormModel.FormName + @""", """ + DefaultSafeNamespaceValueFormModel.FormName + @""", """ + DefaultLowerSafeNamespaceValueFormModel.FormName + @"""] } "); if (!string.IsNullOrEmpty(sourceName)) { nameSymbolConfigBuilder.AppendLine(","); nameSymbolConfigBuilder.AppendLine($"\"replaces\": \"{sourceName}\""); } nameSymbolConfigBuilder.AppendLine("}"); JObject config = JObject.Parse(nameSymbolConfigBuilder.ToString()); return ParameterSymbol.FromJObject(config, null, null); } private static IReadOnlyDictionary<string, IValueForm> SetupValueFormMapForTemplate(JObject source) { Dictionary<string, IValueForm> formMap = new Dictionary<string, IValueForm>(StringComparer.Ordinal); // setup all the built-in default forms. foreach (KeyValuePair<string, IValueForm> builtInForm in ValueFormRegistry.AllForms) { formMap[builtInForm.Key] = builtInForm.Value; } // setup the forms defined by the template configuration. // if any have the same name as a default, the default is overridden. IReadOnlyDictionary<string, JToken> templateDefinedforms = source.ToJTokenDictionary(StringComparer.OrdinalIgnoreCase, nameof(Forms)); foreach (KeyValuePair<string, JToken> form in templateDefinedforms) { if (form.Value is JObject o) { formMap[form.Key] = ValueFormRegistry.GetForm(form.Key, o); } } return formMap; } public static SimpleConfigModel FromJObject(IEngineEnvironmentSettings environmentSettings, JObject source, ISimpleConfigModifiers configModifiers = null, JObject localeSource = null) { ILocalizationModel localizationModel = LocalizationFromJObject(localeSource); SimpleConfigModel config = new SimpleConfigModel() { Author = localizationModel?.Author ?? source.ToString(nameof(config.Author)), Classifications = source.ArrayAsStrings(nameof(config.Classifications)), DefaultName = source.ToString(nameof(DefaultName)), Description = localizationModel?.Description ?? source.ToString(nameof(Description)) ?? string.Empty, GroupIdentity = source.ToString(nameof(GroupIdentity)), Precedence = source.ToInt32(nameof(Precedence)), Guids = source.ArrayAsGuids(nameof(config.Guids)), Identity = source.ToString(nameof(config.Identity)), Name = localizationModel?.Name ?? source.ToString(nameof(config.Name)), SourceName = source.ToString(nameof(config.SourceName)), PlaceholderFilename = source.ToString(nameof(config.PlaceholderFilename)), EnvironmentSettings = environmentSettings, GeneratorVersions = source.ToString(nameof(config.GeneratorVersions)) }; JToken shortNameToken = source.Get<JToken>("ShortName"); config.ShortNameList = JTokenStringOrArrayToCollection(shortNameToken, new string[0]); config.Forms = SetupValueFormMapForTemplate(source); List <ExtendedFileSource> sources = new List<ExtendedFileSource>(); config.Sources = sources; foreach (JObject item in source.Items<JObject>(nameof(config.Sources))) { ExtendedFileSource src = new ExtendedFileSource(); sources.Add(src); src.CopyOnly = item.Get<JToken>(nameof(src.CopyOnly)); src.Exclude = item.Get<JToken>(nameof(src.Exclude)); src.Include = item.Get<JToken>(nameof(src.Include)); src.Condition = item.ToString(nameof(src.Condition)); src.Rename = item.Get<JObject>(nameof(src.Rename)).ToStringDictionary().ToDictionary(x => x.Key, x => x.Value); List<SourceModifier> modifiers = new List<SourceModifier>(); src.Modifiers = modifiers; foreach (JObject entry in item.Items<JObject>(nameof(src.Modifiers))) { SourceModifier modifier = new SourceModifier { Condition = entry.ToString(nameof(modifier.Condition)), CopyOnly = entry.Get<JToken>(nameof(modifier.CopyOnly)), Exclude = entry.Get<JToken>(nameof(modifier.Exclude)), Include = entry.Get<JToken>(nameof(modifier.Include)), Rename = entry.Get<JObject>(nameof(modifier.Rename)) }; modifiers.Add(modifier); } src.Source = item.ToString(nameof(src.Source)); src.Target = item.ToString(nameof(src.Target)); } IBaselineInfo baseline = null; config.BaselineInfo = BaselineInfoFromJObject(source.PropertiesOf("baselines")); if (configModifiers != null && !string.IsNullOrEmpty(configModifiers.BaselineName)) { config.BaselineInfo.TryGetValue(configModifiers.BaselineName, out baseline); } Dictionary<string, ISymbolModel> symbols = new Dictionary<string, ISymbolModel>(StringComparer.Ordinal); // create a name symbol. If one is explicitly defined in the template, it'll override this. symbols.Add(NameSymbolName, SetupDefaultNameSymbol(config.SourceName)); // tags are being deprecated from template configuration, but we still read them for backwards compatibility. // They're turned into symbols here, which eventually become tags. config._tagsDeprecated = source.ToStringDictionary(StringComparer.OrdinalIgnoreCase, nameof(config.Tags)); IReadOnlyDictionary<string, ISymbolModel> symbolsFromTags = ConvertDeprecatedTagsToParameterSymbols(config._tagsDeprecated); foreach (KeyValuePair<string, ISymbolModel> tagSymbol in symbolsFromTags) { if (!symbols.ContainsKey(tagSymbol.Key)) { symbols.Add(tagSymbol.Key, tagSymbol.Value); } } config.Symbols = symbols; foreach (JProperty prop in source.PropertiesOf(nameof(config.Symbols))) { JObject obj = prop.Value as JObject; if (obj == null) { continue; } IParameterSymbolLocalizationModel symbolLocalization = null; if (localizationModel != null) { localizationModel.ParameterSymbols.TryGetValue(prop.Name, out symbolLocalization); } string defaultOverride = null; if (baseline != null && baseline.DefaultOverrides != null) { baseline.DefaultOverrides.TryGetValue(prop.Name, out defaultOverride); } ISymbolModel modelForSymbol = SymbolModelConverter.GetModelForObject(obj, symbolLocalization, defaultOverride); if (modelForSymbol != null) { // The symbols dictionary comparer is Ordinal, making symbol names case-sensitive. if (string.Equals(prop.Name, NameSymbolName, StringComparison.Ordinal) && symbols.TryGetValue(prop.Name, out ISymbolModel existingSymbol)) { // "name" symbol is explicitly defined above. If it's also defined in the template.json, it gets special handling here. symbols[prop.Name] = ParameterSymbol.ExplicitNameSymbolMergeWithDefaults(modelForSymbol, existingSymbol); } else { // last in wins (in the odd case where a template.json defined a symbol multiple times) symbols[prop.Name] = modelForSymbol; } } } config.PostActionModel = RunnableProjects.PostActionModel.ListFromJArray(source.Get<JArray>("PostActions"), localizationModel?.PostActions); config.HasScriptRunningPostActions = config.PostActionModel.Any(x => x.ActionId == PostActionInfo.ProcessStartPostActionProcessorId); config.PrimaryOutputs = CreationPathModel.ListFromJArray(source.Get<JArray>(nameof(PrimaryOutputs))); // Custom operations at the global level JToken globalCustomConfigData = source[nameof(config.CustomOperations)]; if (globalCustomConfigData != null) { config.CustomOperations = CustomFileGlobModel.FromJObject((JObject)globalCustomConfigData, string.Empty); } else { config.CustomOperations = null; } // Custom operations for specials IReadOnlyDictionary<string, JToken> allSpecialOpsConfig = source.ToJTokenDictionary(StringComparer.OrdinalIgnoreCase, "SpecialCustomOperations"); List<ICustomFileGlobModel> specialCustomSetup = new List<ICustomFileGlobModel>(); foreach (KeyValuePair<string, JToken> globConfigKeyValue in allSpecialOpsConfig) { string globName = globConfigKeyValue.Key; JToken globData = globConfigKeyValue.Value; CustomFileGlobModel globModel = CustomFileGlobModel.FromJObject((JObject)globData, globName); specialCustomSetup.Add(globModel); } config.SpecialCustomSetup = specialCustomSetup; // localization operations for individual files Dictionary<string, IReadOnlyList<IOperationProvider>> localizations = new Dictionary<string, IReadOnlyList<IOperationProvider>>(); if (localizationModel != null && localizationModel.FileLocalizations != null) { foreach (FileLocalizationModel fileLocalization in localizationModel.FileLocalizations) { List<IOperationProvider> localizationsForFile = new List<IOperationProvider>(); foreach (KeyValuePair<string, string> localizationInfo in fileLocalization.Localizations) { localizationsForFile.Add(new Replacement(localizationInfo.Key.TokenConfig(), localizationInfo.Value, null, true)); } localizations.Add(fileLocalization.File, localizationsForFile); } } config.LocalizationOperations = localizations; return config; } private static IReadOnlyDictionary<string, IBaselineInfo> BaselineInfoFromJObject(IEnumerable<JProperty> baselineJProperties) { Dictionary<string, IBaselineInfo> allBaselines = new Dictionary<string, IBaselineInfo>(); foreach (JProperty property in baselineJProperties) { JObject obj = property.Value as JObject; if (obj == null) { continue; } BaselineInfo baseline = new BaselineInfo { Description = obj.ToString(nameof(baseline.Description)), DefaultOverrides = obj.Get<JObject>(nameof(baseline.DefaultOverrides)).ToStringDictionary() }; allBaselines[property.Name] = baseline; } return allBaselines; } private static IReadOnlyDictionary<string, ISymbolModel> ConvertDeprecatedTagsToParameterSymbols(IReadOnlyDictionary<string, string> tagsDeprecated) { Dictionary<string, ISymbolModel> symbols = new Dictionary<string, ISymbolModel>(); foreach (KeyValuePair<string, string> tagInfo in tagsDeprecated) { symbols[tagInfo.Key] = ParameterSymbol.FromDeprecatedConfigTag(tagInfo.Value); } return symbols; } public static ILocalizationModel LocalizationFromJObject(JObject source) { if (source == null) { return null; } LocalizationModel locModel = new LocalizationModel() { Author = source.ToString(nameof(locModel.Author)), Name = source.ToString(nameof(locModel.Name)), Description = source.ToString(nameof(locModel.Description)), Identity = source.ToString(nameof(locModel.Identity)), }; // symbol description & choice localizations Dictionary<string, IParameterSymbolLocalizationModel> parameterLocalizations = new Dictionary<string, IParameterSymbolLocalizationModel>(); IReadOnlyDictionary<string, JToken> symbolInfoList = source.ToJTokenDictionary(StringComparer.OrdinalIgnoreCase, "symbols"); foreach (KeyValuePair<string, JToken> symbolDetail in symbolInfoList) { string symbol = symbolDetail.Key; string description = symbolDetail.Value.ToString("description"); Dictionary<string, string> choicesAndDescriptionsForSymbol = new Dictionary<string, string>(); foreach (JObject choiceObject in symbolDetail.Value.Items<JObject>("choices")) { string choice = choiceObject.ToString("choice"); string choiceDescription = choiceObject.ToString("description"); if (!string.IsNullOrEmpty(choice) && !string.IsNullOrEmpty(choiceDescription)) { choicesAndDescriptionsForSymbol.Add(choice, choiceDescription); } } IParameterSymbolLocalizationModel symbolLocalization = new ParameterSymbolLocalizationModel(symbol, description, choicesAndDescriptionsForSymbol); parameterLocalizations.Add(symbol, symbolLocalization); } locModel.ParameterSymbols = parameterLocalizations; // post action localizations Dictionary<Guid, IPostActionLocalizationModel> postActions = new Dictionary<Guid, IPostActionLocalizationModel>(); foreach (JObject item in source.Items<JObject>(nameof(locModel.PostActions))) { IPostActionLocalizationModel postActionModel = PostActionLocalizationModel.FromJObject(item); postActions.Add(postActionModel.ActionId, postActionModel); } locModel.PostActions = postActions; // regular file localizations IReadOnlyDictionary<string, JToken> fileLocalizationJson = source.ToJTokenDictionary(StringComparer.OrdinalIgnoreCase, "localizations"); List<FileLocalizationModel> fileLocalizations = new List<FileLocalizationModel>(); if (fileLocalizationJson != null) { foreach (KeyValuePair<string, JToken> fileLocInfo in fileLocalizationJson) { string fileName = fileLocInfo.Key; JToken localizationJson = fileLocInfo.Value; FileLocalizationModel fileModel = FileLocalizationModel.FromJObject(fileName, (JObject)localizationJson); fileLocalizations.Add(fileModel); } } locModel.FileLocalizations = fileLocalizations; return locModel; } } }
using System; using System.Collections.Generic; using System.Text; using System.IO.Ports; using System.Threading; using System.Diagnostics; using System.Net.Sockets; using System.Net; using Project858.Diagnostics; using Project858.ComponentModel.Client; using System.ComponentModel; namespace Project858.Net { /// <summary> /// Zakladna komunikacna vrstva, pracujuca na linkovej urovni TCP /// </summary> public class TcpTransportClient : ClientBase, ITransportClient { #region - Constructors - /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentNullException"> /// Neinicializovana IPAddress /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Chybny argument / rozsah IP portu /// </exception> /// <param name="ipEndPoint">IpPoint ku ktoremu sa chceme pripojit</param> public TcpTransportClient(IPEndPoint ipEndPoint) : this(new IpEndPointCollection(ipEndPoint), 1000, 1000, 1000, 300) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentNullException"> /// Neinicializovana IPAddress /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Chybny argument / rozsah IP portu /// </exception> /// <param name="ipEndPoints">Kolekcia IpEndPointov ku ktory sa bude klient striedavo pripajat pri autoreconnecte</param> public TcpTransportClient(IpEndPointCollection ipEndPoints) : this(ipEndPoints, 1000, 1000, 1000, 300) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentNullException"> /// Neinicializovana IPAddress /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Chybny argument jedneho z timeoutov, alebo IP portu /// </exception> /// <param name="ipEndPoint">IpPoint ku ktoremu sa chceme pripojit</param> /// <param name="tcpReadTimeout">TcpClient Read Timeout</param> /// <param name="tcpWriteTimeout">TcpClient Write Timeout</param> /// <param name="nsReadTimeout">NetworkStream Read Timeout</param> /// <param name="nsWriteTimeout">NetworkStream Write Timeout</param> public TcpTransportClient(IPEndPoint ipEndPoint, Int32 tcpReadTimeout, Int32 tcpWriteTimeout, Int32 nsReadTimeout, Int32 nsWriteTimeout) : this(new IpEndPointCollection(ipEndPoint), tcpReadTimeout, tcpWriteTimeout, nsReadTimeout, nsWriteTimeout) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentNullException"> /// Neinicializovana IPAddress /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Chybny argument jedneho z timeoutov, alebo IP portu /// </exception> /// <param name="ipEndPoints">Kolekcia IpEndPointov ku ktory sa bude klient striedavo pripajat pri autoreconnecte</param> /// <param name="tcpReadTimeout">TcpClient Read Timeout</param> /// <param name="tcpWriteTimeout">TcpClient Write Timeout</param> /// <param name="nsReadTimeout">NetworkStream Read Timeout</param> /// <param name="nsWriteTimeout">NetworkStream Write Timeout</param> public TcpTransportClient(IpEndPointCollection ipEndPoints, Int32 tcpReadTimeout, Int32 tcpWriteTimeout, Int32 nsReadTimeout, Int32 nsWriteTimeout) { //osetrime vstup if (ipEndPoints == null) throw new ArgumentNullException("ipEndPoints"); if (ipEndPoints.Count == 0) throw new ArgumentException("ipEndPoints.Count can not be 0 !"); if (tcpReadTimeout < -1) throw new ArgumentOutOfRangeException("tcpReadTimeout must be >= -1"); if (tcpWriteTimeout < -1) throw new ArgumentOutOfRangeException("tcpWriteTimeout must be >= -1"); if (nsReadTimeout < -1) throw new ArgumentOutOfRangeException("nsReadTimeout must be >= -1"); if (nsWriteTimeout < -1) throw new ArgumentOutOfRangeException("nsWriteTimeout must be >= -1"); //nastavime timeoty this.m_tcpReadTimeout = tcpReadTimeout; this.m_tcpWriteTimeout = tcpWriteTimeout; this.m_nsReadTimeout = nsReadTimeout; this.m_nsWriteTimeout = nsWriteTimeout; this.m_ipEndPoints = ipEndPoints; this.m_tcpClient = null; this.m_canAutoReconnect = true; } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentNullException"> /// Neinicializovany TcpClient /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Chybny argument jedneho z timeoutov /// </exception> /// <exception cref="ObjectDisposedException"> /// Ak je RemoteEndPoint v tcpClientovi Disposed /// </exception> /// <param name="tcpClient">Client zabezpecujuci tcp komunikaciu</param> public TcpTransportClient(TcpClient tcpClient) : this(tcpClient, 1000, 1000, 1000, 300) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentNullException"> /// Neinicializovany TcpClient /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Chybny argument jedneho z timeoutov /// </exception> /// <exception cref="ObjectDisposedException"> /// Ak je RemoteEndPoint v tcpClientovi Disposed /// </exception> /// <param name="tcpClient">Client zabezpecujuci tcp komunikaciu</param> /// <param name="tcpReadTimeout">TcpClient Read Timeout</param> /// <param name="tcpWriteTimeout">TcpClient Write Timeout</param> /// <param name="nsReadTimeout">NetworkStream Read Timeout</param> /// <param name="nsWriteTimeout">NetworkStream Write Timeout</param> public TcpTransportClient(TcpClient tcpClient, Int32 tcpReadTimeout, Int32 tcpWriteTimeout, Int32 nsReadTimeout, Int32 nsWriteTimeout) { if (tcpClient == null) throw new ArgumentNullException("tcpClient", "Value cannot be null."); if (tcpReadTimeout < -1) throw new ArgumentOutOfRangeException("tcpReadTimeout must be >= -1"); if (tcpWriteTimeout < -1) throw new ArgumentOutOfRangeException("tcpWriteTimeout must be >= -1"); if (nsReadTimeout < -1) throw new ArgumentOutOfRangeException("nsReadTimeout must be >= -1"); if (nsWriteTimeout < -1) throw new ArgumentOutOfRangeException("nsWriteTimeout must be >= -1"); //nastavime timeoty this.m_tcpReadTimeout = tcpReadTimeout; this.m_tcpWriteTimeout = tcpWriteTimeout; this.m_nsReadTimeout = nsReadTimeout; this.m_nsWriteTimeout = nsWriteTimeout; this.m_tcpClient = tcpClient; this.m_ipEndPoints = null; this.m_canAutoReconnect = false; } #endregion #region - State Class - /// <summary> /// pomocna trieda na event na streame /// </summary> private class SocketState { #region - Constructor - /// <summary> /// Initialize this class /// </summary> public SocketState() { this._data = new byte[65536]; } #endregion #region - Properties - /// <summary> /// Klient cez ktoreho prebieha komunikacia /// </summary> public TcpClient Client { get; set; } /// <summary> /// Buffer na citanie _data /// </summary> public Byte[] Data { get { return _data; } set { _data = value; } } /// <summary> /// Stream cez ktory sa komunikuje /// </summary> public NetworkStream Stream { get { return _stream; } set { _stream = value; } } #endregion #region - Variable - /// <summary> /// Buffer na citanie _data /// </summary> private Byte[] _data = null; /// <summary> /// Stream cez ktory sa komunikuje /// </summary> private NetworkStream _stream = null; #endregion } #endregion #region - Event - /// <summary> /// Event na oznamenie spustenia spojenia pre vyssu vrstvu /// </summary> private event EventHandler _connectedEvent = null; /// <summary> /// Event na oznamenie spustenia spojenia pre vyssu vrstvu /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> public event EventHandler ConnectedEvent { add { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); lock (this.m_eventLock) this._connectedEvent += value; } remove { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); lock (this.m_eventLock) this._connectedEvent -= value; } } /// <summary> /// Event na oznamenie ukoncenia spojenia pre vyssu vrstvu /// </summary> private event EventHandler disconnectedEvent = null; /// <summary> /// Event na oznamenie ukoncenia spojenia pre vyssu vrstvu /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> public event EventHandler DisconnectedEvent { add { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); lock (this.m_eventLock) this.disconnectedEvent += value; } remove { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); lock (this.m_eventLock) this.disconnectedEvent -= value; } } /// <summary> /// Event na oznamenue prichodu dat na transportnej vrstve /// </summary> private event DataEventHandler m_receivedDataEvent = null; /// <summary> /// Event na oznamenue prichodu dat na transportnej vrstve /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> public event DataEventHandler ReceivedDataEvent { add { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); lock (this.m_eventLock) this.m_receivedDataEvent += value; } remove { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); //netusim preco ale to mi zvykne zamrznut thread a ja fakt neviem preco lock (this.m_eventLock) this.m_receivedDataEvent -= value; } } /// <summary> /// Event oznamujuci zmenu stavu pripojenia /// </summary> private event EventHandler _changeConnectionStateEvent = null; /// <summary> /// Event oznamujuci zmenu stavu pripojenia /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> /// <exception cref="InvalidOperationException"> /// Ak nie je autoreconnect povoleny /// </exception> public event EventHandler ChangeConnectionStateEvent { add { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); //ak je povolena moznost reconnectu if (!this.m_canAutoReconnect) throw new InvalidOperationException(); lock (this.m_eventLock) this._changeConnectionStateEvent += value; } remove { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); //ak je povolena moznost reconnectu if (!this.m_canAutoReconnect) throw new InvalidOperationException(); lock (this.m_eventLock) this._changeConnectionStateEvent -= value; } } #endregion #region - Properties - /// <summary> /// (Get / Set) Definuje ci je zapnute automaticke pripajanie klienta /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave isDisposed /// </exception> /// <exception cref="InvalidOperationException"> /// Ak nie je autoreconnect povoleny /// </exception> public Boolean AutoReconnect { get { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); return (this.m_canAutoReconnect) ? m_autoReconnect : false; } set { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); //ak je povolena moznost reconnectu if (!this.m_canAutoReconnect) throw new InvalidOperationException(); m_autoReconnect = (this.m_canAutoReconnect) ? value : false; } } /// <summary> /// (Get / Set) Stav v akom sa nachadza komunikacia / komunikacny kanal /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> public ConnectionStates ConnectionState { get { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); return m_connectionState; } } /// <summary> /// (Get / Set) Timeout v akom sa pravidelne vykonava pokus o pripojenie. Minute = 2000, Max = 60000. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> /// Nepovoleny rozsah timeotu /// </exception> /// <exception cref="InvalidOperationException"> /// Ak nie je autoreconnect povoleny /// </exception> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> public Int32 ReconnectTimeout { get { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); return this.m_autoReconnectTimeout; } set { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); //ak je povolena moznost reconnectu if (!this.m_canAutoReconnect) throw new InvalidOperationException(); //overime rozsah timeoutu if (value < 2000 || value > 60000) throw new ArgumentOutOfRangeException("value"); m_autoReconnectTimeout = value; } } /// <summary> /// Kolekcia IPEndPointov ku ktorym sa klient pri reconnecte pripaja /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> public IpEndPointCollection IpEndPoints { get { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); return this.m_ipEndPoints; } } /// <summary> /// (Get) Detekcia pripojenia /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> public Boolean IsConnected { get { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); return this.m_isConnectied; } } /// <summary> /// Definuje ci je mozne vyuzit auto recconect spojenia /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> public Boolean CanAutoReconnect { get { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); return m_canAutoReconnect; } protected set { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); m_canAutoReconnect = value; } } /// <summary> /// Aktualny ip end point na ktory sa pripajame alebo na ktorom sme pripojeny /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> public IPEndPoint LastIpEndPoint { get { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); return m_lastIpEndPoint; } set { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); m_lastIpEndPoint = value; } } #endregion #region - Variable - /// <summary> /// Index posledneho IpEndPointu na ktory sa pokusilo pripojit /// </summary> private int m_lastIpEndPointIndex = 0; /// <summary> /// Definuje ci je mozne vyuzit auto recconect spojenia /// </summary> private Boolean m_canAutoReconnect = false; /// <summary> /// Stream na komunikaciu /// </summary> private NetworkStream m_networkStream = null; /// <summary> /// TcpClient Read Timeout /// </summary> private Int32 m_tcpReadTimeout = 0; /// <summary> /// TcpClient Write Timeout /// </summary> private Int32 m_tcpWriteTimeout = 0; /// <summary> /// NetworkStream Read Timeout /// </summary> private Int32 m_nsReadTimeout = 0; /// <summary> /// NetworkStream Write Timeout /// </summary> private Int32 m_nsWriteTimeout = 0; /// <summary> /// detekcia pripojenia /// </summary> private volatile Boolean m_isConnectied = false; /// <summary> /// Client na pripojenie cez TCP/IP /// </summary> private TcpClient m_tcpClient; /// <summary> /// pristupovy bod cez ktory sme pripojeny /// </summary> private IpEndPointCollection m_ipEndPoints = null; /// <summary> /// Pomocny timer na vykonavanie automatikeho reconnectu v pripade padu spojenia /// </summary> private Timer m_autoReconnectTimer = null; /// <summary> /// Timeout v akom sa pravidelne vykonava pokus o pripojenie /// </summary> private Int32 m_autoReconnectTimeout = 5000; /// <summary> /// Definuje ci je zapnute automaticke pripajanie klienta /// </summary> private Boolean m_autoReconnect = false; /// <summary> /// Stav v akom sa nachadza komunikacia / komunikacny kanal /// </summary> private ConnectionStates m_connectionState = ConnectionStates.Closed; /// <summary> /// Aktualny ip end point na ktory sa pripajame alebo na ktorom sme pripojeny /// </summary> private IPEndPoint m_lastIpEndPoint = null; #endregion #region - Public Method - /// <summary> /// Vrati meno, popis klienta /// </summary> /// <returns>Popis klienta</returns> public override string ToString() { if (this.m_lastIpEndPoint == null) { return base.ToString(); } return String.Format("{0}_[{1}]", base.ToString(), this.LastIpEndPoint.ToString().Replace(":", "_")); } /// <summary> /// This function reads data from stream /// </summary> /// <param name="buffer">Buffer to insert data</param> /// <param name="size">Max size for buffer</param> /// <param name="result">Result, data count from stream</param> /// <returns>True | false</returns> public Boolean Read(Byte[] buffer, int size, out int result) { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); //otvorenie nie je mozne ak je connection == true if (!this.IsConnected) throw new InvalidOperationException("Writing data is not possible! The client is not connected!"); //reset value result = 0x00; try { //zapiseme data result = this.m_networkStream.Read(buffer, 0x00, size); //successfully return true; } catch (Exception ex) { //zalogujeme this.InternalException(ex, "Error during reading data to socket. {0}", ex.Message); //ukoncime klienta this.InternalDisconnect(false); //chybne ukoncenie metody return false; } } /// <summary> /// Zapise _data na komunikacnu linku /// </summary> /// <exception cref="InvalidOperationException"> /// Vynimka v pripade ze sa snazime zapisat _data, ale spojenie nie je. /// </exception> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> /// <returns>True = _data boli uspesne zapisane, False = chyba pri zapise dat</returns> public Boolean Write(Byte[] data) { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); //otvorenie nie je mozne ak je connection == true if (!this.IsConnected) throw new InvalidOperationException("Writing data is not possible! The client is not connected!"); try { //zalogujeme prijate dat this.InternalTrace(TraceTypes.Verbose, "Sending data: [{0}]", data.ToHexaString()); //zapiseme data this.m_networkStream.Write(data, 0, data.Length); this.m_networkStream.Flush(); //zalogujeme prijate dat this.InternalTrace(TraceTypes.Verbose, "Sending the data has been successfully"); //uspesne ukoncenie metody return true; } catch (Exception ex) { //zalogujeme this.InternalException(ex, "Error during sending data to socket. {0}", ex.Message); //ukoncime klienta this.InternalDisconnect(false); //chybne ukoncenie metody return false; } } #endregion #region - Protected and Private Method - /// <summary> /// Podla inicializacie otvori TCP spojenie na pripojeneho clienta /// </summary> /// <returns>True = uspesne otvorene spojenie, False = chyba pri otvarani spojenia</returns> protected override bool InternalStart() { //zmenime stav this.m_connectionState = ConnectionStates.Connecting; //doslo k zmene stavu this.OnChangeConnectionState(EventArgs.Empty); //pokusime sa vytvorit spojenie if (!this.InternalConnect(!this.AutoReconnect)) { if (this.IsRun) { //spustime automaticky reconnec this.StartReconnect(); } else { //start nebol uspesny return false; } } //spojenie bolo uspesne vytvorene return true; } /// <summary> /// Zatvori spojenie /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> /// <returns>True = uspesne zatvorene spojenie, False = chyba pri zatvarani spojenia</returns> protected override void InternalStop() { //ak bol stav connecting tak bol spusteny reconnect if (this.m_connectionState == ConnectionStates.Connecting) this.StopReconnect(); //ziskame stav Boolean state = this.IsConnected; //deinicializacia base this.InternalDisconnect(true); //ak sme pripojeny if (state) { //spojenie bolo ukoncene this.OnDisconnected(EventArgs.Empty); } //spojenie nie ja aktivne if (this.m_connectionState != ConnectionStates.Closed) { //zmena stavu this.m_connectionState = ConnectionStates.Closed; //event oznamujuci zmenu stavu this.OnChangeConnectionState(EventArgs.Empty); } } /// <summary> /// Vrati ipEndPoint ku ktoremu sa nasledne klient pokusi pripojit /// </summary> /// <returns>IpPoint ku ktoremu sa pokusime pripojit</returns> private IPEndPoint GetIpEndPoint() { //ak sme prekrocili index dostupnych poloziek if (this.m_lastIpEndPointIndex > this.m_ipEndPoints.Count - 1) this.m_lastIpEndPointIndex = 0; //ziskame index ipEndPointu IPEndPoint ipEndPoint = this.m_ipEndPoints[this.m_lastIpEndPointIndex]; //dalsi index this.m_lastIpEndPointIndex += 1; //vratime ipEndPoint na pripojenie return ipEndPoint; } /// <summary> /// Vykona interny pokus o pripojenie k vzdialenemu bodu /// </summary> /// <param name="starting">Definuje ci ide o pripajanie pri starte alebo reconnecte</param> /// <returns>True = spojenie bolo uspesne vytvorene</returns> private Boolean InternalConnect(Boolean starting) { try { lock (this) { //pokusime sa vytvorit spojenie this.InternalOnConnect(); //ak bol aktivny reconnect tak ho ukoncime this.StopReconnect(); //start komunikacie sa podaril this.m_connectionState = ConnectionStates.Connected; //spojenie bolo vytvorene this.OnConnected(EventArgs.Empty); //doslo k zmene stavu this.OnChangeConnectionState(EventArgs.Empty); } //inicializacia komunikacie bola uspesna return true; } catch (Exception) { //ak doslo k chybe pri starte klienta if (starting == true) { throw; } //inicializacia nebola uspesna return false; } } /// <summary> /// Interna snaha o pripojenie /// </summary> private void InternalOnConnect() { try { //zalogujeme this.InternalTrace(TraceTypes.Info, "Initializing socket..."); //ak inicializujeme triedu na zaklade IP a portu if (this.m_tcpClient == null) { //ziskame ipEndPoint na pripojenie this.m_lastIpEndPoint = this.GetIpEndPoint(); //inicializujeme a pripojime klienta this.m_tcpClient = new TcpClient(); this.m_tcpClient.Connect(this.m_lastIpEndPoint); } else { //adresa ku ktorej som pripojeny this.m_lastIpEndPoint = (IPEndPoint)this.m_tcpClient.Client.RemoteEndPoint; } //nastavime timeoty pre socket this.m_tcpClient.ReceiveTimeout = this.m_tcpReadTimeout; this.m_tcpClient.SendTimeout = this.m_tcpWriteTimeout; //ziskame komunikacny stream this.m_networkStream = m_tcpClient.GetStream(); this.m_networkStream.ReadTimeout = this.m_nsReadTimeout; this.m_networkStream.WriteTimeout = this.m_nsWriteTimeout; //inicializujeme state SocketState state = new SocketState() { Stream = this.m_networkStream, Client = this.m_tcpClient }; //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Initialization socket was successful"); //nastavime detekciu spjenia this.m_isConnectied = true; //otvorime asynchronne citanie na streame this.m_networkStream.BeginRead(state.Data, 0, state.Data.Length, tcp_DataReceived, state); } catch (Exception ex) { //zalogujeme this.InternalException(ex, "Error during initializing socket. {0}", ex.Message); //nastavime detekciu spjenia this.m_isConnectied = false; this.m_tcpClient = null; this.m_networkStream = null; //preposleme vynimku throw; } } /// <summary> /// Interny disconnect /// </summary> /// <param name="closing">Definuje ci doslo u ukonceniu alebo len preruseniu spojenia</param> private void InternalDisconnect(Boolean closing) { //ukoncime komunikaciu this.InternalOnDisconnect(); //ak doslo len k padu spojenia if (this.IsDisposed == false && closing == false) { //vykoname start recconectu this.ValidateConnection(); } } /// <summary> /// Overi nastavenia triedy. Vykona start automatickehor reconnectu alebo ukonci klienta /// </summary> private void ValidateConnection() { //overime ci je mozne spustit reconnect if (this.CanAutoReconnect && this.AutoReconnect) { //event o ukonceni spojenia len ak uz bolo oznamenie o connecte if (this.m_connectionState == ConnectionStates.Connected) { //doslo k ukonceniu spojenia this.OnDisconnected(EventArgs.Empty); } //zmenime stav this.m_connectionState = ConnectionStates.Connecting; //doslo k zmene stavu this.OnChangeConnectionState(EventArgs.Empty); //spustime automaticky reconnect this.StartReconnect(); } else { //ukoncime klienta if (!this.IsDisposed) { if (this.IsRun) { //ukoncime klienta this.Stop(); } } //doslo k ukonceniu spojenia this.OnDisconnected(EventArgs.Empty); //zmenime stav this.m_connectionState = ConnectionStates.Closed; //doslo k zmene stavu this.OnChangeConnectionState(EventArgs.Empty); } } /// <summary> /// Interny disconnect /// </summary> private void InternalOnDisconnect() { try { //spojenie bolo ukoncene this.m_isConnectied = false; //ukoncime stream ak je vytvoreny if (this.m_networkStream != null) { this.m_networkStream.Close(); this.m_networkStream = null; } //ukoncime tcp spojenie if (this.m_tcpClient != null) { this.m_tcpClient.Close(); this.m_tcpClient = null; } } catch (Exception) { //preposleme vynimku vyssie throw; } finally { //nova inicializaia / deinicializacia premennych this.m_isConnectied = false; this.m_tcpClient = null; this.m_networkStream = null; } } /// <summary> /// Calback / prichod dat an streame /// </summary> /// <param name="ar">IAsyncResult</param> private void tcp_DataReceived(IAsyncResult ar) { try { this.DataReceived(ar); } catch (Exception ex) { //trace message this.InternalException(ex, "Error during receiving asynchronous data. {0}", ex.Message); } } /// <summary> /// Calback / prichod dat an streame /// </summary> /// <param name="ar">IAsyncResult</param> private void DataReceived(IAsyncResult ar) { lock (this) { //inicializacia SocketState state = (SocketState)ar.AsyncState; NetworkStream stream = state.Stream; Int32 r = 0; // kontrola ci mozme zo streamu citat if (!stream.CanRead) return; try { //prerusime asynchronne citanie r = stream.EndRead(ar); //ak neboli nacitane ziadne _data asi ide o pad spojenia if (r == 0) { //niekedy dochadza k oneskoreniu vlakna zo streamu ktory oznamuje pad spojenia if (this.IsDisposed == false) { //zalogujeme. this.InternalTrace(TraceTypes.Error, "Loss connection with the remote end point!"); //ukoncime komunikaciu this.InternalDisconnect(false); } //nebolo by vhodne nahodit t stav disconnected ??? return; } } catch (Exception ex) { //zalogujeme this.InternalException(ex, "Error during exiting asynchronous reading from the stream. {0}.", ex.Message); //ukoncime komunikaciu this.InternalDisconnect(false); //ukoncime return; } //skopirujeme pole bytov Byte[] rdata = new Byte[r]; Buffer.BlockCopy(state.Data, 0, rdata, 0, r); //zalogujeme prijate dat //this.InternalTrace(TraceTypes.Verbose, "Received _data: [{0}]", BitConverter.ToString(rdata)); this.InternalTrace(TraceTypes.Verbose, "Received data: [{0}]", rdata.Length); //_data su akeptovane len ak sme pripojeny if (this.IsConnected) { //vytvorime udalost a posleme data OnReceivedData(new DataEventArgs(rdata, state.Client.Client.RemoteEndPoint as IPEndPoint)); } try { //otvorime asynchronne citanie na streame stream.BeginRead(state.Data, 0, state.Data.Length, tcp_DataReceived, state); } catch (Exception ex) { //zalogujeme this.InternalTrace(TraceTypes.Error, "Chyba pri opatovnom spusteni asynchronneho citania zo streamu. {0}", ex.Message); //ukoncime return; } } } /// <summary> /// Spusti timer na automatiky reconnect /// </summary> private void StartReconnect() { //check reconnect mode if (this.IsRun && this.CanAutoReconnect) { //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Spustanie obsluhy automtickeho reconnectu..."); //spustime timer this.m_autoReconnectTimer = new Timer(new TimerCallback(TimerTick), null, this.m_autoReconnectTimeout, this.m_autoReconnectTimeout); //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Obsluha bola spustena."); } } /// <summary> /// Ukonci timer na automaticky reconnect /// </summary> private void StopReconnect() { //check reconnect mode if (this.CanAutoReconnect) { //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Ukoncovanie obsluhy automtickeho reconnectu..."); //ukoncime timer if (this.m_autoReconnectTimer != null) this.m_autoReconnectTimer.Dispose(); //zrusime objekt this.m_autoReconnectTimer = null; //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Obsluha bola ukoncena."); } } /// <summary> /// Obsluha pre timer vykonavajuci automatiky recconnect /// </summary> /// <param name="obj">Object</param> private void TimerTick(Object obj) { //overime ci je timer aktivny if (this.m_autoReconnectTimer == null || this.IsRun == false) return; try { //overime timer if (this.m_autoReconnectTimer != null) this.m_autoReconnectTimer.Change(Timeout.Infinite, Timeout.Infinite); } catch (ObjectDisposedException) { //chybu ignorujeme } try { //vykoname reconnect this.ReconnectProcessing(); } catch (Exception ex) { //zalogujeme this.InternalTrace(TraceTypes.Error, "Chyba pri automatickom reconnecte. {0}", ex.Message); } try { //spustime timer na povodnu hodnotu if (this.m_autoReconnectTimer != null && this.IsRun) this.m_autoReconnectTimer.Change(this.m_autoReconnectTimeout, this.m_autoReconnectTimeout); } catch (ObjectDisposedException) { //chybu ignorujeme } } /// <summary> /// Vykona automaticky reconnect /// </summary> private void ReconnectProcessing() { //obnova len ak nebol klient ukonceny if (this.IsRun) { //zalogujeme this.InternalTrace(TraceTypes.Info, "Obnovovanie spojenia...."); //vykoname obnovu if (this.InternalConnect(false)) { //inicializacia spojenia bola uspesna this.StopReconnect(); } } } #endregion #region - Call Event Method - /// <summary> /// Vytvori asynchronne volanie na metodu zabezpecujucu vytvorenie eventu /// oznamujuceho prijatie dat /// </summary> /// <param name="e">EventArgs obsahujuci data</param> protected virtual void OnReceivedData(DataEventArgs e) { DataEventHandler handler = this.m_receivedDataEvent; if (handler != null) handler(this, e); } /// <summary> /// Vytvori asynchronne volanie na metodu zabezpecujucu vytvorenie eventu /// oznamujuceho pripojenie /// </summary> /// <param name="e">EventArgs</param> protected virtual void OnConnected(EventArgs e) { EventHandler handler = this._connectedEvent; if (handler != null) handler(this, e); } /// <summary> /// Vytvori asynchronne volanie na metodu zabezpecujucu vytvorenie eventu /// oznamujuceho pad spojenia /// </summary> /// <param name="e">EventArgs</param> protected virtual void OnDisconnected(EventArgs e) { EventHandler handler = this.disconnectedEvent; if (handler != null) handler(this, e); } /// <summary> /// Vygeneruje event oznamujui zmenu stavu pripojenia /// </summary> /// <param name="e">EventArgs</param> protected virtual void OnChangeConnectionState(EventArgs e) { //ziskame pristup EventHandler handler = this._changeConnectionStateEvent; //vyvolame event if (handler != null) handler(this, e); } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Logger : Roar.ILogger { public void DebugLog( string k ) { if (Debug.isDebugBuild) Debug.Log (k); } } /** * Implementation of the IRoar interface. * This is the class you need to drag onto your unity empty to start using the * Roar framework. However once that is done you should only use the object * through the IRoar interface. That is your unity scripts should look * something like this * * var roar_:IRoar * function Awake() * { * roar_ = GetComponent(DefaultRoar) as IRoar * } * * Further documentation about how you can use the Roar object * can be found in the IRoar class. */ public class DefaultRoar : MonoBehaviour, IRoar, IUnityObject { // These are purely to enable the values to show up in the unity UI. public bool debug = true; public bool appstoreSandbox = true; public string gameKey = string.Empty; public enum XMLType { Lightweight, System }; public XMLType xmlParser = XMLType.Lightweight; public GUISkin defaultGUISkin; public Roar.IConfig Config { get { return config; } } protected Roar.IConfig config; public IWebAPI WebAPI { get { return webAPI; } } protected IWebAPI webAPI; public Roar.Components.IUser User { get { return user; } } protected Roar.Components.IUser user; public Roar.Components.IFacebook Facebook { get { return facebook; } } protected Roar.Components.IFacebook facebook; public Roar.Components.IProperties Properties { get { return properties; } } protected Roar.Components.IProperties properties; public Roar.Components.ILeaderboards Leaderboards { get { return leaderboards; } } protected Roar.Components.ILeaderboards leaderboards; //public Roar.Components.IRanking Ranking { get { return Ranking_; } } //protected Roar.Components.IRanking Ranking_; public Roar.Components.IInventory Inventory { get { return inventory; } } protected Roar.Components.IInventory inventory = null; public Roar.Components.IShop Shop { get { return shop; } } protected Roar.Components.IShop shop; public Roar.Components.IActions Actions { get { return actions; } } protected Roar.Components.IActions actions; public Roar.Components.IAchievements Achievements { get { return achievements; } } protected Roar.Components.IAchievements achievements; public Roar.Components.IGifts Gifts { get { return gifts; } } protected Roar.Components.IGifts gifts; public Roar.Components.IInAppPurchase Appstore { get{ return appstore;} } protected Roar.implementation.Components.InAppPurchase appstore; public Roar.Adapters.IUrbanAirship UrbanAirship { get{ return urbanAirship;} } protected Roar.implementation.Adapters.UrbanAirship urbanAirship; public string AuthToken { get { return config.AuthToken; } } private static DefaultRoar instance; private static IRoar api; private Roar.implementation.DataStore datastore; private Logger logger = new Logger(); /** * Access to the Roar Engine singleton. */ public static DefaultRoar Instance { get { if (instance == null) { instance = GameObject.FindObjectOfType(typeof(DefaultRoar)) as DefaultRoar; if (instance == null) Debug.LogWarning("Unable to locate the Roar interface."); } return instance; } } /** * Access to the Roar Engine API singleton. */ public static IRoar API { get { if (api == null) { DefaultRoar defaultRoar = Instance; if (defaultRoar != null) api = (IRoar)defaultRoar; } return api; } } /** * Called by unity when everything is ready to go. * We use this rather than the constructor as its what unity suggests. */ public void Awake() { config = new Roar.implementation.Config(); // Apply public settings string key = gameKey.ToLower(); //key = key.Replace("_", ""); Config.Game = key; Config.IsDebug = debug; switch (xmlParser) { case XMLType.System: IXMLNodeFactory.instance = new SystemXMLNodeFactory(); break; case XMLType.Lightweight: IXMLNodeFactory.instance = new XMLNodeFactory(); break; } RequestSender api = new RequestSender(config,this,logger); datastore = new Roar.implementation.DataStore(api, logger); webAPI = new global::WebAPI(api); user = new Roar.implementation.Components.User(webAPI.user,datastore, logger); properties = new Roar.implementation.Components.Properties( datastore ); leaderboards = new Roar.implementation.Components.Leaderboards(datastore, logger); inventory = new Roar.implementation.Components.Inventory( webAPI.items, datastore, logger); shop = new Roar.implementation.Components.Shop( webAPI.shop, datastore, logger ); actions = new Roar.implementation.Components.Actions( webAPI.tasks, datastore ); facebook = new Roar.implementation.Components.Facebook(webAPI.facebook, datastore, logger); if (!Application.isEditor) { appstore = new Roar.implementation.Components.InAppPurchase( webAPI.appstore, "Roar", logger, appstoreSandbox ); } urbanAirship = new Roar.implementation.Adapters.UrbanAirship(webAPI); DontDestroyOnLoad(gameObject); } public void Start() { if(urbanAirship!=null) urbanAirship.OnStart(); } public void OnUpdate() { if(urbanAirship!=null) urbanAirship.OnUpdate(); } string version="1.0.0"; public string Version( Roar.Callback callback = null ) { if(callback!=null) callback( new Roar.CallbackInfo<object>( version ) ); return version; } public void Login( string username, string password, Roar.Callback callback=null ) { User.DoLogin(username,password,callback); } public void FetchFacebookOAuthToken( string code, Roar.Callback callback=null ) { Facebook.DoFetchFacebookOAuthToken(code,callback); } public void LoginFacebookOAuth( string oauth_token, Roar.Callback callback=null ) { Facebook.DoLoginFacebookOAuth(oauth_token,callback); } public void LoginFacebookSignedReq( string signedReq, Roar.Callback callback=null ) { Facebook.DoLoginFacebookSignedReq(signedReq,callback); } public void Logout( Roar.Callback callback=null ) { User.DoLogout(callback); } public void CreateFacebookSignedReq( string username, string signedReq, Roar.Callback callback=null ) { Facebook.DoCreateFacebookSignedReq(username,signedReq,callback); } public void CreateFacebookOAuthToken( string username, string oAuthToken, Roar.Callback callback=null ) { Facebook.DoCreateFacebookOAuth(username,oAuthToken,callback); } public void Create( string username, string password, Roar.Callback callback=null ) { User.DoCreate(username,password,callback); } public string WhoAmI( Roar.Callback callback=null ) { if (callback!=null) callback( new Roar.CallbackInfo<object>(Properties.GetValue( "name" )) ); return Properties.GetValue( "name" ); } public string PlayerId( Roar.Callback callback=null ) { if (callback!=null) callback( new Roar.CallbackInfo<object>(Properties.GetValue( "id" )) ); return Properties.GetValue( "id" ); } public bool IsDebug{ get { return Config.IsDebug; } } public void DoCoroutine( IEnumerator method ) { this.StartCoroutine(method); } public Roar.implementation.DataStore DataStore { get { return datastore; } } public Logger Logger { get { return logger; } } #region EXTERNAL CALLBACKS void OnAppstoreProductData(string productDataXml) { Appstore.OnProductData(productDataXml); } void OnAppstoreRequestProductDataInvalidProductId(string invalidProductId) { Appstore.OnInvalidProductId(invalidProductId); } void OnAppstoreProductPurchaseComplete(string purchaseXml) { Appstore.OnPurchaseComplete(purchaseXml); } void OnAppstoreProductPurchaseCancelled(string productIdentifier) { Appstore.OnPurchaseCancelled(productIdentifier); } void OnAppstoreProductPurchaseFailed(string errorXml) { Appstore.OnPurchaseFailed(errorXml); } #endregion }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Net; using System.Reflection; using Orleans.CodeGeneration; using Orleans.Concurrency; using Orleans.Runtime; namespace Orleans.Serialization { internal static class BuiltInTypes { #region Constants private static readonly Type objectType = typeof(object); #endregion #region Generic collections internal static void SerializeGenericReadOnlyCollection(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeReadOnlyCollection", "DeserializeReadOnlyCollection", "DeepCopyReadOnlyCollection", generics); concretes.Item1(original, stream, expected); } internal static object DeserializeGenericReadOnlyCollection(Type expected, BinaryTokenStreamReader stream) { var generics = expected.GetGenericArguments(); var concretes = RegisterConcreteMethods(expected, "SerializeReadOnlyCollection", "DeserializeReadOnlyCollection", "DeepCopyReadOnlyCollection", generics); return concretes.Item2(expected, stream); } internal static object CopyGenericReadOnlyCollection(object original) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeReadOnlyCollection", "DeserializeReadOnlyCollection", "DeepCopyReadOnlyCollection", generics); return concretes.Item3(original); } internal static void SerializeReadOnlyCollection<T>(object obj, BinaryTokenStreamWriter stream, Type expected) { var collection = (ReadOnlyCollection<T>)obj; stream.Write(collection.Count); foreach (var element in collection) { SerializationManager.SerializeInner(element, stream, typeof(T)); } } internal static object DeserializeReadOnlyCollection<T>(Type expected, BinaryTokenStreamReader stream) { var count = stream.ReadInt(); var list = new List<T>(count); DeserializationContext.Current.RecordObject(list); for (var i = 0; i < count; i++) { list.Add((T)SerializationManager.DeserializeInner(typeof(T), stream)); } var ret = new ReadOnlyCollection<T>(list); DeserializationContext.Current.RecordObject(ret); return ret; } internal static object DeepCopyReadOnlyCollection<T>(object original) { var collection = (ReadOnlyCollection<T>)original; if (typeof(T).IsOrleansShallowCopyable()) { return original; } var innerList = new List<T>(collection.Count); innerList.AddRange(collection.Select(element => (T)SerializationManager.DeepCopyInner(element))); var retVal = new ReadOnlyCollection<T>(innerList); SerializationContext.Current.RecordObject(original, retVal); return retVal; } #region Lists internal static void SerializeGenericList(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeList", "DeserializeList", "DeepCopyList", generics); concretes.Item1(original, stream, expected); } internal static object DeserializeGenericList(Type expected, BinaryTokenStreamReader stream) { var generics = expected.GetGenericArguments(); var concretes = RegisterConcreteMethods(expected, "SerializeList", "DeserializeList", "DeepCopyList", generics); return concretes.Item2(expected, stream); } internal static object CopyGenericList(object original) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeList", "DeserializeList", "DeepCopyList", generics); return concretes.Item3(original); } internal static void SerializeList<T>(object obj, BinaryTokenStreamWriter stream, Type expected) { var list = (List<T>)obj; stream.Write(list.Count); foreach (var element in list) { SerializationManager.SerializeInner(element, stream, typeof(T)); } } internal static object DeserializeList<T>(Type expected, BinaryTokenStreamReader stream) { var count = stream.ReadInt(); var list = new List<T>(count); DeserializationContext.Current.RecordObject(list); for (var i = 0; i < count; i++) { list.Add((T)SerializationManager.DeserializeInner(typeof(T), stream)); } return list; } internal static object DeepCopyList<T>(object original) { var list = (List<T>)original; if (typeof(T).IsOrleansShallowCopyable()) { return new List<T>(list); } // set the list capacity, to avoid list resizing. var retVal = new List<T>(list.Count); SerializationContext.Current.RecordObject(original, retVal); retVal.AddRange(list.Select(element => (T)SerializationManager.DeepCopyInner(element))); return retVal; } #endregion #region LinkedLists internal static void SerializeGenericLinkedList(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeLinkedList", "DeserializeLinkedList", "DeepCopyLinkedList", generics); concretes.Item1(original, stream, expected); } internal static object DeserializeGenericLinkedList(Type expected, BinaryTokenStreamReader stream) { var generics = expected.GetGenericArguments(); var concretes = RegisterConcreteMethods(expected, "SerializeLinkedList", "DeserializeLinkedList", "DeepCopyLinkedList", generics); return concretes.Item2(expected, stream); } internal static object CopyGenericLinkedList(object original) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeLinkedList", "DeserializeLinkedList", "DeepCopyLinkedList", generics); return concretes.Item3(original); } internal static void SerializeLinkedList<T>(object obj, BinaryTokenStreamWriter stream, Type expected) { var list = (LinkedList<T>)obj; stream.Write(list.Count); foreach (var element in list) { SerializationManager.SerializeInner(element, stream, typeof(T)); } } internal static object DeserializeLinkedList<T>(Type expected, BinaryTokenStreamReader stream) { var count = stream.ReadInt(); var list = new LinkedList<T>(); DeserializationContext.Current.RecordObject(list); for (var i = 0; i < count; i++) { list.AddLast((T)SerializationManager.DeserializeInner(typeof(T), stream)); } return list; } internal static object DeepCopyLinkedList<T>(object original) { var list = (LinkedList<T>)original; if (typeof(T).IsOrleansShallowCopyable()) { return new LinkedList<T>(list); } var retVal = new LinkedList<T>(); SerializationContext.Current.RecordObject(original, retVal); foreach (var item in list) { retVal.AddLast((T)SerializationManager.DeepCopyInner(item)); } return retVal; } #endregion #region HashSets internal static void SerializeGenericHashSet(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeHashSet", "DeserializeHashSet", "DeepCopyHashSet", generics); concretes.Item1(original, stream, expected); } internal static object DeserializeGenericHashSet(Type expected, BinaryTokenStreamReader stream) { var generics = expected.GetGenericArguments(); var concretes = RegisterConcreteMethods(expected, "SerializeHashSet", "DeserializeHashSet", "DeepCopyHashSet", generics); return concretes.Item2(expected, stream); } internal static object CopyGenericHashSet(object original) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeHashSet", "DeserializeHashSet", "DeepCopyHashSet", generics); return concretes.Item3(original); } internal static void SerializeHashSet<T>(object obj, BinaryTokenStreamWriter stream, Type expected) { var set = (HashSet<T>)obj; SerializationManager.SerializeInner(set.Comparer.Equals(EqualityComparer<T>.Default) ? null : set.Comparer, stream, typeof(IEqualityComparer<T>)); stream.Write(set.Count); foreach (var element in set) { SerializationManager.SerializeInner(element, stream, typeof(T)); } } internal static object DeserializeHashSet<T>(Type expected, BinaryTokenStreamReader stream) { var comparer = (IEqualityComparer<T>)SerializationManager.DeserializeInner(typeof(IEqualityComparer<T>), stream); var count = stream.ReadInt(); var set = new HashSet<T>(comparer); DeserializationContext.Current.RecordObject(set); for (var i = 0; i < count; i++) { set.Add((T)SerializationManager.DeserializeInner(typeof(T), stream)); } return set; } internal static object DeepCopyHashSet<T>(object original) { var set = (HashSet<T>)original; if (typeof(T).IsOrleansShallowCopyable()) { return new HashSet<T>(set, set.Comparer); } var retVal = new HashSet<T>(set.Comparer); SerializationContext.Current.RecordObject(original, retVal); foreach (var item in set) { retVal.Add((T)SerializationManager.DeepCopyInner(item)); } return retVal; } internal static void SerializeGenericSortedSet(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeSortedSet", "DeserializeSortedSet", "DeepCopySortedSet", generics); concretes.Item1(original, stream, expected); } internal static object DeserializeGenericSortedSet(Type expected, BinaryTokenStreamReader stream) { var generics = expected.GetGenericArguments(); var concretes = RegisterConcreteMethods(expected, "SerializeSortedSet", "DeserializeSortedSet", "DeepCopySortedSet", generics); return concretes.Item2(expected, stream); } internal static object CopyGenericSortedSet(object original) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeSortedSet", "DeserializeSortedSet", "DeepCopySortedSet", generics); return concretes.Item3(original); } internal static void SerializeSortedSet<T>(object obj, BinaryTokenStreamWriter stream, Type expected) { var set = (SortedSet<T>)obj; SerializationManager.SerializeInner(set.Comparer.Equals(Comparer<T>.Default) ? null : set.Comparer, stream, typeof(IComparer<T>)); stream.Write(set.Count); foreach (var element in set) { SerializationManager.SerializeInner(element, stream, typeof(T)); } } internal static object DeserializeSortedSet<T>(Type expected, BinaryTokenStreamReader stream) { var comparer = (IComparer<T>)SerializationManager.DeserializeInner(typeof(IComparer<T>), stream); var count = stream.ReadInt(); var set = new SortedSet<T>(comparer); DeserializationContext.Current.RecordObject(set); for (var i = 0; i < count; i++) { set.Add((T)SerializationManager.DeserializeInner(typeof(T), stream)); } return set; } internal static object DeepCopySortedSet<T>(object original) { var set = (SortedSet<T>)original; if (typeof(T).IsOrleansShallowCopyable()) { return new SortedSet<T>(set, set.Comparer); } var retVal = new SortedSet<T>(set.Comparer); SerializationContext.Current.RecordObject(original, retVal); foreach (var item in set) { retVal.Add((T)SerializationManager.DeepCopyInner(item)); } return retVal; } #endregion #region Queues internal static void SerializeGenericQueue(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeQueue", "DeserializeQueue", "DeepCopyQueue", generics); concretes.Item1(original, stream, expected); } internal static object DeserializeGenericQueue(Type expected, BinaryTokenStreamReader stream) { var generics = expected.GetGenericArguments(); var concretes = RegisterConcreteMethods(expected, "SerializeQueue", "DeserializeQueue", "DeepCopyQueue", generics); return concretes.Item2(expected, stream); } internal static object CopyGenericQueue(object original) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeQueue", "DeserializeQueue", "DeepCopyQueue", generics); return concretes.Item3(original); } internal static void SerializeQueue<T>(object obj, BinaryTokenStreamWriter stream, Type expected) { var queue = (Queue<T>)obj; stream.Write(queue.Count); foreach (var element in queue) { SerializationManager.SerializeInner(element, stream, typeof(T)); } } internal static object DeserializeQueue<T>(Type expected, BinaryTokenStreamReader stream) { var count = stream.ReadInt(); var queue = new Queue<T>(); DeserializationContext.Current.RecordObject(queue); for (var i = 0; i < count; i++) { queue.Enqueue((T)SerializationManager.DeserializeInner(typeof(T), stream)); } return queue; } internal static object DeepCopyQueue<T>(object original) { var queue = (Queue<T>)original; if (typeof(T).IsOrleansShallowCopyable()) { return new Queue<T>(queue); } var retVal = new Queue<T>(queue.Count); SerializationContext.Current.RecordObject(original, retVal); foreach (var item in queue) { retVal.Enqueue((T)SerializationManager.DeepCopyInner(item)); } return retVal; } #endregion #region Stacks internal static void SerializeGenericStack(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeStack", "DeserializeStack", "DeepCopyStack", generics); concretes.Item1(original, stream, expected); } internal static object DeserializeGenericStack(Type expected, BinaryTokenStreamReader stream) { var generics = expected.GetGenericArguments(); var concretes = RegisterConcreteMethods(expected, "SerializeStack", "DeserializeStack", "DeepCopyStack", generics); return concretes.Item2(expected, stream); } internal static object CopyGenericStack(object original) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeStack", "DeserializeStack", "DeepCopyStack", generics); return concretes.Item3(original); } internal static void SerializeStack<T>(object obj, BinaryTokenStreamWriter stream, Type expected) { var stack = (Stack<T>)obj; stream.Write(stack.Count); foreach (var element in stack) { SerializationManager.SerializeInner(element, stream, typeof(T)); } } internal static object DeserializeStack<T>(Type expected, BinaryTokenStreamReader stream) { var count = stream.ReadInt(); var list = new List<T>(count); var stack = new Stack<T>(count); DeserializationContext.Current.RecordObject(stack); for (var i = 0; i < count; i++) { list.Add((T)SerializationManager.DeserializeInner(typeof(T), stream)); } for (var i = count - 1; i >= 0; i--) { stack.Push(list[i]); } return stack; } internal static object DeepCopyStack<T>(object original) { var stack = (Stack<T>)original; if (typeof(T).IsOrleansShallowCopyable()) { return new Stack<T>(stack.Reverse()); // NOTE: Yes, the Reverse really is required } var retVal = new Stack<T>(); SerializationContext.Current.RecordObject(original, retVal); foreach (var item in stack.Reverse()) { retVal.Push((T)SerializationManager.DeepCopyInner(item)); } return retVal; } #endregion #region Dictionaries internal static void SerializeGenericDictionary(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeDictionary", "DeserializeDictionary", "CopyDictionary"); concreteMethods.Item1(original, stream, expected); } internal static object DeserializeGenericDictionary(Type expected, BinaryTokenStreamReader stream) { var concreteMethods = RegisterConcreteMethods(expected, "SerializeDictionary", "DeserializeDictionary", "CopyDictionary"); return concreteMethods.Item2(expected, stream); } internal static object CopyGenericDictionary(object original) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeDictionary", "DeserializeDictionary", "CopyDictionary"); return concreteMethods.Item3(original); } internal static void SerializeDictionary<K, V>(object original, BinaryTokenStreamWriter stream, Type expected) { var dict = (Dictionary<K, V>)original; SerializationManager.SerializeInner(dict.Comparer.Equals(EqualityComparer<K>.Default) ? null : dict.Comparer, stream, typeof(IEqualityComparer<K>)); stream.Write(dict.Count); foreach (var pair in dict) { SerializationManager.SerializeInner(pair.Key, stream, typeof(K)); SerializationManager.SerializeInner(pair.Value, stream, typeof(V)); } } internal static object DeserializeDictionary<K, V>(Type expected, BinaryTokenStreamReader stream) { var comparer = (IEqualityComparer<K>)SerializationManager.DeserializeInner(typeof(IEqualityComparer<K>), stream); var count = stream.ReadInt(); var dict = new Dictionary<K, V>(count, comparer); DeserializationContext.Current.RecordObject(dict); for (var i = 0; i < count; i++) { var key = (K)SerializationManager.DeserializeInner(typeof(K), stream); var value = (V)SerializationManager.DeserializeInner(typeof(V), stream); dict[key] = value; } return dict; } internal static object CopyDictionary<K, V>(object original) { var dict = (Dictionary<K, V>)original; if (typeof(K).IsOrleansShallowCopyable() && typeof(V).IsOrleansShallowCopyable()) { return new Dictionary<K, V>(dict, dict.Comparer); } var result = new Dictionary<K, V>(dict.Count, dict.Comparer); SerializationContext.Current.RecordObject(original, result); foreach (var pair in dict) { result[(K)SerializationManager.DeepCopyInner(pair.Key)] = (V)SerializationManager.DeepCopyInner(pair.Value); } return result; } internal static void SerializeGenericReadOnlyDictionary(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeReadOnlyDictionary", "DeserializeReadOnlyDictionary", "CopyReadOnlyDictionary"); concreteMethods.Item1(original, stream, expected); } internal static object DeserializeGenericReadOnlyDictionary(Type expected, BinaryTokenStreamReader stream) { var concreteMethods = RegisterConcreteMethods(expected, "SerializeReadOnlyDictionary", "DeserializeReadOnlyDictionary", "CopyReadOnlyDictionary"); return concreteMethods.Item2(expected, stream); } internal static object CopyGenericReadOnlyDictionary(object original) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeReadOnlyDictionary", "DeserializeReadOnlyDictionary", "CopyReadOnlyDictionary"); return concreteMethods.Item3(original); } internal static void SerializeReadOnlyDictionary<K, V>(object original, BinaryTokenStreamWriter stream, Type expected) { var dict = (ReadOnlyDictionary<K, V>)original; stream.Write(dict.Count); foreach (var pair in dict) { SerializationManager.SerializeInner(pair.Key, stream, typeof(K)); SerializationManager.SerializeInner(pair.Value, stream, typeof(V)); } } internal static object DeserializeReadOnlyDictionary<K, V>(Type expected, BinaryTokenStreamReader stream) { var count = stream.ReadInt(); var dict = new Dictionary<K, V>(count); for (var i = 0; i < count; i++) { var key = (K)SerializationManager.DeserializeInner(typeof(K), stream); var value = (V)SerializationManager.DeserializeInner(typeof(V), stream); dict[key] = value; } var retVal = new ReadOnlyDictionary<K, V>(dict); DeserializationContext.Current.RecordObject(retVal); return retVal; } internal static object CopyReadOnlyDictionary<K, V>(object original) { if (typeof(K).IsOrleansShallowCopyable() && typeof(V).IsOrleansShallowCopyable()) { return original; } var dict = (ReadOnlyDictionary<K, V>)original; var innerDict = new Dictionary<K, V>(dict.Count); foreach (var pair in dict) { innerDict[(K)SerializationManager.DeepCopyInner(pair.Key)] = (V)SerializationManager.DeepCopyInner(pair.Value); } var retVal = new ReadOnlyDictionary<K, V>(innerDict); SerializationContext.Current.RecordObject(original, retVal); return retVal; } internal static void SerializeStringObjectDictionary(object original, BinaryTokenStreamWriter stream, Type expected) { var dict = (Dictionary<string, object>)original; SerializationManager.SerializeInner(dict.Comparer.Equals(EqualityComparer<string>.Default) ? null : dict.Comparer, stream, typeof(IEqualityComparer<string>)); stream.Write(dict.Count); foreach (var pair in dict) { //stream.WriteTypeHeader(stringType, stringType); stream.Write(pair.Key); SerializationManager.SerializeInner(pair.Value, stream, objectType); } } internal static object DeserializeStringObjectDictionary(Type expected, BinaryTokenStreamReader stream) { var comparer = (IEqualityComparer<string>)SerializationManager.DeserializeInner(typeof(IEqualityComparer<string>), stream); var count = stream.ReadInt(); var dict = new Dictionary<string, object>(count, comparer); DeserializationContext.Current.RecordObject(dict); for (var i = 0; i < count; i++) { //stream.ReadFullTypeHeader(stringType); // Skip the type header, which will be string var key = stream.ReadString(); var value = SerializationManager.DeserializeInner(null, stream); dict[key] = value; } return dict; } internal static object CopyStringObjectDictionary(object original) { var dict = (Dictionary<string, object>)original; var result = new Dictionary<string, object>(dict.Count, dict.Comparer); SerializationContext.Current.RecordObject(original, result); foreach (var pair in dict) { result[pair.Key] = SerializationManager.DeepCopyInner(pair.Value); } return result; } #endregion #region SortedDictionaries internal static void SerializeGenericSortedDictionary(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeSortedDictionary", "DeserializeSortedDictionary", "CopySortedDictionary"); concreteMethods.Item1(original, stream, expected); } internal static object DeserializeGenericSortedDictionary(Type expected, BinaryTokenStreamReader stream) { var concreteMethods = RegisterConcreteMethods(expected, "SerializeSortedDictionary", "DeserializeSortedDictionary", "CopySortedDictionary"); return concreteMethods.Item2(expected, stream); } internal static object CopyGenericSortedDictionary(object original) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeSortedDictionary", "DeserializeSortedDictionary", "CopySortedDictionary"); return concreteMethods.Item3(original); } internal static void SerializeSortedDictionary<K, V>(object original, BinaryTokenStreamWriter stream, Type expected) { var dict = (SortedDictionary<K, V>)original; SerializationManager.SerializeInner(dict.Comparer.Equals(Comparer<K>.Default) ? null : dict.Comparer, stream, typeof(IComparer<K>)); stream.Write(dict.Count); foreach (var pair in dict) { SerializationManager.SerializeInner(pair.Key, stream, typeof(K)); SerializationManager.SerializeInner(pair.Value, stream, typeof(V)); } } internal static object DeserializeSortedDictionary<K, V>(Type expected, BinaryTokenStreamReader stream) { var comparer = (IComparer<K>)SerializationManager.DeserializeInner(typeof(IComparer<K>), stream); var count = stream.ReadInt(); var dict = new SortedDictionary<K, V>(comparer); DeserializationContext.Current.RecordObject(dict); for (var i = 0; i < count; i++) { var key = (K)SerializationManager.DeserializeInner(typeof(K), stream); var value = (V)SerializationManager.DeserializeInner(typeof(V), stream); dict[key] = value; } return dict; } internal static object CopySortedDictionary<K, V>(object original) { var dict = (SortedDictionary<K, V>)original; if (typeof(K).IsOrleansShallowCopyable() && typeof(V).IsOrleansShallowCopyable()) { return new SortedDictionary<K, V>(dict, dict.Comparer); } var result = new SortedDictionary<K, V>(dict.Comparer); SerializationContext.Current.RecordObject(original, result); foreach (var pair in dict) { result[(K)SerializationManager.DeepCopyInner(pair.Key)] = (V)SerializationManager.DeepCopyInner(pair.Value); } return result; } #endregion #region SortedLists internal static void SerializeGenericSortedList(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeSortedList", "DeserializeSortedList", "CopySortedList"); concreteMethods.Item1(original, stream, expected); } internal static object DeserializeGenericSortedList(Type expected, BinaryTokenStreamReader stream) { var concreteMethods = RegisterConcreteMethods(expected, "SerializeSortedList", "DeserializeSortedList", "CopySortedList"); return concreteMethods.Item2(expected, stream); } internal static object CopyGenericSortedList(object original) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeSortedList", "DeserializeSortedList", "CopySortedList"); return concreteMethods.Item3(original); } internal static void SerializeSortedList<K, V>(object original, BinaryTokenStreamWriter stream, Type expected) { var list = (SortedList<K, V>)original; SerializationManager.SerializeInner(list.Comparer.Equals(Comparer<K>.Default) ? null : list.Comparer, stream, typeof(IComparer<K>)); stream.Write(list.Count); foreach (var pair in list) { SerializationManager.SerializeInner(pair.Key, stream, typeof(K)); SerializationManager.SerializeInner(pair.Value, stream, typeof(V)); } } internal static object DeserializeSortedList<K, V>(Type expected, BinaryTokenStreamReader stream) { var comparer = (IComparer<K>)SerializationManager.DeserializeInner(typeof(IComparer<K>), stream); var count = stream.ReadInt(); var list = new SortedList<K, V>(count, comparer); DeserializationContext.Current.RecordObject(list); for (var i = 0; i < count; i++) { var key = (K)SerializationManager.DeserializeInner(typeof(K), stream); var value = (V)SerializationManager.DeserializeInner(typeof(V), stream); list[key] = value; } return list; } internal static object CopySortedList<K, V>(object original) { var list = (SortedList<K, V>)original; if (typeof(K).IsOrleansShallowCopyable() && typeof(V).IsOrleansShallowCopyable()) { return new SortedList<K, V>(list, list.Comparer); } var result = new SortedList<K, V>(list.Count, list.Comparer); SerializationContext.Current.RecordObject(original, result); foreach (var pair in list) { result[(K)SerializationManager.DeepCopyInner(pair.Key)] = (V)SerializationManager.DeepCopyInner(pair.Value); } return result; } #endregion #endregion #region Other generics #region Tuples internal static void SerializeTuple(object raw, BinaryTokenStreamWriter stream, Type expected) { Type t = raw.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeTuple" + generics.Length, "DeserializeTuple" + generics.Length, "DeepCopyTuple" + generics.Length, generics); concretes.Item1(raw, stream, expected); } internal static object DeserializeTuple(Type t, BinaryTokenStreamReader stream) { var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeTuple" + generics.Length, "DeserializeTuple" + generics.Length, "DeepCopyTuple" + generics.Length, generics); return concretes.Item2(t, stream); } internal static object DeepCopyTuple(object original) { Type t = original.GetType(); var generics = t.GetGenericArguments(); var concretes = RegisterConcreteMethods(t, "SerializeTuple" + generics.Length, "DeserializeTuple" + generics.Length, "DeepCopyTuple" + generics.Length, generics); return concretes.Item3(original); } internal static object DeepCopyTuple1<T1>(object original) { var input = (Tuple<T1>)original; var result = new Tuple<T1>((T1)SerializationManager.DeepCopyInner(input.Item1)); SerializationContext.Current.RecordObject(original, result); return result; } internal static void SerializeTuple1<T1>(object obj, BinaryTokenStreamWriter stream, Type expected) { var input = (Tuple<T1>)obj; SerializationManager.SerializeInner(input.Item1, stream, typeof(T1)); } internal static object DeserializeTuple1<T1>(Type expected, BinaryTokenStreamReader stream) { var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream); return new Tuple<T1>(item1); } internal static object DeepCopyTuple2<T1, T2>(object original) { var input = (Tuple<T1, T2>)original; var result = new Tuple<T1, T2>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2)); SerializationContext.Current.RecordObject(original, result); return result; } internal static void SerializeTuple2<T1, T2>(object obj, BinaryTokenStreamWriter stream, Type expected) { var input = (Tuple<T1, T2>)obj; SerializationManager.SerializeInner(input.Item1, stream, typeof(T1)); SerializationManager.SerializeInner(input.Item2, stream, typeof(T2)); } internal static object DeserializeTuple2<T1, T2>(Type expected, BinaryTokenStreamReader stream) { var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream); var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream); return new Tuple<T1, T2>(item1, item2); } internal static object DeepCopyTuple3<T1, T2, T3>(object original) { var input = (Tuple<T1, T2, T3>)original; var result = new Tuple<T1, T2, T3>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2), (T3)SerializationManager.DeepCopyInner(input.Item3)); SerializationContext.Current.RecordObject(original, result); return result; } internal static void SerializeTuple3<T1, T2, T3>(object obj, BinaryTokenStreamWriter stream, Type expected) { var input = (Tuple<T1, T2, T3>)obj; SerializationManager.SerializeInner(input.Item1, stream, typeof(T1)); SerializationManager.SerializeInner(input.Item2, stream, typeof(T2)); SerializationManager.SerializeInner(input.Item3, stream, typeof(T3)); } internal static object DeserializeTuple3<T1, T2, T3>(Type expected, BinaryTokenStreamReader stream) { var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream); var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream); var item3 = (T3)SerializationManager.DeserializeInner(typeof(T3), stream); return new Tuple<T1, T2, T3>(item1, item2, item3); } internal static object DeepCopyTuple4<T1, T2, T3, T4>(object original) { var input = (Tuple<T1, T2, T3, T4>)original; var result = new Tuple<T1, T2, T3, T4>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2), (T3)SerializationManager.DeepCopyInner(input.Item3), (T4)SerializationManager.DeepCopyInner(input.Item4)); SerializationContext.Current.RecordObject(original, result); return result; } internal static void SerializeTuple4<T1, T2, T3, T4>(object obj, BinaryTokenStreamWriter stream, Type expected) { var input = (Tuple<T1, T2, T3, T4>)obj; SerializationManager.SerializeInner(input.Item1, stream, typeof(T1)); SerializationManager.SerializeInner(input.Item2, stream, typeof(T2)); SerializationManager.SerializeInner(input.Item3, stream, typeof(T3)); SerializationManager.SerializeInner(input.Item4, stream, typeof(T4)); } internal static object DeserializeTuple4<T1, T2, T3, T4>(Type expected, BinaryTokenStreamReader stream) { var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream); var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream); var item3 = (T3)SerializationManager.DeserializeInner(typeof(T3), stream); var item4 = (T4)SerializationManager.DeserializeInner(typeof(T4), stream); return new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4); } internal static object DeepCopyTuple5<T1, T2, T3, T4, T5>(object original) { var input = (Tuple<T1, T2, T3, T4, T5>)original; var result = new Tuple<T1, T2, T3, T4, T5>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2), (T3)SerializationManager.DeepCopyInner(input.Item3), (T4)SerializationManager.DeepCopyInner(input.Item4), (T5)SerializationManager.DeepCopyInner(input.Item5)); SerializationContext.Current.RecordObject(original, result); return result; } internal static void SerializeTuple5<T1, T2, T3, T4, T5>(object obj, BinaryTokenStreamWriter stream, Type expected) { var input = (Tuple<T1, T2, T3, T4, T5>)obj; SerializationManager.SerializeInner(input.Item1, stream, typeof(T1)); SerializationManager.SerializeInner(input.Item2, stream, typeof(T2)); SerializationManager.SerializeInner(input.Item3, stream, typeof(T3)); SerializationManager.SerializeInner(input.Item4, stream, typeof(T4)); SerializationManager.SerializeInner(input.Item5, stream, typeof(T5)); } internal static object DeserializeTuple5<T1, T2, T3, T4, T5>(Type expected, BinaryTokenStreamReader stream) { var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream); var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream); var item3 = (T3)SerializationManager.DeserializeInner(typeof(T3), stream); var item4 = (T4)SerializationManager.DeserializeInner(typeof(T4), stream); var item5 = (T5)SerializationManager.DeserializeInner(typeof(T5), stream); return new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5); } internal static object DeepCopyTuple6<T1, T2, T3, T4, T5, T6>(object original) { var input = (Tuple<T1, T2, T3, T4, T5, T6>)original; var result = new Tuple<T1, T2, T3, T4, T5, T6>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2), (T3)SerializationManager.DeepCopyInner(input.Item3), (T4)SerializationManager.DeepCopyInner(input.Item4), (T5)SerializationManager.DeepCopyInner(input.Item5), (T6)SerializationManager.DeepCopyInner(input.Item6)); SerializationContext.Current.RecordObject(original, result); return result; } internal static void SerializeTuple6<T1, T2, T3, T4, T5, T6>(object obj, BinaryTokenStreamWriter stream, Type expected) { var input = (Tuple<T1, T2, T3, T4, T5, T6>)obj; SerializationManager.SerializeInner(input.Item1, stream, typeof(T1)); SerializationManager.SerializeInner(input.Item2, stream, typeof(T2)); SerializationManager.SerializeInner(input.Item3, stream, typeof(T3)); SerializationManager.SerializeInner(input.Item4, stream, typeof(T4)); SerializationManager.SerializeInner(input.Item5, stream, typeof(T5)); SerializationManager.SerializeInner(input.Item6, stream, typeof(T6)); } internal static object DeserializeTuple6<T1, T2, T3, T4, T5, T6>(Type expected, BinaryTokenStreamReader stream) { var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream); var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream); var item3 = (T3)SerializationManager.DeserializeInner(typeof(T3), stream); var item4 = (T4)SerializationManager.DeserializeInner(typeof(T4), stream); var item5 = (T5)SerializationManager.DeserializeInner(typeof(T5), stream); var item6 = (T6)SerializationManager.DeserializeInner(typeof(T6), stream); return new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6); } internal static object DeepCopyTuple7<T1, T2, T3, T4, T5, T6, T7>(object original) { var input = (Tuple<T1, T2, T3, T4, T5, T6, T7>)original; var result = new Tuple<T1, T2, T3, T4, T5, T6, T7>((T1)SerializationManager.DeepCopyInner(input.Item1), (T2)SerializationManager.DeepCopyInner(input.Item2), (T3)SerializationManager.DeepCopyInner(input.Item3), (T4)SerializationManager.DeepCopyInner(input.Item4), (T5)SerializationManager.DeepCopyInner(input.Item5), (T6)SerializationManager.DeepCopyInner(input.Item6), (T7)SerializationManager.DeepCopyInner(input.Item7)); SerializationContext.Current.RecordObject(original, result); return result; } internal static void SerializeTuple7<T1, T2, T3, T4, T5, T6, T7>(object obj, BinaryTokenStreamWriter stream, Type expected) { var input = (Tuple<T1, T2, T3, T4, T5, T6, T7>)obj; SerializationManager.SerializeInner(input.Item1, stream, typeof(T1)); SerializationManager.SerializeInner(input.Item2, stream, typeof(T2)); SerializationManager.SerializeInner(input.Item3, stream, typeof(T3)); SerializationManager.SerializeInner(input.Item4, stream, typeof(T4)); SerializationManager.SerializeInner(input.Item5, stream, typeof(T5)); SerializationManager.SerializeInner(input.Item6, stream, typeof(T6)); SerializationManager.SerializeInner(input.Item7, stream, typeof(T7)); } internal static object DeserializeTuple7<T1, T2, T3, T4, T5, T6, T7>(Type expected, BinaryTokenStreamReader stream) { var item1 = (T1)SerializationManager.DeserializeInner(typeof(T1), stream); var item2 = (T2)SerializationManager.DeserializeInner(typeof(T2), stream); var item3 = (T3)SerializationManager.DeserializeInner(typeof(T3), stream); var item4 = (T4)SerializationManager.DeserializeInner(typeof(T4), stream); var item5 = (T5)SerializationManager.DeserializeInner(typeof(T5), stream); var item6 = (T6)SerializationManager.DeserializeInner(typeof(T6), stream); var item7 = (T7)SerializationManager.DeserializeInner(typeof(T7), stream); return new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7); } #endregion #region KeyValuePairs internal static void SerializeGenericKeyValuePair(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeKeyValuePair", "DeserializeKeyValuePair", "CopyKeyValuePair"); concreteMethods.Item1(original, stream, expected); } internal static object DeserializeGenericKeyValuePair(Type expected, BinaryTokenStreamReader stream) { var concreteMethods = RegisterConcreteMethods(expected, "SerializeKeyValuePair", "DeserializeKeyValuePair", "CopyKeyValuePair"); return concreteMethods.Item2(expected, stream); } internal static object CopyGenericKeyValuePair(object original) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeKeyValuePair", "DeserializeKeyValuePair", "CopyKeyValuePair"); return concreteMethods.Item3(original); } internal static void SerializeKeyValuePair<TK, TV>(object original, BinaryTokenStreamWriter stream, Type expected) { var pair = (KeyValuePair<TK, TV>)original; SerializationManager.SerializeInner(pair.Key, stream, typeof(TK)); SerializationManager.SerializeInner(pair.Value, stream, typeof(TV)); } internal static object DeserializeKeyValuePair<K, V>(Type expected, BinaryTokenStreamReader stream) { var key = (K)SerializationManager.DeserializeInner(typeof(K), stream); var value = (V)SerializationManager.DeserializeInner(typeof(V), stream); return new KeyValuePair<K, V>(key, value); } internal static object CopyKeyValuePair<TK, TV>(object original) { var pair = (KeyValuePair<TK, TV>)original; if (typeof(TK).IsOrleansShallowCopyable() && typeof(TV).IsOrleansShallowCopyable()) { return pair; // KeyValuePair is a struct, so there's already been a copy at this point } var result = new KeyValuePair<TK, TV>((TK)SerializationManager.DeepCopyInner(pair.Key), (TV)SerializationManager.DeepCopyInner(pair.Value)); SerializationContext.Current.RecordObject(original, result); return result; } #endregion #region Nullables internal static void SerializeGenericNullable(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeNullable", "DeserializeNullable", "CopyNullable"); concreteMethods.Item1(original, stream, expected); } internal static object DeserializeGenericNullable(Type expected, BinaryTokenStreamReader stream) { var concreteMethods = RegisterConcreteMethods(expected, "SerializeNullable", "DeserializeNullable", "CopyNullable"); return concreteMethods.Item2(expected, stream); } internal static object CopyGenericNullable(object original) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeNullable", "DeserializeNullable", "CopyNullable"); return concreteMethods.Item3(original); } internal static void SerializeNullable<T>(object original, BinaryTokenStreamWriter stream, Type expected) where T : struct { var obj = (T?)original; if (obj.HasValue) { SerializationManager.SerializeInner(obj.Value, stream, typeof(T)); } else { stream.WriteNull(); } } internal static object DeserializeNullable<T>(Type expected, BinaryTokenStreamReader stream) where T : struct { if (stream.PeekToken() == SerializationTokenType.Null) { stream.ReadToken(); return new T?(); } var val = (T)SerializationManager.DeserializeInner(typeof(T), stream); return new Nullable<T>(val); } internal static object CopyNullable<T>(object original) where T : struct { return original; // Everything is a struct, so a direct copy is fine } #endregion #region Immutables internal static void SerializeGenericImmutable(object original, BinaryTokenStreamWriter stream, Type expected) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeImmutable", "DeserializeImmutable", "CopyImmutable"); concreteMethods.Item1(original, stream, expected); } internal static object DeserializeGenericImmutable(Type expected, BinaryTokenStreamReader stream) { var concreteMethods = RegisterConcreteMethods(expected, "SerializeImmutable", "DeserializeImmutable", "CopyImmutable"); return concreteMethods.Item2(expected, stream); } internal static object CopyGenericImmutable(object original) { Type t = original.GetType(); var concreteMethods = RegisterConcreteMethods(t, "SerializeImmutable", "DeserializeImmutable", "CopyImmutable"); return concreteMethods.Item3(original); } internal static void SerializeImmutable<T>(object original, BinaryTokenStreamWriter stream, Type expected) { var obj = (Immutable<T>)original; SerializationManager.SerializeInner(obj.Value, stream, typeof(T)); } internal static object DeserializeImmutable<T>(Type expected, BinaryTokenStreamReader stream) { var val = (T)SerializationManager.DeserializeInner(typeof(T), stream); return new Immutable<T>(val); } internal static object CopyImmutable<T>(object original) { return original; // Immutable means never having to make a copy... } #endregion #endregion #region Other System types #region TimeSpan internal static void SerializeTimeSpan(object obj, BinaryTokenStreamWriter stream, Type expected) { var ts = (TimeSpan)obj; stream.Write(ts.Ticks); } internal static object DeserializeTimeSpan(Type expected, BinaryTokenStreamReader stream) { return new TimeSpan(stream.ReadLong()); } internal static object CopyTimeSpan(object obj) { return obj; // TimeSpan is a value type } #endregion #region DateTimeOffset internal static void SerializeDateTimeOffset(object obj, BinaryTokenStreamWriter stream, Type expected) { var dts = (DateTimeOffset)obj; stream.Write(dts.DateTime.Ticks); stream.Write(dts.Offset.Ticks); } internal static object DeserializeDateTimeOffset(Type expected, BinaryTokenStreamReader stream) { return new DateTimeOffset(stream.ReadLong(), new TimeSpan(stream.ReadLong())); } internal static object CopyDateTimeOffset(object obj) { return obj; // DateTimeOffset is a value type } #endregion #region Type internal static void SerializeType(object obj, BinaryTokenStreamWriter stream, Type expected) { stream.Write(((Type)obj).OrleansTypeName()); } internal static object DeserializeType(Type expected, BinaryTokenStreamReader stream) { return SerializationManager.ResolveTypeName(stream.ReadString()); } internal static object CopyType(object obj) { return obj; // Type objects are effectively immutable } #endregion Type #region GUID internal static void SerializeGuid(object obj, BinaryTokenStreamWriter stream, Type expected) { var guid = (Guid)obj; stream.Write(guid.ToByteArray()); } internal static object DeserializeGuid(Type expected, BinaryTokenStreamReader stream) { var bytes = stream.ReadBytes(16); return new Guid(bytes); } internal static object CopyGuid(object obj) { return obj; // Guids are value types } #endregion #region URIs [ThreadStatic] static private TypeConverter uriConverter; internal static void SerializeUri(object obj, BinaryTokenStreamWriter stream, Type expected) { if (uriConverter == null) uriConverter = TypeDescriptor.GetConverter(typeof(Uri)); stream.Write(uriConverter.ConvertToInvariantString(obj)); } internal static object DeserializeUri(Type expected, BinaryTokenStreamReader stream) { if (uriConverter == null) uriConverter = TypeDescriptor.GetConverter(typeof(Uri)); return uriConverter.ConvertFromInvariantString(stream.ReadString()); } internal static object CopyUri(object obj) { return obj; // URIs are immutable } #endregion #endregion #region Internal Orleans types #region Basic types internal static void SerializeGrainId(object obj, BinaryTokenStreamWriter stream, Type expected) { var id = (GrainId)obj; stream.Write(id); } internal static object DeserializeGrainId(Type expected, BinaryTokenStreamReader stream) { return stream.ReadGrainId(); } internal static object CopyGrainId(object original) { return original; } internal static void SerializeActivationId(object obj, BinaryTokenStreamWriter stream, Type expected) { var id = (ActivationId)obj; stream.Write(id); } internal static object DeserializeActivationId(Type expected, BinaryTokenStreamReader stream) { return stream.ReadActivationId(); } internal static object CopyActivationId(object original) { return original; } internal static void SerializeActivationAddress(object obj, BinaryTokenStreamWriter stream, Type expected) { var addr = (ActivationAddress)obj; stream.Write(addr); } internal static object DeserializeActivationAddress(Type expected, BinaryTokenStreamReader stream) { return stream.ReadActivationAddress(); } internal static object CopyActivationAddress(object original) { return original; } internal static void SerializeIPAddress(object obj, BinaryTokenStreamWriter stream, Type expected) { var ip = (IPAddress)obj; stream.Write(ip); } internal static object DeserializeIPAddress(Type expected, BinaryTokenStreamReader stream) { return stream.ReadIPAddress(); } internal static object CopyIPAddress(object original) { return original; } internal static void SerializeIPEndPoint(object obj, BinaryTokenStreamWriter stream, Type expected) { var ep = (IPEndPoint)obj; stream.Write(ep); } internal static object DeserializeIPEndPoint(Type expected, BinaryTokenStreamReader stream) { return stream.ReadIPEndPoint(); } internal static object CopyIPEndPoint(object original) { return original; } internal static void SerializeCorrelationId(object obj, BinaryTokenStreamWriter stream, Type expected) { var id = (CorrelationId)obj; stream.Write(id); } internal static object DeserializeCorrelationId(Type expected, BinaryTokenStreamReader stream) { var bytes = stream.ReadBytes(CorrelationId.SIZE_BYTES); return new CorrelationId(bytes); } internal static object CopyCorrelationId(object original) { return original; } internal static void SerializeSiloAddress(object obj, BinaryTokenStreamWriter stream, Type expected) { var addr = (SiloAddress)obj; stream.Write(addr); } internal static object DeserializeSiloAddress(Type expected, BinaryTokenStreamReader stream) { return stream.ReadSiloAddress(); } internal static object CopySiloAddress(object original) { return original; } internal static object CopyTaskId(object original) { return original; } #endregion #region InvokeMethodRequest internal static void SerializeInvokeMethodRequest(object obj, BinaryTokenStreamWriter stream, Type expected) { var request = (InvokeMethodRequest)obj; stream.Write(request.InterfaceId); stream.Write(request.MethodId); stream.Write(request.Arguments != null ? request.Arguments.Length : 0); if (request.Arguments != null) { foreach (var arg in request.Arguments) { SerializationManager.SerializeInner(arg, stream, null); } } } internal static object DeserializeInvokeMethodRequest(Type expected, BinaryTokenStreamReader stream) { int iid = stream.ReadInt(); int mid = stream.ReadInt(); int argCount = stream.ReadInt(); object[] args = null; if (argCount > 0) { args = new object[argCount]; for (var i = 0; i < argCount; i++) { args[i] = SerializationManager.DeserializeInner(null, stream); } } return new InvokeMethodRequest(iid, mid, args); } internal static object CopyInvokeMethodRequest(object original) { var request = (InvokeMethodRequest)original; object[] args = null; if (request.Arguments != null) { args = new object[request.Arguments.Length]; for (var i = 0; i < request.Arguments.Length; i++) { args[i] = SerializationManager.DeepCopyInner(request.Arguments[i]); } } var result = new InvokeMethodRequest(request.InterfaceId, request.MethodId, args); SerializationContext.Current.RecordObject(original, result); return result; } #endregion #region Response internal static void SerializeOrleansResponse(object obj, BinaryTokenStreamWriter stream, Type expected) { var resp = (Response)obj; SerializationManager.SerializeInner(resp.ExceptionFlag ? resp.Exception : resp.Data, stream, null); } internal static object DeserializeOrleansResponse(Type expected, BinaryTokenStreamReader stream) { var obj = SerializationManager.DeserializeInner(null, stream); return new Response(obj); } internal static object CopyOrleansResponse(object original) { var resp = (Response)original; if (resp.ExceptionFlag) { return original; } var result = new Response(SerializationManager.DeepCopyInner(resp.Data)); SerializationContext.Current.RecordObject(original, result); return result; } #endregion #endregion #region Utilities private static Tuple<SerializationManager.Serializer, SerializationManager.Deserializer, SerializationManager.DeepCopier> RegisterConcreteMethods(Type t, string serializerName, string deserializerName, string copierName, Type[] genericArgs = null) { if (genericArgs == null) { genericArgs = t.GetGenericArguments(); } var genericCopier = typeof(BuiltInTypes).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).Where(m => m.Name == copierName).FirstOrDefault(); var concreteCopier = genericCopier.MakeGenericMethod(genericArgs); var copier = (SerializationManager.DeepCopier)concreteCopier.CreateDelegate(typeof(SerializationManager.DeepCopier)); var genericSerializer = typeof(BuiltInTypes).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).Where(m => m.Name == serializerName).FirstOrDefault(); var concreteSerializer = genericSerializer.MakeGenericMethod(genericArgs); var serializer = (SerializationManager.Serializer)concreteSerializer.CreateDelegate(typeof(SerializationManager.Serializer)); var genericDeserializer = typeof(BuiltInTypes).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).Where(m => m.Name == deserializerName).FirstOrDefault(); var concreteDeserializer = genericDeserializer.MakeGenericMethod(genericArgs); var deserializer = (SerializationManager.Deserializer)concreteDeserializer.CreateDelegate(typeof(SerializationManager.Deserializer)); SerializationManager.Register(t, copier, serializer, deserializer); return new Tuple<SerializationManager.Serializer, SerializationManager.Deserializer, SerializationManager.DeepCopier>(serializer, deserializer, copier); } public static Tuple<SerializationManager.Serializer, SerializationManager.Deserializer, SerializationManager.DeepCopier> RegisterConcreteMethods(Type concreteType, Type definingType, string copierName, string serializerName, string deserializerName, Type[] genericArgs = null) { if (genericArgs == null) { genericArgs = concreteType.GetGenericArguments(); } var genericCopier = definingType.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).Where(m => m.Name == copierName).FirstOrDefault(); var concreteCopier = genericCopier.MakeGenericMethod(genericArgs); var copier = (SerializationManager.DeepCopier)concreteCopier.CreateDelegate(typeof(SerializationManager.DeepCopier)); var genericSerializer = definingType.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).Where(m => m.Name == serializerName).FirstOrDefault(); var concreteSerializer = genericSerializer.MakeGenericMethod(genericArgs); var serializer = (SerializationManager.Serializer)concreteSerializer.CreateDelegate(typeof(SerializationManager.Serializer)); var genericDeserializer = definingType.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).Where(m => m.Name == deserializerName).FirstOrDefault(); var concreteDeserializer = genericDeserializer.MakeGenericMethod(genericArgs); var deserializer = (SerializationManager.Deserializer)concreteDeserializer.CreateDelegate(typeof(SerializationManager.Deserializer)); SerializationManager.Register(concreteType, copier, serializer, deserializer); return new Tuple<SerializationManager.Serializer, SerializationManager.Deserializer, SerializationManager.DeepCopier>(serializer, deserializer, copier); } #endregion } }
<!-- Copyright 2010 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <?cs # Table of contents for devices.?> <ul id="nav"> <!-- Porting Android --> <li class="nav-section"> <div class="nav-section-header"> <a href="<?cs var:toroot ?>devices/index.html"> <span class="en">Porting</span> </a> </div> <ul> <li><a href="<?cs var:toroot ?>devices/media.html">Media</a></li> <li class="nav-section"> <div class="nav-section-header"> <a href="<?cs var:toroot ?>devices/audio.html"> <span class="en">Audio</span> </a> </div> <ul> <li><a href="<?cs var:toroot ?>devices/audio_latency.html">Latency</a></li> <li><a href="<?cs var:toroot ?>devices/audio_warmup.html">Warmup</a></li> <li><a href="<?cs var:toroot ?>devices/audio_avoiding_pi.html">Avoiding Priority Inversion</a></li> <li><a href="<?cs var:toroot ?>devices/latency_design.html">Design For Reduced Latency</a></li> <li><a href="<?cs var:toroot ?>devices/audio_terminology.html">Terminology</a></li> <li><a href="<?cs var:toroot ?>devices/testing_circuit.html">Testing Circuit</a></li> </ul> </li> <li><a href="<?cs var:toroot ?>devices/camera.html">Camera v1</a></li> <li><a href="<?cs var:toroot ?>devices/drm.html">DRM</a></li> <li><a href="<?cs var:toroot ?>devices/graphics.html">Graphics</a></li> <li><a href="<?cs var:toroot ?>devices/bluetooth.html">Bluetooth</a></li> <!-- Find a better section for these --> <li class="nav-section"> <div class="nav-section-header empty"> <a href="<?cs var:toroot ?>devices/reference/files.html"> <span class="en">Reference</span> </a> </div> </li> </ul> </li> <!-- End Porting Android --> </li> <li class="nav-section"> <div class="nav-section-header"> <a href="<?cs var:toroot ?>devices/tech/index.html"> <span class="en">Technical Information</span> </a> </div> <ul> <li class="nav-section"> <div class="nav-section-header"> <a href="<?cs var:toroot ?>devices/tech/dalvik/index.html"> <span class="en">Dalvik</span></a> </div> <ul> <li><a href="<?cs var:toroot ?>devices/tech/dalvik/dalvik-bytecode.html">Bytecode Format</a></li> <li><a href="<?cs var:toroot ?>devices/tech/dalvik/dex-format.html">.Dex Format</a></li> <li><a href="<?cs var:toroot ?>devices/tech/dalvik/instruction-formats.html">Instruction Formats</a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"> <a href="<?cs var:toroot ?>devices/tech/datausage/index.html"> <span class="en">Data Usage</span> </a> </div> <ul> <li><a href="<?cs var:toroot ?>devices/tech/datausage/iface-overview.html">Network interface statistics overview</a></li> <li><a href="<?cs var:toroot ?>devices/tech/datausage/excluding-network-types.html">Excluding Network Types from Data Usage</a></li> <li><a href="<?cs var:toroot ?>devices/tech/datausage/tethering-data.html">Tethering Data</a></li> <li><a href="<?cs var:toroot ?>devices/tech/datausage/usage-cycle-resets-dates.html">Usage Cycle Reset Dates</a></li> <li><a href="<?cs var:toroot ?>devices/tech/datausage/kernel-overview.html">Kernel Overview</a></li> <li><a href="<?cs var:toroot ?>devices/tech/datausage/tags-explained.html">Data Usage Tags Explained</a></li> <li><a href="<?cs var:toroot ?>devices/tech/datausage/kernel-changes.html">Kernel Changes</a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"> <a href="<?cs var:toroot ?>devices/debugtune.html"> <span class="en">Debugging and Tuning</span> </a> </div> <ul> <li><a href="<?cs var:toroot ?>devices/tuning.html">Performance Tuning</a></li> <li><a href="<?cs var:toroot ?>devices/native-memory.html">Native Memory Usage</a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"> <a href="<?cs var:toroot ?>devices/tech/encryption/index.html"> <span class="en">Encryption</span> </a> </div> <ul> <li><a href="<?cs var:toroot ?>devices/tech/encryption/android_crypto_implementation.html">Encryption Technical Information</a></li> </ul> </li> <li> <a href="<?cs var:toroot ?>devices/tech/storage/index.html"> <span class="en">External Storage</span> </a> </li> <li class="nav-section"> <div class="nav-section-header"> <a href="<?cs var:toroot ?>devices/tech/input/index.html"> <span class="en">Input</span> </a> </div> <ul> <li><a href="<?cs var:toroot ?>devices/tech/input/overview.html">Overview</a></li> <li><a href="<?cs var:toroot ?>devices/tech/input/key-layout-files.html">Key Layout Files</a></li> <li><a href="<?cs var:toroot ?>devices/tech/input/key-character-map-files.html">Key Character Map Files</a></li> <li><a href="<?cs var:toroot ?>devices/tech/input/input-device-configuration-files.html">Input Device Configuration Files</a></li> <li><a href="<?cs var:toroot ?>devices/tech/input/migration-guide.html">Migration Guide</a></li> <li><a href="<?cs var:toroot ?>devices/tech/input/keyboard-devices.html">Keyboard Devices</a></li> <li><a href="<?cs var:toroot ?>devices/tech/input/touch-devices.html">Touch Devices</a></li> <li><a href="<?cs var:toroot ?>devices/tech/input/dumpsys.html">Dumpsys</a></li> <li><a href="<?cs var:toroot ?>devices/tech/input/getevent.html">Getevent</a></li> <li><a href="<?cs var:toroot ?>devices/tech/input/validate-keymaps.html">Validate Keymaps</a></li> </ul> </li> <li> <a href="<?cs var:toroot ?>devices/tech/kernel.html"> <span class="en">Kernel</span> </a> </li> <li> <a href="<?cs var:toroot ?>devices/tech/power.html"> <span class="en">Power</span> </a> </li> <li class="nav-section"> <div class="nav-section-header"> <a href="<?cs var:toroot ?>devices/tech/security/index.html"> <span class="en">Security</span> </a> </div> <ul> <li> <a href="<?cs var:toroot ?>devices/tech/security/enhancements42.html"> <span class="en">Security Enhancements in Android 4.2</span> </a> </li> <li> <a href="<?cs var:toroot ?>devices/tech/security/enhancements43.html"> <span class="en">Security Enhancements in Android 4.3</span> </a> </li> <li> <a href="<?cs var:toroot ?>devices/tech/security/se-linux.html"> <span class="en">Security-Enhanced Linux</span> </a> </li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"> <a href="<?cs var:toroot ?>devices/tech/test_infra/tradefed/index.html"> <span class="en">Trade Federation Testing Infrastructure</span> </a> </div> <ul> <li><a href="<?cs var:toroot ?>devices/tech/test_infra/tradefed/fundamentals/index.html" >Start Here</a></li> <li><a href="<?cs var:toroot ?>devices/tech/test_infra/tradefed/fundamentals/machine_setup.html" >Machine Setup</a></li> <li><a href="<?cs var:toroot ?>devices/tech/test_infra/tradefed/fundamentals/devices.html" >Working with Devices</a></li> <li><a href="<?cs var:toroot ?>devices/tech/test_infra/tradefed/fundamentals/lifecycle.html" >Test Lifecycle</a></li> <li><a href="<?cs var:toroot ?>devices/tech/test_infra/tradefed/fundamentals/options.html" >Option Handling</a></li> <li><a href="<?cs var:toroot ?>devices/tech/test_infra/tradefed/full_example.html" >An End-to-End Example</a></li> <li id="tradefed-tree-list" class="nav-section"> <div class="nav-section-header"> <a href="<?cs var:toroot ?>reference/packages.html"> <span class="en">Reference</span> </a> <div> </li> </ul> </li> </ul> </li> </ul>
// ReSharper disable PossibleMultipleEnumeration namespace Gu.Wpf.DataGrid2D { using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; /// <summary> /// A bindable view of a list. /// </summary> #pragma warning disable CA1010 // Collections should implement generic interface WPF needs only IList public class Lists2DView : Lists2DViewBase #pragma warning restore CA1010 // Collections should implement generic interface { /// <summary> /// Initializes a new instance of the <see cref="Lists2DView"/> class. /// </summary> /// <param name="source">The <see cref="IEnumerable{IEnumerable}"/>.</param> public Lists2DView(IEnumerable<IEnumerable> source) : base(source) { if (source is null) { throw new ArgumentNullException(nameof(source)); } bool isEmpty = source.IsEmpty(); this.MaxColumnCount = isEmpty ? 0 : source.Max(x => x.Count()); var itemType = source.GetElementType().GetEnumerableItemType(); this.ColumnElementTypes = Enumerable.Repeat(itemType, this.MaxColumnCount).ToList(); var min = isEmpty ? 0 : this.Source.Min(x => x.Count()); this.ColumnIsReadOnlies = Enumerable.Repeat(false, min) .Concat(Enumerable.Repeat(true, this.MaxColumnCount - min)) .ToList(); this.ResetRows(); } /// <inheritdoc/> public override bool IsTransposed => false; internal IReadOnlyList<Type> ColumnElementTypes { get; } internal IReadOnlyList<bool> ColumnIsReadOnlies { get; } internal int MaxColumnCount { get; } /// <inheritdoc/> public override bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { if (sender is null) { throw new ArgumentNullException(nameof(sender)); } if (e is null) { throw new ArgumentNullException(nameof(e)); } if (managerType != typeof(CollectionChangedEventManager)) { return false; } var ccea = (NotifyCollectionChangedEventArgs)e; if (this.IsColumnsChange(ccea)) { this.OnColumnsChanged(); return true; } _ = base.ReceiveWeakEvent(managerType, sender, e); if (ReferenceEquals(sender, this.Source)) { switch (ccea.Action) { case NotifyCollectionChangedAction.Add: this.AddRows(ccea.NewStartingIndex, ccea.NewItems.Count); break; case NotifyCollectionChangedAction.Remove: this.RemoveRows(ccea.OldStartingIndex, ccea.OldItems.Count); break; case NotifyCollectionChangedAction.Replace: this.Rows[ccea.NewStartingIndex].RaiseAllChanged(); break; case NotifyCollectionChangedAction.Move: this.Rows[ccea.OldStartingIndex].RaiseAllChanged(); this.Rows[ccea.NewStartingIndex].RaiseAllChanged(); break; case NotifyCollectionChangedAction.Reset: this.ResetRows(); break; default: throw new ArgumentOutOfRangeException(nameof(e)); } } else if (this.Source is { } source) { var changed = (IEnumerable)sender; var row = source.IndexOf(changed); switch (ccea.Action) { case NotifyCollectionChangedAction.Add: this.Rows[row].RaiseColumnsChanged(changed.Count() - ccea.NewItems.Count, ccea.NewItems.Count); break; case NotifyCollectionChangedAction.Remove: if (!changed.IsEmpty()) { this.Rows[row].RaiseColumnsChanged(changed.Count() - ccea.OldItems.Count, ccea.OldItems.Count); } break; case NotifyCollectionChangedAction.Replace: this.Rows[row].RaiseColumnsChanged(ccea.NewStartingIndex, 1); break; case NotifyCollectionChangedAction.Move: this.Rows[row].RaiseColumnsChanged(ccea.OldStartingIndex, 1); this.Rows[row].RaiseColumnsChanged(ccea.NewStartingIndex, 1); break; case NotifyCollectionChangedAction.Reset: this.Rows[row].RaiseColumnsChanged(0, this.MaxColumnCount); break; default: throw new ArgumentOutOfRangeException(nameof(e)); } } return true; } /// <inheritdoc/> protected override ListRowView CreateRow(int index) { var propertyDescriptors = this.Rows.Count > 0 ? this.Rows[0].GetProperties() : ListIndexPropertyDescriptor.GetRowPropertyDescriptorCollection(this.ColumnElementTypes, this.ColumnIsReadOnlies, this.MaxColumnCount); return new ListRowView(this, index, propertyDescriptors); } // ReSharper disable once UnusedParameter.Local private bool IsColumnsChange(NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: case NotifyCollectionChangedAction.Remove: case NotifyCollectionChangedAction.Reset: break; case NotifyCollectionChangedAction.Replace: case NotifyCollectionChangedAction.Move: return false; default: throw new ArgumentOutOfRangeException(nameof(e)); } if (this.Source is { } source) { var min = this.MaxColumnCount; var max = 0; foreach (var row in source) { var count = row.Count(); if (count > max) { max = count; } if (count < min) { min = count; } } if (max != this.MaxColumnCount) { return true; } var readOnlies = this.ColumnIsReadOnlies.Count(x => x == false); if (min != readOnlies) { return true; } } return false; } private void ResetRows() { var source = this.Source; this.Rows.Clear(); if (source is null || !source.Any()) { this.OnCollectionChanged(NotifyCollectionResetEventArgs); return; } for (var index = 0; index < source.Count(); index++) { var listRowView = this.CreateRow(index); this.Rows.Add(listRowView); } this.OnPropertyChanged(CountPropertyChangedEventArgs); this.OnPropertyChanged(IndexerPropertyChangedEventArgs); this.OnCollectionChanged(NotifyCollectionResetEventArgs); } } }