context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class represents settings specified by de jure or // de facto standards for a particular country/region. In // contrast to CultureInfo, the RegionInfo does not represent // preferences of the user and does not depend on the user's // language or culture. // // //////////////////////////////////////////////////////////////////////////// using System; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization { [Serializable] public partial class RegionInfo { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // // // Name of this region (ie: es-US): serialized, the field used for deserialization // internal String _name; // // The CultureData instance that we are going to read data from. // internal CultureData _cultureData; // // The RegionInfo for our current region // internal static volatile RegionInfo s_currentRegionInfo; //////////////////////////////////////////////////////////////////////// // // RegionInfo Constructors // // Note: We prefer that a region be created with a full culture name (ie: en-US) // because otherwise the native strings won't be right. // // In Silverlight we enforce that RegionInfos must be created with a full culture name // //////////////////////////////////////////////////////////////////////// public RegionInfo(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, nameof(name)); } Contract.EndContractBlock(); // // For CoreCLR we only want the region names that are full culture names // _cultureData = CultureData.GetCultureDataForRegion(name, true); if (_cultureData == null) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, name), nameof(name)); // Not supposed to be neutral if (_cultureData.IsNeutralCulture) throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), nameof(name)); SetName(name); } [System.Security.SecuritySafeCritical] // auto-generated public RegionInfo(int culture) { if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture); } if (culture == CultureInfo.LOCALE_NEUTRAL) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } if (culture == CultureInfo.LOCALE_CUSTOM_DEFAULT) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CustomCultureCannotBePassedByNumber, culture), nameof(culture)); } _cultureData = CultureData.GetCultureData(culture, true); _name = _cultureData.SREGIONNAME; if (_cultureData.IsNeutralCulture) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } } internal RegionInfo(CultureData cultureData) { _cultureData = cultureData; _name = _cultureData.SREGIONNAME; } private void SetName(string name) { // Use the name of the region we found _name = _cultureData.SREGIONNAME; } [OnSerializing] private void OnSerializing(StreamingContext ctx) { } [System.Security.SecurityCritical] // auto-generated [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { _cultureData = CultureData.GetCultureData(_name, true); if (_cultureData == null) { throw new ArgumentException( String.Format(CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, _name), "_name"); } _name = _cultureData.SREGIONNAME; } //////////////////////////////////////////////////////////////////////// // // GetCurrentRegion // // This instance provides methods based on the current user settings. // These settings are volatile and may change over the lifetime of the // thread. // //////////////////////////////////////////////////////////////////////// public static RegionInfo CurrentRegion { get { RegionInfo temp = s_currentRegionInfo; if (temp == null) { temp = new RegionInfo(CultureInfo.CurrentCulture.m_cultureData); // Need full name for custom cultures temp._name = temp._cultureData.SREGIONNAME; s_currentRegionInfo = temp; } return temp; } } //////////////////////////////////////////////////////////////////////// // // GetName // // Returns the name of the region (ie: en-US) // //////////////////////////////////////////////////////////////////////// public virtual String Name { get { Contract.Assert(_name != null, "Expected RegionInfo._name to be populated already"); return (_name); } } //////////////////////////////////////////////////////////////////////// // // GetEnglishName // // Returns the name of the region in English. (ie: United States) // //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { get { return (_cultureData.SENGCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetDisplayName // // Returns the display name (localized) of the region. (ie: United States // if the current UI language is en-US) // //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { get { return (_cultureData.SLOCALIZEDCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetNativeName // // Returns the native name of the region. (ie: Deutschland) // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual String NativeName { get { return (_cultureData.SNATIVECOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // TwoLetterISORegionName // // Returns the two letter ISO region name (ie: US) // //////////////////////////////////////////////////////////////////////// public virtual String TwoLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterISORegionName // // Returns the three letter ISO region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME2); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterWindowsRegionName // // Returns the three letter windows region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterWindowsRegionName { get { // ThreeLetterWindowsRegionName is really same as ThreeLetterISORegionName return ThreeLetterISORegionName; } } //////////////////////////////////////////////////////////////////////// // // IsMetric // // Returns true if this region uses the metric measurement system // //////////////////////////////////////////////////////////////////////// public virtual bool IsMetric { get { int value = _cultureData.IMEASURE; return (value == 0); } } public virtual int GeoId { get { return (_cultureData.IGEOID); } } //////////////////////////////////////////////////////////////////////// // // CurrencyEnglishName // // English name for this region's currency, ie: Swiss Franc // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyEnglishName { get { return (_cultureData.SENGLISHCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencyNativeName // // Native name for this region's currency, ie: Schweizer Franken // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyNativeName { get { return (_cultureData.SNATIVECURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencySymbol // // Currency Symbol for this locale, ie: Fr. or $ // //////////////////////////////////////////////////////////////////////// public virtual String CurrencySymbol { get { return (_cultureData.SCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // ISOCurrencySymbol // // ISO Currency Symbol for this locale, ie: CHF // //////////////////////////////////////////////////////////////////////// public virtual String ISOCurrencySymbol { get { return (_cultureData.SINTLSYMBOL); } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same RegionInfo as the current instance. // // RegionInfos are considered equal if and only if they have the same name // (ie: en-US) // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { RegionInfo that = value as RegionInfo; if (that != null) { return this.Name.Equals(that.Name); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for RegionInfo // A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns the name of the Region, ie: es-US // //////////////////////////////////////////////////////////////////////// public override String ToString() { return (Name); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Elasticsearch.Net.Connection.Configuration; using Elasticsearch.Net.Connection.RequestHandlers; using Elasticsearch.Net.Connection.RequestState; using Elasticsearch.Net.ConnectionPool; using Elasticsearch.Net.Exceptions; using Elasticsearch.Net.Providers; using Elasticsearch.Net.Serialization; using PurifyNet; namespace Elasticsearch.Net.Connection { public class Transport : ITransport, ITransportDelegator { protected internal readonly IConnectionConfigurationValues ConfigurationValues; protected internal readonly IConnection Connection; private readonly IElasticsearchSerializer _serializer; private readonly IConnectionPool _connectionPool; private readonly IDateTimeProvider _dateTimeProvider; private readonly IMemoryStreamProvider _memoryStreamProvider; private readonly RequestHandler _requestHandler; private readonly RequestHandlerAsync _requestHandlerAsync; private DateTime? _lastSniff; private const int DefaultPingTimeout = 1000; private readonly int SslDefaultPingTimeout = 2000; public IConnectionConfigurationValues Settings { get { return ConfigurationValues; } } public IElasticsearchSerializer Serializer { get { return _serializer; } } private ITransportDelegator Self { get { return this; } } public Transport( IConnectionConfigurationValues configurationValues, IConnection connection, IElasticsearchSerializer serializer, IDateTimeProvider dateTimeProvider = null, IMemoryStreamProvider memoryStreamProvider = null ) { this.ConfigurationValues = configurationValues; this.Connection = connection ?? new HttpConnection(configurationValues); this._serializer = serializer ?? new ElasticsearchDefaultSerializer(); this._connectionPool = this.ConfigurationValues.ConnectionPool; this._dateTimeProvider = dateTimeProvider ?? new DateTimeProvider(); this._memoryStreamProvider = memoryStreamProvider ?? new MemoryStreamProvider(); this._lastSniff = this._dateTimeProvider.Now(); this.Settings.Serializer = this._serializer; this._requestHandler = new RequestHandler(this.Settings, this._connectionPool, this.Connection, this._serializer, this._memoryStreamProvider, this); this._requestHandlerAsync = new RequestHandlerAsync(this.Settings, this._connectionPool, this.Connection, this._serializer, this._memoryStreamProvider, this); if (this._connectionPool.AcceptsUpdates && this.Settings.SniffsOnStartup && !this._connectionPool.SniffedOnStartup) { Self.SniffClusterState(); this._connectionPool.SniffedOnStartup = true; } } /* PING/SNIFF *** ********************************************/ bool ITransportDelegator.Ping(ITransportRequestState requestState) { var defaultPingTimeout = this._connectionPool.UsingSsl ? SslDefaultPingTimeout : DefaultPingTimeout; var pingTimeout = this.Settings.PingTimeout.GetValueOrDefault(defaultPingTimeout); pingTimeout = requestState.RequestConfiguration != null ? requestState.RequestConfiguration.ConnectTimeout.GetValueOrDefault(pingTimeout) : pingTimeout; var requestOverrides = new RequestConfiguration { ConnectTimeout = pingTimeout, RequestTimeout = pingTimeout }; try { ElasticsearchResponse<Stream> response; using (var rq = requestState.InitiateRequest(RequestType.Ping)) { response = this.Connection.HeadSync(requestState.CreatePathOnCurrentNode(""), requestOverrides); rq.Finish(response.Success, response.HttpStatusCode); } if (!response.HttpStatusCode.HasValue || response.HttpStatusCode.Value == -1) throw new Exception("ping returned no status code", response.OriginalException); this.ThrowAuthExceptionWhenNeeded(response); if (response.Response == null) return response.Success; using (response.Response) return response.Success; } catch (ElasticsearchAuthException) { throw; } catch (Exception e) { throw new PingException(requestState.CurrentNode, e); } } Task<bool> ITransportDelegator.PingAsync(ITransportRequestState requestState) { var defaultPingTimeout = this._connectionPool.UsingSsl ? SslDefaultPingTimeout : DefaultPingTimeout; var pingTimeout = this.Settings.PingTimeout.GetValueOrDefault(defaultPingTimeout); pingTimeout = requestState.RequestConfiguration != null ? requestState.RequestConfiguration.ConnectTimeout.GetValueOrDefault(pingTimeout) : pingTimeout; var requestOverrides = new RequestConfiguration { ConnectTimeout = pingTimeout, RequestTimeout = pingTimeout }; var rq = requestState.InitiateRequest(RequestType.Ping); try { return this.Connection.Head(requestState.CreatePathOnCurrentNode(""), requestOverrides) .ContinueWith(t => { if (t.IsFaulted) { rq.Finish(false, null); rq.Dispose(); throw new PingException(requestState.CurrentNode, t.Exception); } rq.Finish(t.Result.Success, t.Result.HttpStatusCode); rq.Dispose(); var response = t.Result; if (!response.HttpStatusCode.HasValue || response.HttpStatusCode.Value == -1) throw new PingException(requestState.CurrentNode, t.Exception); this.ThrowAuthExceptionWhenNeeded(response); using (response.Response) return response.Success; }); } catch (ElasticsearchAuthException) { throw; } catch (Exception e) { var tcs = new TaskCompletionSource<bool>(); var pingException = new PingException(requestState.CurrentNode, e); tcs.SetException(pingException); return tcs.Task; } } IList<Uri> ITransportDelegator.Sniff(ITransportRequestState ownerState = null) { var defaultPingTimeout = this._connectionPool.UsingSsl ? SslDefaultPingTimeout : DefaultPingTimeout; var pingTimeout = this.Settings.PingTimeout.GetValueOrDefault(defaultPingTimeout); var requestOverrides = new RequestConfiguration { ConnectTimeout = pingTimeout, RequestTimeout = pingTimeout, DisableSniff = true //sniff call should never recurse }; var requestParameters = new RequestParameters { RequestConfiguration = requestOverrides }; try { var path = "_nodes/_all/clear?timeout=" + pingTimeout; ElasticsearchResponse<Stream> response; using (var requestState = new TransportRequestState<Stream>(this.Settings, requestParameters, "GET", path)) { response = this._requestHandler.Request(requestState); //inform the owing request state of the requests the sniffs did. if (requestState.RequestMetrics != null && ownerState != null) { foreach (var r in requestState.RequestMetrics.Where(p => p.RequestType == RequestType.ElasticsearchCall)) r.RequestType = RequestType.Sniff; if (ownerState.RequestMetrics == null) ownerState.RequestMetrics = new List<RequestMetrics>(); ownerState.RequestMetrics.AddRange(requestState.RequestMetrics); } this.ThrowAuthExceptionWhenNeeded(response); if (response.Response == null) return null; using (response.Response) { return Sniffer.FromStream( response, response.Response, this.Serializer, this.Connection.AddressScheme ); } } } catch (MaxRetryException e) { throw new MaxRetryException(new SniffException(e)); } } void ITransportDelegator.SniffClusterState(ITransportRequestState requestState = null) { if (!this._connectionPool.AcceptsUpdates) return; var newClusterState = Self.Sniff(requestState); if (!newClusterState.HasAny()) return; this._connectionPool.UpdateNodeList(newClusterState); this._lastSniff = this._dateTimeProvider.Now(); } void ITransportDelegator.SniffOnStaleClusterState(ITransportRequestState requestState) { if (Self.SniffingDisabled(requestState.RequestConfiguration)) return; var sniffLifeSpan = this.ConfigurationValues.SniffInformationLifeSpan; var now = this._dateTimeProvider.Now(); if (requestState.Retried == 0 && this._lastSniff.HasValue && sniffLifeSpan.HasValue && sniffLifeSpan.Value < (now - this._lastSniff.Value)) Self.SniffClusterState(requestState); } void ITransportDelegator.SniffOnConnectionFailure(ITransportRequestState requestState) { if (requestState.SniffedOnConnectionFailure || !requestState.UsingPooling || Self.SniffingDisabled(requestState.RequestConfiguration) || !this.ConfigurationValues.SniffsOnConnectionFault || requestState.Retried != 0) return; Self.SniffClusterState(requestState); requestState.SniffedOnConnectionFailure = true; } /* REQUEST STATE *** ********************************************/ /// <summary> /// Returns whether the current delegation over nodes took too long and we should quit. /// if <see cref="ConnectionSettings.SetMaxRetryTimeout"/> is set we'll use that timeout otherwise we default to th value of /// <see cref="ConnectionSettings.SetTimeout"/> which itself defaults to 60 seconds /// </summary> bool ITransportDelegator.TookTooLongToRetry(ITransportRequestState requestState) { var timeout = this.Settings.MaxRetryTimeout.GetValueOrDefault(TimeSpan.FromMilliseconds(this.Settings.Timeout)); var startedOn = requestState.StartedOn; var now = this._dateTimeProvider.Now(); //we apply a soft margin so that if a request timesout at 59 seconds when the maximum is 60 //we also abort. var margin = (timeout.TotalMilliseconds / 100.0) * 98; var marginTimeSpan = TimeSpan.FromMilliseconds(margin); var timespanCall = (now - startedOn); var tookToLong = timespanCall >= marginTimeSpan; return tookToLong; } /// <summary> /// Returns either the fixed maximum set on the connection configuration settings or the number of nodes /// </summary> int ITransportDelegator.GetMaximumRetries(IRequestConfiguration requestConfiguration) { //if we have a request specific max retry setting use that if (requestConfiguration != null && requestConfiguration.MaxRetries.HasValue) return requestConfiguration.MaxRetries.Value; return this.ConfigurationValues.MaxRetries.GetValueOrDefault(this._connectionPool.MaxRetries); } bool ITransportDelegator.SniffingDisabled(IRequestConfiguration requestConfiguration) { if (!this._connectionPool.AcceptsUpdates) return true; if (requestConfiguration == null) return false; return requestConfiguration.DisableSniff.GetValueOrDefault(false); } bool ITransportDelegator.SniffOnFaultDiscoveredMoreNodes(ITransportRequestState requestState, int retried, ElasticsearchResponse<Stream> streamResponse) { if (!requestState.UsingPooling || retried != 0 || (streamResponse != null && streamResponse.SuccessOrKnownError)) return false; Self.SniffOnConnectionFailure(requestState); return Self.GetMaximumRetries(requestState.RequestConfiguration) > 0; } /// <summary> /// Selects next node uri on request state /// </summary> /// <returns>bool hint whether the new current node needs to pinged first</returns> bool ITransportDelegator.SelectNextNode(ITransportRequestState requestState) { if (requestState.RequestConfiguration != null && requestState.RequestConfiguration.ForceNode != null) { requestState.Seed = 0; return false; } int initialSeed; bool shouldPingHint; var baseUri = this._connectionPool.GetNext(requestState.Seed, out initialSeed, out shouldPingHint); requestState.Seed = initialSeed; requestState.CurrentNode = baseUri; return shouldPingHint && !this.ConfigurationValues.DisablePings && (requestState.RequestConfiguration == null || !requestState.RequestConfiguration.DisablePing.GetValueOrDefault(false)); } private void ThrowAuthExceptionWhenNeeded(ElasticsearchResponse<Stream> response) { var statusCode = response.HttpStatusCode.GetValueOrDefault(200); switch (statusCode) { case 401: throw new ElasticsearchAuthenticationException(response); case 403: throw new ElasticsearchAuthorizationException(response); } } public ElasticsearchResponse<T> DoRequest<T>(string method, string path, object data = null, IRequestParameters requestParameters = null) { using (var requestState = new TransportRequestState<T>(this.Settings, requestParameters, method, path)) { return this._requestHandler.Request<T>(requestState, data); } } public Task<ElasticsearchResponse<T>> DoRequestAsync<T>(string method, string path, object data = null, IRequestParameters requestParameters = null) { using (var requestState = new TransportRequestState<T>(this.Settings, requestParameters, method, path)) { return this._requestHandlerAsync.RequestAsync(requestState, data) .ContinueWith<ElasticsearchResponse<T>>(t => { if (t.IsFaulted && t.Exception != null) { t.Exception.Flatten().InnerException.RethrowKeepingStackTrace(); return null; //won't be hit } return t.Result; }); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Sockets { // This object is used to wrap a bunch of ConnectAsync operations // on behalf of a single user call to ConnectAsync with a DnsEndPoint internal abstract class MultipleConnectAsync { protected SocketAsyncEventArgs _userArgs; protected SocketAsyncEventArgs _internalArgs; protected DnsEndPoint _endPoint; protected IPAddress[] _addressList; protected int _nextAddress; private enum State { NotStarted, DnsQuery, ConnectAttempt, Completed, Canceled, } private State _state; private readonly object _lockObject = new object(); // Called by Socket to kick off the ConnectAsync process. We'll complete the user's SAEA // when it's done. Returns true if the operation will be asynchronous, false if it has failed synchronously public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint) { lock (_lockObject) { if (endPoint.AddressFamily != AddressFamily.Unspecified && endPoint.AddressFamily != AddressFamily.InterNetwork && endPoint.AddressFamily != AddressFamily.InterNetworkV6) { NetEventSource.Fail(this, $"Unexpected endpoint address family: {endPoint.AddressFamily}"); } _userArgs = args; _endPoint = endPoint; // If Cancel() was called before we got the lock, it only set the state to Canceled: we need to // fail synchronously from here. Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail. if (_state == State.Canceled) { SyncFail(new SocketException((int)SocketError.OperationAborted)); return false; } if (_state != State.NotStarted) { NetEventSource.Fail(this, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state"); } _state = State.DnsQuery; IAsyncResult result = Dns.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null); if (result.CompletedSynchronously) { return DoDnsCallback(result, true); } else { return true; } } } // Callback which fires when the Dns Resolve is complete private void DnsCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { DoDnsCallback(result, false); } } // Called when the DNS query completes (either synchronously or asynchronously). Checks for failure and // starts the first connection attempt if it succeeded. Returns true if the operation will be asynchronous, // false if it has failed synchronously. private bool DoDnsCallback(IAsyncResult result, bool sync) { Exception exception = null; lock (_lockObject) { // If the connection attempt was canceled during the dns query, the user's callback has already been // called asynchronously and we simply need to return. if (_state == State.Canceled) { return true; } if (_state != State.DnsQuery) { NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): Unexpected object state"); } try { _addressList = Dns.EndGetHostAddresses(result); if (_addressList == null) { NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!"); } } catch (Exception e) { _state = State.Completed; exception = e; } // If the dns query succeeded, try to connect to the first address if (exception == null) { _state = State.ConnectAttempt; _internalArgs = new SocketAsyncEventArgs(); _internalArgs.Completed += InternalConnectCallback; _internalArgs.CopyBufferFrom(_userArgs); exception = AttemptConnection(); if (exception != null) { // There was a synchronous error while connecting _state = State.Completed; } } } // Call this outside of the lock because it might call the user's callback. if (exception != null) { return Fail(sync, exception); } else { return true; } } // Callback which fires when an internal connection attempt completes. // If it failed and there are more addresses to try, do it. private void InternalConnectCallback(object sender, SocketAsyncEventArgs args) { Exception exception = null; lock (_lockObject) { if (_state == State.Canceled) { // If Cancel was called before we got the lock, the Socket will be closed soon. We need to report // OperationAborted (even though the connection actually completed), or the user will try to use a // closed Socket. exception = new SocketException((int)SocketError.OperationAborted); } else { Debug.Assert(_state == State.ConnectAttempt); if (args.SocketError == SocketError.Success) { // The connection attempt succeeded; go to the completed state. // The callback will be called outside the lock. _state = State.Completed; } else if (args.SocketError == SocketError.OperationAborted) { // The socket was closed while the connect was in progress. This can happen if the user // closes the socket, and is equivalent to a call to CancelConnectAsync exception = new SocketException((int)SocketError.OperationAborted); _state = State.Canceled; } else { // Keep track of this because it will be overwritten by AttemptConnection SocketError currentFailure = args.SocketError; Exception connectException = AttemptConnection(); if (connectException == null) { // don't call the callback, another connection attempt is successfully started return; } else { SocketException socketException = connectException as SocketException; if (socketException != null && socketException.SocketErrorCode == SocketError.NoData) { // If the error is NoData, that means there are no more IPAddresses to attempt // a connection to. Return the last error from an actual connection instead. exception = new SocketException((int)currentFailure); } else { exception = connectException; } _state = State.Completed; } } } } if (exception == null) { Succeed(); } else { AsyncFail(exception); } } // Called to initiate a connection attempt to the next address in the list. Returns an exception // if the attempt failed synchronously, or null if it was successfully initiated. private Exception AttemptConnection() { try { Socket attemptSocket; IPAddress attemptAddress = GetNextAddress(out attemptSocket); if (attemptAddress == null) { return new SocketException((int)SocketError.NoData); } _internalArgs.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint.Port); return AttemptConnection(attemptSocket, _internalArgs); } catch (Exception e) { if (e is ObjectDisposedException) { NetEventSource.Fail(this, "unexpected ObjectDisposedException"); } return e; } } private Exception AttemptConnection(Socket attemptSocket, SocketAsyncEventArgs args) { try { if (attemptSocket == null) { NetEventSource.Fail(null, "attemptSocket is null!"); } bool pending = attemptSocket.ConnectAsync(args); if (!pending) { InternalConnectCallback(null, args); } } catch (ObjectDisposedException) { // This can happen if the user closes the socket, and is equivalent to a call // to CancelConnectAsync return new SocketException((int)SocketError.OperationAborted); } catch (Exception e) { return e; } return null; } protected abstract void OnSucceed(); private void Succeed() { OnSucceed(); _userArgs.FinishWrapperConnectSuccess(_internalArgs.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags); _internalArgs.Dispose(); } protected abstract void OnFail(bool abortive); private bool Fail(bool sync, Exception e) { if (sync) { SyncFail(e); return false; } else { AsyncFail(e); return true; } } private void SyncFail(Exception e) { OnFail(false); if (_internalArgs != null) { _internalArgs.Dispose(); } SocketException socketException = e as SocketException; if (socketException != null) { _userArgs.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None); } else { ExceptionDispatchInfo.Throw(e); } } private void AsyncFail(Exception e) { OnFail(false); if (_internalArgs != null) { _internalArgs.Dispose(); } _userArgs.FinishConnectByNameAsyncFailure(e, 0, SocketFlags.None); } public void Cancel() { bool callOnFail = false; lock (_lockObject) { switch (_state) { case State.NotStarted: // Cancel was called before the Dns query was started. The dns query won't be started // and the connection attempt will fail synchronously after the state change to DnsQuery. // All we need to do here is close all the sockets. callOnFail = true; break; case State.DnsQuery: // Cancel was called after the Dns query was started, but before it finished. We can't // actually cancel the Dns query, but we'll fake it by failing the connect attempt asynchronously // from here, and silently dropping the connection attempt when the Dns query finishes. Task.Factory.StartNew( s => CallAsyncFail(s), null, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); callOnFail = true; break; case State.ConnectAttempt: // Cancel was called after the Dns query completed, but before we had a connection result to give // to the user. Closing the sockets will cause any in-progress ConnectAsync call to fail immediately // with OperationAborted, and will cause ObjectDisposedException from any new calls to ConnectAsync // (which will be translated to OperationAborted by AttemptConnection). callOnFail = true; break; case State.Completed: // Cancel was called after we locked in a result to give to the user. Ignore it and give the user // the real completion. break; default: NetEventSource.Fail(this, "Unexpected object state"); break; } _state = State.Canceled; } // Call this outside the lock because Socket.Close may block if (callOnFail) { OnFail(true); } } // Call AsyncFail on a threadpool thread so it's asynchronous with respect to Cancel(). private void CallAsyncFail(object ignored) { AsyncFail(new SocketException((int)SocketError.OperationAborted)); } protected abstract IPAddress GetNextAddress(out Socket attemptSocket); } // Used when the instance ConnectAsync method is called, or when the DnsEndPoint specified // an AddressFamily. There's only one Socket, and we only try addresses that match its // AddressFamily internal sealed class SingleSocketMultipleConnectAsync : MultipleConnectAsync { private readonly Socket _socket; private readonly bool _userSocket; public SingleSocketMultipleConnectAsync(Socket socket, bool userSocket) { _socket = socket; _userSocket = userSocket; } protected override IPAddress GetNextAddress(out Socket attemptSocket) { _socket.ReplaceHandleIfNecessaryAfterFailedConnect(); IPAddress rval = null; do { if (_nextAddress >= _addressList.Length) { attemptSocket = null; return null; } rval = _addressList[_nextAddress]; ++_nextAddress; } while (!_socket.CanTryAddressFamily(rval.AddressFamily)); attemptSocket = _socket; return rval; } protected override void OnFail(bool abortive) { // Close the socket if this is an abortive failure (CancelConnectAsync) // or if we created it internally if (abortive || !_userSocket) { _socket.Dispose(); } } // nothing to do on success protected override void OnSucceed() { } } // This is used when the static ConnectAsync method is called. We don't know the address family // ahead of time, so we create both IPv4 and IPv6 sockets. internal sealed class DualSocketMultipleConnectAsync : MultipleConnectAsync { private readonly Socket _socket4; private readonly Socket _socket6; public DualSocketMultipleConnectAsync(SocketType socketType, ProtocolType protocolType) { if (Socket.OSSupportsIPv4) { _socket4 = new Socket(AddressFamily.InterNetwork, socketType, protocolType); } if (Socket.OSSupportsIPv6) { _socket6 = new Socket(AddressFamily.InterNetworkV6, socketType, protocolType); } } protected override IPAddress GetNextAddress(out Socket attemptSocket) { IPAddress rval = null; attemptSocket = null; while (attemptSocket == null) { if (_nextAddress >= _addressList.Length) { return null; } rval = _addressList[_nextAddress]; ++_nextAddress; if (rval.AddressFamily == AddressFamily.InterNetworkV6) { attemptSocket = _socket6; } else if (rval.AddressFamily == AddressFamily.InterNetwork) { attemptSocket = _socket4; } } attemptSocket?.ReplaceHandleIfNecessaryAfterFailedConnect(); return rval; } // on success, close the socket that wasn't used protected override void OnSucceed() { if (_socket4 != null && !_socket4.Connected) { _socket4.Dispose(); } if (_socket6 != null && !_socket6.Connected) { _socket6.Dispose(); } } // close both sockets whether its abortive or not - we always create them internally protected override void OnFail(bool abortive) { _socket4?.Dispose(); _socket6?.Dispose(); } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security; using System.Xml; namespace Umbraco.Core { public static class ObjectExtensions { //private static readonly ConcurrentDictionary<Type, Func<object>> ObjectFactoryCache = new ConcurrentDictionary<Type, Func<object>>(); public static IEnumerable<T> AsEnumerableOfOne<T>(this T input) { return Enumerable.Repeat(input, 1); } public static void DisposeIfDisposable(this object input) { var disposable = input as IDisposable; if (disposable != null) disposable.Dispose(); } /// <summary> /// Provides a shortcut way of safely casting an input when you cannot guarantee the <typeparam name="T"></typeparam> is an instance type (i.e., when the C# AS keyword is not applicable) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input">The input.</param> /// <returns></returns> internal static T SafeCast<T>(this object input) { if (ReferenceEquals(null, input) || ReferenceEquals(default(T), input)) return default(T); if (input is T) return (T)input; return default(T); } /// <summary> /// Tries to convert the input object to the output type using TypeConverters /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input"></param> /// <returns></returns> public static Attempt<T> TryConvertTo<T>(this object input) { var result = TryConvertTo(input, typeof(T)); if (!result.Success) { //just try a straight up conversion try { var converted = (T) input; return Attempt<T>.Succeed(converted); } catch (Exception e) { return Attempt<T>.Fail(e); } } return !result.Success ? Attempt<T>.Fail() : Attempt<T>.Succeed((T)result.Result); } /// <summary> /// Tries to convert the input object to the output type using TypeConverters. If the destination type is a superclass of the input type, /// if will use <see cref="Convert.ChangeType(object,System.Type)"/>. /// </summary> /// <param name="input">The input.</param> /// <param name="destinationType">Type of the destination.</param> /// <returns></returns> public static Attempt<object> TryConvertTo(this object input, Type destinationType) { if (input == null) return Attempt<object>.Fail(); if (destinationType == typeof(object)) return Attempt.Succeed(input); if (input.GetType() == destinationType) return Attempt.Succeed(input); //check for string so that overloaders of ToString() can take advantage of the conversion. if (destinationType == typeof(string)) return Attempt<object>.Succeed(input.ToString()); // if we've got a nullable of something, we try to convert directly to that thing. if (destinationType.IsGenericType && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>)) { var underlyingType = Nullable.GetUnderlyingType(destinationType); //special case for empty strings for bools/dates which should return null if an empty string var asString = input as string; if (asString != null && string.IsNullOrEmpty(asString) && (underlyingType == typeof(DateTime) || underlyingType == typeof(bool))) { return Attempt<object>.Succeed(null); } // recursively call into myself with the inner (not-nullable) type and handle the outcome var nonNullable = input.TryConvertTo(underlyingType); // and if sucessful, fall on through to rewrap in a nullable; if failed, pass on the exception if (nonNullable.Success) input = nonNullable.Result; // now fall on through... else return Attempt<object>.Fail(nonNullable.Exception); } // we've already dealed with nullables, so any other generic types need to fall through if (!destinationType.IsGenericType) { if (input is string) { var result = TryConvertToFromString(input as string, destinationType); // if we processed the string (succeed or fail), we're done if (result.HasValue) return result.Value; } //TODO: Do a check for destination type being IEnumerable<T> and source type implementing IEnumerable<T> with // the same 'T', then we'd have to find the extension method for the type AsEnumerable() and execute it. if (TypeHelper.IsTypeAssignableFrom(destinationType, input.GetType()) && TypeHelper.IsTypeAssignableFrom<IConvertible>(input)) { try { var casted = Convert.ChangeType(input, destinationType); return Attempt.Succeed(casted); } catch (Exception e) { return Attempt<object>.Fail(e); } } } var inputConverter = TypeDescriptor.GetConverter(input); if (inputConverter.CanConvertTo(destinationType)) { try { var converted = inputConverter.ConvertTo(input, destinationType); return Attempt.Succeed(converted); } catch (Exception e) { return Attempt<object>.Fail(e); } } if (destinationType == typeof(bool)) { var boolConverter = new CustomBooleanTypeConverter(); if (boolConverter.CanConvertFrom(input.GetType())) { try { var converted = boolConverter.ConvertFrom(input); return Attempt.Succeed(converted); } catch (Exception e) { return Attempt<object>.Fail(e); } } } var outputConverter = TypeDescriptor.GetConverter(destinationType); if (outputConverter.CanConvertFrom(input.GetType())) { try { var converted = outputConverter.ConvertFrom(input); return Attempt.Succeed(converted); } catch (Exception e) { return Attempt<object>.Fail(e); } } if (TypeHelper.IsTypeAssignableFrom<IConvertible>(input)) { try { var casted = Convert.ChangeType(input, destinationType); return Attempt.Succeed(casted); } catch (Exception e) { return Attempt<object>.Fail(e); } } return Attempt<object>.Fail(); } private static Nullable<Attempt<object>> TryConvertToFromString(this string input, Type destinationType) { if (destinationType == typeof(string)) return Attempt<object>.Succeed(input); if (string.IsNullOrEmpty(input)) { if (destinationType == typeof(Boolean)) return Attempt<object>.Succeed(false); // special case for booleans, null/empty == false if (destinationType == typeof(DateTime)) return Attempt<object>.Succeed(DateTime.MinValue); } // we have a non-empty string, look for type conversions in the expected order of frequency of use... if (destinationType.IsPrimitive) { if (destinationType == typeof(Int32)) { Int32 value; return Int32.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } if (destinationType == typeof(Int64)) { Int64 value; return Int64.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } if (destinationType == typeof(Boolean)) { Boolean value; if (Boolean.TryParse(input, out value)) return Attempt<object>.Succeed(value); // don't declare failure so the CustomBooleanTypeConverter can try } else if (destinationType == typeof(Int16)) { Int16 value; return Int16.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Double)) { Double value; return Double.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Single)) { Single value; return Single.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Char)) { Char value; return Char.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Byte)) { Byte value; return Byte.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(SByte)) { SByte value; return SByte.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(UInt32)) { UInt32 value; return UInt32.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(UInt16)) { UInt16 value; return UInt16.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(UInt64)) { UInt64 value; return UInt64.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } } else if (destinationType == typeof(Guid)) { Guid value; return Guid.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(DateTime)) { DateTime value; return DateTime.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(DateTimeOffset)) { DateTimeOffset value; return DateTimeOffset.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(TimeSpan)) { TimeSpan value; return TimeSpan.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Decimal)) { Decimal value; return Decimal.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Version)) { Version value; return Version.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } // E_NOTIMPL IPAddress, BigInteger return null; // we can't decide... } internal static void CheckThrowObjectDisposed(this IDisposable disposable, bool isDisposed, string objectname) { //TODO: Localise this exception if (isDisposed) throw new ObjectDisposedException(objectname); } //public enum PropertyNamesCaseType //{ // CamelCase, // CaseInsensitive //} ///// <summary> ///// Convert an object to a JSON string with camelCase formatting ///// </summary> ///// <param name="obj"></param> ///// <returns></returns> //public static string ToJsonString(this object obj) //{ // return obj.ToJsonString(PropertyNamesCaseType.CamelCase); //} ///// <summary> ///// Convert an object to a JSON string with the specified formatting ///// </summary> ///// <param name="obj">The obj.</param> ///// <param name="propertyNamesCaseType">Type of the property names case.</param> ///// <returns></returns> //public static string ToJsonString(this object obj, PropertyNamesCaseType propertyNamesCaseType) //{ // var type = obj.GetType(); // var dateTimeStyle = "yyyy-MM-dd HH:mm:ss"; // if (type.IsPrimitive || typeof(string).IsAssignableFrom(type)) // { // return obj.ToString(); // } // if (typeof(DateTime).IsAssignableFrom(type) || typeof(DateTimeOffset).IsAssignableFrom(type)) // { // return Convert.ToDateTime(obj).ToString(dateTimeStyle); // } // var serializer = new JsonSerializer(); // switch (propertyNamesCaseType) // { // case PropertyNamesCaseType.CamelCase: // serializer.ContractResolver = new CamelCasePropertyNamesContractResolver(); // break; // } // var dateTimeConverter = new IsoDateTimeConverter // { // DateTimeStyles = System.Globalization.DateTimeStyles.None, // DateTimeFormat = dateTimeStyle // }; // if (typeof(IDictionary).IsAssignableFrom(type)) // { // return JObject.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter); // } // if (type.IsArray || (typeof(IEnumerable).IsAssignableFrom(type))) // { // return JArray.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter); // } // return JObject.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter); //} /// <summary> /// Converts an object into a dictionary /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <typeparam name="TVal"> </typeparam> /// <param name="o"></param> /// <param name="ignoreProperties"></param> /// <returns></returns> internal static IDictionary<string, TVal> ToDictionary<T, TProperty, TVal>(this T o, params Expression<Func<T, TProperty>>[] ignoreProperties) { return o.ToDictionary<TVal>(ignoreProperties.Select(e => o.GetPropertyInfo(e)).Select(propInfo => propInfo.Name).ToArray()); } /// <summary> /// Turns object into dictionary /// </summary> /// <param name="o"></param> /// <param name="ignoreProperties">Properties to ignore</param> /// <returns></returns> internal static IDictionary<string, TVal> ToDictionary<TVal>(this object o, params string[] ignoreProperties) { if (o != null) { var props = TypeDescriptor.GetProperties(o); var d = new Dictionary<string, TVal>(); foreach (var prop in props.Cast<PropertyDescriptor>().Where(x => !ignoreProperties.Contains(x.Name))) { var val = prop.GetValue(o); if (val != null) { d.Add(prop.Name, (TVal)val); } } return d; } return new Dictionary<string, TVal>(); } internal static string ToDebugString(this object obj, int levels = 0) { if (obj == null) return "{null}"; try { if (obj is string) { return "\"{0}\"".InvariantFormat(obj); } if (obj is int || obj is Int16 || obj is Int64 || obj is float || obj is double || obj is bool || obj is int? || obj is Int16? || obj is Int64? || obj is float? || obj is double? || obj is bool?) { return "{0}".InvariantFormat(obj); } if (obj is Enum) { return "[{0}]".InvariantFormat(obj); } if (obj is IEnumerable) { var enumerable = (obj as IEnumerable); var items = (from object enumItem in enumerable let value = GetEnumPropertyDebugString(enumItem, levels) where value != null select value).Take(10).ToList(); return items.Count() > 0 ? "{{ {0} }}".InvariantFormat(String.Join(", ", items)) : null; } var props = obj.GetType().GetProperties(); if ((props.Count() == 2) && props[0].Name == "Key" && props[1].Name == "Value" && levels > -2) { try { var key = props[0].GetValue(obj, null) as string; var value = props[1].GetValue(obj, null).ToDebugString(levels - 1); return "{0}={1}".InvariantFormat(key, value); } catch (Exception) { return "[KeyValuePropertyException]"; } } if (levels > -1) { var items = from propertyInfo in props let value = GetPropertyDebugString(propertyInfo, obj, levels) where value != null select "{0}={1}".InvariantFormat(propertyInfo.Name, value); return items.Count() > 0 ? "[{0}]:{{ {1} }}".InvariantFormat(obj.GetType().Name, String.Join(", ", items)) : null; } } catch (Exception ex) { return "[Exception:{0}]".InvariantFormat(ex.Message); } return null; } /// <summary> /// Attempts to serialize the value to an XmlString using ToXmlString /// </summary> /// <param name="value"></param> /// <param name="type"></param> /// <returns></returns> internal static Attempt<string> TryConvertToXmlString(this object value, Type type) { try { var output = value.ToXmlString(type); return Attempt.Succeed(output); } catch (NotSupportedException ex) { return Attempt<string>.Fail(ex); } } /// <summary> /// Returns an XmlSerialized safe string representation for the value /// </summary> /// <param name="value"></param> /// <param name="type">The Type can only be a primitive type or Guid and byte[] otherwise an exception is thrown</param> /// <returns></returns> internal static string ToXmlString(this object value, Type type) { if (type == typeof(string)) return ((string)value).IsNullOrWhiteSpace() ? "" : (string)value; if (type == typeof(bool)) return XmlConvert.ToString((bool)value); if (type == typeof(byte)) return XmlConvert.ToString((byte)value); if (type == typeof(char)) return XmlConvert.ToString((char)value); if (type == typeof(DateTime)) return XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.RoundtripKind); if (type == typeof(DateTimeOffset)) return XmlConvert.ToString((DateTimeOffset)value); if (type == typeof(decimal)) return XmlConvert.ToString((decimal)value); if (type == typeof(double)) return XmlConvert.ToString((double)value); if (type == typeof(float)) return XmlConvert.ToString((float)value); if (type == typeof(Guid)) return XmlConvert.ToString((Guid)value); if (type == typeof(int)) return XmlConvert.ToString((int)value); if (type == typeof(long)) return XmlConvert.ToString((long)value); if (type == typeof(sbyte)) return XmlConvert.ToString((sbyte)value); if (type == typeof(short)) return XmlConvert.ToString((short)value); if (type == typeof(TimeSpan)) return XmlConvert.ToString((TimeSpan)value); if (type == typeof(bool)) return XmlConvert.ToString((bool)value); if (type == typeof(uint)) return XmlConvert.ToString((uint)value); if (type == typeof(ulong)) return XmlConvert.ToString((ulong)value); if (type == typeof(ushort)) return XmlConvert.ToString((ushort)value); throw new NotSupportedException("Cannot convert type " + type.FullName + " to a string using ToXmlString as it is not supported by XmlConvert"); } private static string GetEnumPropertyDebugString(object enumItem, int levels) { try { return enumItem.ToDebugString(levels - 1); } catch (Exception) { return "[GetEnumPartException]"; } } private static string GetPropertyDebugString(PropertyInfo propertyInfo, object obj, int levels) { try { return propertyInfo.GetValue(obj, null).ToDebugString(levels - 1); } catch (Exception) { return "[GetPropertyValueException]"; } } } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion LGPL License #region Using Directives using System; using System.Collections; using Axiom.Core; using Axiom.MathLib; using Axiom.Collections; using Axiom.SceneManagers.PagingLandscape.Collections; using Axiom.SceneManagers.PagingLandscape.Tile; using Axiom.SceneManagers.PagingLandscape.Page; #endregion Using Directives #region Versioning Information /// File Revision /// =============================================== /// OgrePagingLandScapeData2DManager.h 1.9 /// OgrePagingLandScapeData2DManager.cpp 1.14 /// #endregion namespace Axiom.SceneManagers.PagingLandscape.Data2D { /// <summary> /// Summary description for Data2DManager. /// </summary> public class Data2DManager: IDisposable { #region Singleton Implementation /// <summary> /// Constructor /// </summary> private Data2DManager() { long w = Options.Instance.World_Width; long h = Options.Instance.World_Height; //Setup the page array long i, j; data2D = new Data2DPages(); for ( i = 0; i < w; i++) { Data2DRow dr = new Data2DRow(); data2D.Add( dr ); for ( j = 0; j < w; j++ ) dr.Add( null ); } //Populate the page array if ( Options.Instance.Data2DFormat == "HeightField" ) { for ( j = 0; j < h; j++ ) { for ( i = 0; i < w; i++ ) { data2D[ i ][ j ] = new Data2D_HeightField(); } } } else if (Options.Instance.Data2DFormat == "ClientGen") { for (j = 0; j < h; j++) { for (i = 0; i < w; i++) { data2D[i][j] = new Data2D_ClientGen((int)i, (int)j); } } } /* else if ( Options.Instance.Data2DFormat == "HeightFieldTC" ) { for ( j = 0; j < h; j++ ) { for ( i = 0; i < w; i++ ) { Data2D data; data = new Data2D_HeightFieldTC(); data2D[ i ][ j ] = data; } } } else if ( Options.Instance.Data2DFormat == "SplineField" ) { for ( j = 0; j < h; j++ ) { for ( i = 0; i < w; i++ ) { eData2D data; data = new Data2D_Spline(); data2D[ i ][ j ] = data; } } } */ else { throw new Exception( "PageData2D not supplied!"); } // when data is not yet loaded it gives the absolute maximum possible maxHeight = data2D[ 0 ][ 0 ].MaxHeight; } private static Data2DManager instance = null; public static Data2DManager Instance { get { if ( instance == null ) instance = new Data2DManager(); return instance; } } #endregion Singleton Implementation #region IDisposable Implementation public void Dispose() { if (instance == this) { data2D.Clear(); instance = null; } } #endregion IDisposable Implementation #region Fields Data2DPages data2D; float maxHeight; #endregion Fields public void Load( long dataX, long dataZ ) { Data2D data = data2D[ dataX ][ dataZ ]; if ( !data.IsLoaded ) { data.Load( dataX, dataZ ); } } public void Unload( long dataX, long dataZ ) { Data2D data = data2D[ dataX ][ dataZ ]; if ( data.IsLoaded ) { data.Unload(); } } public bool IsLoaded( long dataX, long dataZ ) { return data2D[ dataX ][ dataZ ].IsLoaded; } public float GetHeight( long dataX, long dataZ, float x, float z ) { Data2D data = data2D[ dataX ][ dataZ ]; if ( data.IsLoaded ) { return data.GetHeight(x, z); } return 0.0f; } public float GetHeight( long dataX, long dataZ, long x, long z ) { Data2D data = data2D[ dataX ][ dataZ ]; if ( data.IsLoaded ) { return data.GetHeight(x, z); } return 0.0f; } public float GetHeightAtPage( long dataX, long dataZ, float x, float z) { Data2D data = null; float lX = x; float lZ = z; float pSize = Options.Instance.PageSize; //check if we have to change current page if ( lX < 0.0f ) { if ( dataX == 0 ) lX = 0.0f; else { data = data2D[ dataX - 1 ][ dataZ ]; if ( data.IsLoaded ) { lX = (float) (pSize - 1); } else { lX = 0.0f; data = data2D[ dataX ][ dataZ ]; } } } else if (lX > pSize) { if ( dataX == Options.Instance.World_Width - 1 ) lX = (float) (pSize); else { data = data2D[ dataX + 1 ][ dataZ ]; if ( data.IsLoaded ) { lX = 0.0f; } else { lX = (float) (pSize); data = data2D[ dataX ][ dataZ ]; } } } if ( lZ < 0.0f ) { if ( dataZ == 0 ) lZ = 0.0f; else { data = data2D[ dataX ][ dataZ - 1 ]; if ( data.IsLoaded ) { lZ = (float)(pSize); } else { lZ = 0.0f; data = data2D[ dataX ][ dataZ ]; } } } else if (lZ > pSize) { if ( dataZ == Options.Instance.World_Height - 1) lZ = (float) (pSize); else { data = data2D[ dataX ][ dataZ + 1 ]; if ( data.IsLoaded ) { lZ = 0.0f; } else { lZ = (float) (pSize); data = data2D[ dataX ][ dataZ ]; } } } if ( data == null ) data = data2D[ dataX ][ dataZ ]; if ( data.IsLoaded ) { return data.GetHeight (lX, lZ); } return 0.0f; } public float GetHeightAtPage( long dataX, long dataZ, int x, int z) { Data2D data = data2D[ dataX ][ dataZ ]; if ( data.IsLoaded ) { int lX = x; int lZ = z; int pSize = (int)Options.Instance.PageSize; //check if we have to change current page if ( lX < 0 ) { if ( dataX == 0 ) lX = 0; else { data = data2D[ dataX - 1 ][ dataZ ]; if ( data.IsLoaded ) { lX = pSize; } else { lX = 0; data = data2D[ dataX ][ dataZ ]; } } } else if (lX > pSize) { if ( dataX == Options.Instance.World_Width ) lX = pSize; else { data = data2D[ dataX + 1 ][ dataZ ]; if ( data.IsLoaded ) { lX = 0; } else { lX = pSize; data = data2D[ dataX ][ dataZ ]; } } } if ( lZ < 0 ) { if ( dataZ == 0 ) lZ = 0; else { data = data2D[ dataX ][ dataZ - 1 ]; if ( data.IsLoaded ) { lZ = pSize; } else { lZ = 0; data = data2D[ dataX ][ dataZ ]; } } } else if (lZ > pSize) { if ( dataZ == Options.Instance.World_Height ) lZ = pSize; else { data = data2D[ dataX ][ dataZ + 1 ]; if ( data.IsLoaded ) { lZ = 0; } else { lZ = pSize; data = data2D[ dataX ][ dataZ ]; } } } return data.GetHeight (x, z); } return 0.0f; } public void DeformHeight( Vector3 deformationPoint, float modificationHeight, TileInfo info) { long pSize = Options.Instance.PageSize; long pX = info.PageX; long pZ = info.PageZ; long wL = Options.Instance.World_Width; long hL = Options.Instance.World_Height; // adjust x and z to be local to page long x = (long) ((deformationPoint.x ) - ((pX - wL * 0.5f) * (pSize))); long z = (long) ((deformationPoint.z ) - ((pZ - hL * 0.5f) * (pSize))); Data2D data = data2D[ pX ][ pZ ]; if ( data.IsLoaded ) { float h = data.DeformHeight (x, z, modificationHeight); // If we're on a page edge, we must duplicate the change on the // neighbour page (if it has one...) if (x == 0 && pX != 0) { data = data2D[ pX - 1 ][ pZ ]; if ( data.IsLoaded ) { data.SetHeight (Options.Instance.PageSize - 1, z, h); } } if (x == pSize - 1 && pX < wL - 1) { data = data2D[ pX + 1 ][ pZ ]; if ( data.IsLoaded ) { data.SetHeight (0, z, h); } } if (z == 0 && pZ != 0) { data = data2D[ pX ][ pZ - 1 ]; if ( data.IsLoaded ) { data.SetHeight (x, Options.Instance.PageSize - 1, h); } } if (z == pSize - 1 && pZ < hL - 1) { data = data2D[ pX ][ pZ + 1]; if ( data.IsLoaded ) { data.SetHeight (x, 0, h); } } } } public bool AddNewHeight( Sphere newSphere ) { long x, z; // Calculate where is going to be placed the new height this.GetPageIndices( newSphere.Center, out x, out z); // TODO: DeScale and add the sphere to all the necessary pages //place it there return data2D[ x ][ z ].AddNewHeight(newSphere); } public bool RemoveNewHeight( Sphere oldSphere ) { long x, z; // Calculate where is going to be placed the new height GetPageIndices( oldSphere.Center, out x, out z); // TODO: DeScale and add the sphere to all the necessary pages //remove it return data2D[ x ][ z ].RemoveNewHeight(oldSphere); } //This function will return the max possible value of height base on the current 2D Data implementation public float GetMaxHeight( long x, long z) { Data2D data = data2D[ x ][ z ]; if ( data.IsLoaded ) { return data2D[ x ][ z ].MaxHeight; } return maxHeight; } public float GetMaxHeight() { return maxHeight; } /** Get the real world height at a particular position @remarks Method is used to get the terrain height at a world position based on x and z. This method just figures out what page the position is on and then asks the page node to do the dirty work of getting the height. @par the float returned is the real world height based on the scale of the world. If the height could not be determined then -1 is returned and this would only occur if the page was not preloaded or loaded @param x x world position @param z z world position */ public float GetRealWorldHeight( float x, float z) { // figure out which page the point is on Vector3 pos = new Vector3(x, 0, z); long dataX, dataZ; GetPageIndices(pos, out dataX, out dataZ); if ( data2D[dataX][dataZ].Dynamic ) { return GetRealPageHeight (x, z, dataX, dataZ, 0); } else { if ( !(data2D[ dataX ][ dataZ ].IsLoaded )) return 0.0f; // figure out which tile the point is on Tile.Tile t = PageManager.Instance.GetTile (pos, dataX, dataZ); long Lod = 0; if (t != null && t.IsLoaded ) Lod = t.Renderable.RenderLevel; return GetRealPageHeight (x, z, dataX, dataZ, Lod); } } public float GetRealWorldHeight( float x, float z, TileInfo info) { // figure out which page the point is on long dataX = info.PageX; long dataZ = info.PageZ; if ( ! (data2D[ dataX ][ dataZ ].IsLoaded )) return 0.0f; Tile.Tile t = PageManager.Instance.GetPage (dataX, dataZ ).GetTile (info.TileX, info.TileZ); long Lod = 0; if (t != null && t.IsLoaded ) Lod = t.Renderable.RenderLevel; return GetRealPageHeight (x, z, dataX, dataZ, Lod); } public float GetRealPageHeight ( float x, float z, long pageX, long pageZ, long Lod) { // scale position from world to page scale float localX = x / Options.Instance.Scale.x; float localZ = z / Options.Instance.Scale.z; // adjust x and z to be local to page long pSize = Options.Instance.PageSize - 1; localX -= (float)(pageX - Options.Instance.World_Width * 0.5f) * pSize; localZ -= (float)(pageZ - Options.Instance.World_Height * 0.5f) * pSize; // make sure x and z do not go outside the world boundaries if (localX < 0) localX = 0; else if (localX > pSize) localX = pSize; if (localZ < 0) localZ = 0; else if (localZ > pSize) localZ = pSize; // find the 4 vertices that surround the point // use LOD info to determine vertex spacing - this is passed into the method // determine vertices on left and right of point and top and bottom // don't access VBO since a big performance hit when only 4 vertices are needed int vertex_spread = 1 << (int)Lod; // find the vertex to the bottom left of the point int bottom_left_x = ((int)(localX / vertex_spread)) * vertex_spread; int bottom_left_z = ((int)(localZ / vertex_spread)) * vertex_spread; // find the 4 heights around the point Data2D data = data2D[ pageX ][ pageZ ]; float bottom_left_y = data.GetHeight(bottom_left_x , bottom_left_z); float bottom_right_y = data.GetHeight(bottom_left_x + vertex_spread, bottom_left_z); float top_left_y = data.GetHeight(bottom_left_x , bottom_left_z + vertex_spread); float top_right_y = data.GetHeight(bottom_left_x + vertex_spread, bottom_left_z + vertex_spread); float x_pct = (localX - (float)bottom_left_x) / (float)vertex_spread; float z_pct = (localZ - (float)bottom_left_z) / (float)vertex_spread; //bilinear interpolate to find the height. // figure out which 3 vertices are closest to the point and use those to form triangle plane for intersection // Triangle strip has diagonal going from bottom left to top right if ((x_pct - z_pct) >= 0) { return ( (bottom_left_y + (bottom_right_y - bottom_left_y ) * x_pct + (top_right_y - bottom_right_y) * z_pct)); } else { return ( (top_left_y + (top_right_y - top_left_y ) * x_pct + (bottom_left_y - top_left_y) * (1 - z_pct))); } } public ColorEx GetCoverageAt( long dataX, long dataZ, float x, float z ) { Data2D data = data2D[ dataX ][ dataZ ]; if ( data.IsLoaded ) { return data.GetCoverage(x, z); } return ColorEx.White; } public ColorEx GetBaseAt( long dataX, long dataZ, float x, float z ) { Data2D data = data2D[ dataX ][ dataZ ]; if ( data.IsLoaded ) { return data.GetBase(x, z); } return ColorEx.White; } public Vector3 GetNormalAt( long dataX, long dataZ, float x, float z) { Data2D data = data2D[ dataX ][ dataZ ]; if ( data.IsLoaded ) { #if !_LOADEDNORM return data.GetNormalAt (x, z); #else { // First General method : (9 adds and 6 muls + a normalization) // *---v3--* // | | | // | | | // v1--X--v2 // | | | // | | | // *---v4--* // // U = v2 - v1; // V = v4 - v3; // N = Cross(U, V); // N.normalise; // // BUT IN CASE OF A HEIGHTMAP : // // if you do some math by hand before you code, // you can see that N is immediately given by // Approximation (2 adds and a normalization) // // N = Vector3(z[x-1][y] - z[x+1][y], z[x][y-1] - z[x][y+1], 2); // N.normalise(); // // or even using SOBEL operator VERY accurate! // (14 adds and a normalization) // // N = Vector3 (z[x-1][y-1] + z[x-1][y] + z[x-1][y] + z[x-1][y+1] - z[x+1][y-1] - z[x+1][y] - z[x+1][y] - z[x+1][y+1], // z[x-1][y-1] + z[x][y-1] + z[x][y-1] + z[x+1][y-1] - z[x-1][y+1] - z[x][y+1] - z[x][y+1] - z[x+1][y+1], // 8); // N.normalize(); // Fast SOBEL filter Vector3 result = new Vector3 (this.GetHeightAtPage( dataX, dataZ, x - 1.0F, z ) - this.GetHeightAtPage( dataX, dataZ, x + 1.0F, z ), 2.0f, this.GetHeightAtPage( dataX, dataZ, x, z - 1.0F) - this.GetHeightAtPage( dataX, dataZ, x , z + 1.0F)); result.Normalize(); return result; } #endif } return Vector3.UnitY; } // JEFF /** Get the Page indices from a world position vector @remarks Method is used to find the Page indices using a world position vector. Beats having to iterate through the Page list to find a page at a particular position in the world. @param pos the world position vector. Only components x and z are used @param x result placed in reference to the x index of the page @param z result placed in reference to the z index of the page */ public void GetPageIndices( Vector3 pos, out long x, out long z) { long w = Options.Instance.World_Width; long h = Options.Instance.World_Height; x = (long)(pos.x / Options.Instance.Scale.x / (Options.Instance.PageSize - 1.0) + w * 0.5f); z = (long)(pos.z / Options.Instance.Scale.z / (Options.Instance.PageSize - 1.0) + h * 0.5f); // make sure indices are not negative or outside range of number of pages if (x >= w) { x = w - 1; } else if ( x < 0 ) { x = 0; } if (z >= h) { z = h - 1; } else if ( z < 0 ) { z = 0; } } public Data2D GetData2D ( long x, long z) { Data2D data = data2D[ x ][ z ]; return ( data.IsLoaded )? data: null; } } }
// // Log.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, 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 System; using Couchbase.Lite.Util; using System.Threading; using System.Diagnostics; namespace Couchbase.Lite.Util { /// <summary> /// Centralized logging facility. /// </summary> public static class Log { private static object logger = LoggerFactory.CreateLogger(); private static ILogger Logger { get { return (ILogger)logger; } } /// <summary> /// Sets the logger. /// </summary> /// <returns><c>true</c>, if Logger was set, <c>false</c> otherwise.</returns> /// <param name="customLogger">Custom logger.</param> public static bool SetLogger(ILogger customLogger) { var currentLogger = Logger; Interlocked.CompareExchange(ref logger, customLogger, currentLogger); return Logger == customLogger; } /// <summary> /// Sets up Couchbase Lite to use the default logger (an internal class), /// with the specified logging level /// </summary> /// <returns><c>true</c>, if the logger was changed, <c>false</c> otherwise.</returns> /// <param name="level">The levels to log</param> public static bool SetDefaultLoggerWithLevel(SourceLevels level) { return SetLogger(new CustomLogger(level)); } /// <summary>Send a VERBOSE message.</summary> /// <remarks>Send a VERBOSE message.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="msg">The message you would like logged.</param> [System.Diagnostics.Conditional("TRACE")] public static void V(string tag, string msg) { if (Logger != null) { Logger.V(tag, msg); } } /// <summary>Send a VERBOSE message and log the exception.</summary> /// <remarks>Send a VERBOSE message and log the exception.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="msg">The message you would like logged.</param> /// <param name="tr">An exception to log</param> [System.Diagnostics.Conditional("TRACE")] public static void V(string tag, string msg, Exception tr) { if (Logger != null) { Logger.V(tag, msg, tr); } } /// <summary>Send a VERBOSE message and log the exception.</summary> /// <remarks>Send a VERBOSE message and log the exception.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="format">The message you would like logged.</param> /// <param name="args">string format arguments</param> [System.Diagnostics.Conditional("TRACE")] public static void V(string tag, string format, params object[] args) { if (Logger != null) { Logger.V(tag, format, args); } } /// <summary>Send a DEBUG message.</summary> /// <remarks>Send a DEBUG message.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="msg">The message you would like logged.</param> [System.Diagnostics.Conditional("DEBUG")] public static void D(string tag, string msg) { if (Logger != null) { Logger.D(tag, msg); } } /// <summary>Send a DEBUG message and log the exception.</summary> /// <remarks>Send a DEBUG message and log the exception.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="msg">The message you would like logged.</param> /// <param name="tr">An exception to log</param> [System.Diagnostics.Conditional("DEBUG")] public static void D(string tag, string msg, Exception tr) { if (Logger != null) { Logger.D(tag, msg, tr); } } /// <summary>Send a DEBUG message and log the exception.</summary> /// <remarks>Send a DEBUG message and log the exception.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="format">The message you would like logged.</param> /// <param name="args">string format arguments</param> [System.Diagnostics.Conditional("DEBUG")] public static void D(string tag, string format, params object[] args) { if (Logger != null) { Logger.D(tag, format, args); } } /// <summary>Send an INFO message.</summary> /// <remarks>Send an INFO message.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="msg">The message you would like logged.</param> public static void I(string tag, string msg) { if (Logger != null) { Logger.I(tag, msg); } } /// <summary>Send a INFO message and log the exception.</summary> /// <remarks>Send a INFO message and log the exception.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="msg">The message you would like logged.</param> /// <param name="tr">An exception to log</param> public static void I(string tag, string msg, Exception tr) { if (Logger != null) { Logger.I(tag, msg, tr); } } /// <summary>Send a INFO message and log the exception.</summary> /// <remarks>Send a INFO message and log the exception.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="format">The message you would like logged.</param> /// <param name="args">string format arguments</param> public static void I(string tag, string format, params object[] args) { if (Logger != null) { Logger.I(tag, format, args); } } /// <summary>Send a WARN message.</summary> /// <remarks>Send a WARN message.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="msg">The message you would like logged.</param> public static void W(string tag, string msg) { if (Logger != null) { Logger.W(tag, msg); } } /// <summary>Send a WARN message.</summary> /// <remarks>Send a WARN message.</remarks> /// <param name="tag">Tag.</param> /// <param name="tr">Exception</param> public static void W(string tag, Exception tr) { if (Logger != null) { Logger.W(tag, tr); } } /// <summary>Send a WARN message and log the exception.</summary> /// <remarks>Send a WARN message and log the exception.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="msg">The message you would like logged.</param> /// <param name="tr">An exception to log</param> public static void W(string tag, string msg, Exception tr) { if (Logger != null) { Logger.W(tag, msg, tr); } } /// <summary>Send a WARN message and log the exception.</summary> /// <remarks>Send a WARN message and log the exception.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="format">The message you would like logged.</param> /// <param name="args">string format arguments</param> public static void W(string tag, string format, params object[] args) { if (Logger != null) { Logger.W(tag, format, args); } } /// <summary>Send an ERROR message.</summary> /// <remarks>Send an ERROR message.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="msg">The message you would like logged.</param> public static void E(string tag, string msg) { if (Logger != null) { Logger.E(tag, msg); } } /// <summary>Send a ERROR message and log the exception.</summary> /// <remarks>Send a ERROR message and log the exception.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="msg">The message you would like logged.</param> /// <param name="tr">An exception to log</param> public static void E(string tag, string msg, Exception tr) { if (Logger != null) { Logger.E(tag, msg, tr); } } /// <summary>Send a ERROR message and log the exception.</summary> /// <remarks>Send a ERROR message and log the exception.</remarks> /// <param name="tag"> /// Used to identify the source of a log message. It usually identifies /// the class or activity where the log call occurs. /// </param> /// <param name="format">The message you would like logged.</param> /// <param name="args">string format arguments</param> public static void E(string tag, string format, params object[] args) { if (Logger != null) { Logger.E(tag, format, args); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines { /// <summary> /// CA1716: Identifiers should not match keywords /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class IdentifiersShouldNotMatchKeywordsAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1716"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotMatchKeywordsTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMemberParameter = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotMatchKeywordsMessageMemberParameter), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMember = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotMatchKeywordsMessageMember), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageType = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotMatchKeywordsMessageType), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageNamespace = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotMatchKeywordsMessageNamespace), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotMatchKeywordsDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); // Properties common to all DiagnosticDescriptors for this rule: private static readonly string s_category = DiagnosticCategory.Naming; private const DiagnosticSeverity Severity = DiagnosticHelpers.DefaultDiagnosticSeverity; private const bool IsEnabledByDefault = true; private const string HelpLinkUri = "https://msdn.microsoft.com/en-us/library/ms182248.aspx"; private static readonly string[] s_customTags = new[] { WellKnownDiagnosticTags.Telemetry }; internal static DiagnosticDescriptor MemberParameterRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageMemberParameter, s_category, Severity, isEnabledByDefault: IsEnabledByDefault, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: s_customTags); internal static DiagnosticDescriptor MemberRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageMember, s_category, Severity, isEnabledByDefault: IsEnabledByDefault, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: s_customTags); internal static DiagnosticDescriptor TypeRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageType, s_category, Severity, isEnabledByDefault: IsEnabledByDefault, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: s_customTags); internal static DiagnosticDescriptor NamespaceRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageNamespace, s_category, Severity, isEnabledByDefault: IsEnabledByDefault, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: s_customTags); // Define the format in which this rule displays namespace names. The format is chosen to be // consistent with FxCop's display format for this rule. private static readonly SymbolDisplayFormat s_namespaceDisplayFormat = SymbolDisplayFormat.CSharpErrorMessageFormat // Turn off the EscapeKeywordIdentifiers flag (which is on by default), so that // a method named "@for" is displayed as "for" .WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.None); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(MemberParameterRule, MemberRule, TypeRule, NamespaceRule); public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); analysisContext.RegisterCompilationStartAction(compilationStartAnalysisContext => { var namespaceRuleAnalyzer = new NamespaceRuleAnalyzer(); compilationStartAnalysisContext.RegisterSymbolAction( symbolAnalysisContext => namespaceRuleAnalyzer.Analyze(symbolAnalysisContext), SymbolKind.NamedType); compilationStartAnalysisContext.RegisterSymbolAction(AnalyzeTypeRule, SymbolKind.NamedType); compilationStartAnalysisContext.RegisterSymbolAction(AnalyzeMemberRule, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property); compilationStartAnalysisContext.RegisterSymbolAction(AnalyzeMemberParameterRule, SymbolKind.Method); }); } private sealed class NamespaceRuleAnalyzer { private readonly ISet<string> _namespaceWithKeywordSet = new HashSet<string>(); private readonly object _lockGuard = new object(); public void Analyze(SymbolAnalysisContext context) { INamedTypeSymbol type = (INamedTypeSymbol)context.Symbol; // Don't complain about a namespace unless it contains at least one public type. if (type.GetResultantVisibility() != SymbolVisibility.Public) { return; } INamespaceSymbol containingNamespace = type.ContainingNamespace; if (containingNamespace.IsGlobalNamespace) { return; } string namespaceDisplayString = containingNamespace.ToDisplayString(s_namespaceDisplayFormat); IEnumerable<string> namespaceNameComponents = containingNamespace.ToDisplayParts(s_namespaceDisplayFormat) .Where(dp => dp.Kind == SymbolDisplayPartKind.NamespaceName) .Select(dp => dp.ToString()); foreach (string component in namespaceNameComponents) { if (IsKeyword(component, out string matchingKeyword)) { bool doReportDiagnostic; lock (_lockGuard) { string namespaceWithKeyword = namespaceDisplayString + "*" + matchingKeyword; doReportDiagnostic = _namespaceWithKeywordSet.Add(namespaceWithKeyword); } if (doReportDiagnostic) { // Don't report the diagnostic at a specific location. See dotnet/roslyn#8643. var diagnostic = Diagnostic.Create(NamespaceRule, Location.None, namespaceDisplayString, matchingKeyword); context.ReportDiagnostic(diagnostic); } } } } } private void AnalyzeTypeRule(SymbolAnalysisContext context) { INamedTypeSymbol type = (INamedTypeSymbol)context.Symbol; if (type.GetResultantVisibility() != SymbolVisibility.Public) { return; } if (IsKeyword(type.Name, out string matchingKeyword)) { context.ReportDiagnostic( type.CreateDiagnostic( TypeRule, type.FormatMemberName(), matchingKeyword)); } } private void AnalyzeMemberRule(SymbolAnalysisContext context) { ISymbol symbol = context.Symbol; if (symbol.GetResultantVisibility() != SymbolVisibility.Public) { return; } if (!IsKeyword(symbol.Name, out string matchingKeyword)) { return; } // IsAbstract returns true for both abstract class members and interface members. if (symbol.IsVirtual || symbol.IsAbstract) { context.ReportDiagnostic( symbol.CreateDiagnostic( MemberRule, symbol.FormatMemberName(), matchingKeyword)); } } private void AnalyzeMemberParameterRule(SymbolAnalysisContext context) { var method = (IMethodSymbol)context.Symbol; if (method.GetResultantVisibility() != SymbolVisibility.Public) { return; } // IsAbstract returns true for both abstract class members and interface members. if (!method.IsVirtual && !method.IsAbstract) { return; } foreach (IParameterSymbol parameter in method.Parameters) { if (IsKeyword(parameter.Name, out string matchingKeyword)) { context.ReportDiagnostic( parameter.CreateDiagnostic( MemberParameterRule, method.FormatMemberName(), parameter.Name, matchingKeyword)); } } } private static bool IsKeyword(string name, out string keyword) { if (s_caseSensitiveKeywords.TryGetValue(name, out keyword)) { return true; } return s_caseInsensitiveKeywords.TryGetKey(name, out keyword); } private static readonly ImmutableHashSet<string> s_caseSensitiveKeywords = new[] { // C# "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while", // Listed as a keywords in Microsoft.CodeAnalysis.CSharp.SyntaxKind, but // omitted, at least for now, for compatibility with FxCop: //"__arglist", //"__makeref", //"__reftype", //"__refvalue", //"stackalloc", // C++ "__abstract", "__alignof", "__asm", "__assume", "__based", "__box", "__builtin_alignof", "__cdecl", "__clrcall", "__compileBreak", "__CURSOR__", "__declspec", "__delegate", "__event", "__except", "__fastcall", "__feacp_av", "__feacpBreak", "__finally", "__forceinline", "__gc", "__has_assign", "__has_copy", "__has_finalizer", "__has_nothrow_assign", "__has_nothrow_copy", "__has_trivial_assign", "__has_trivial_constructor", "__has_trivial_copy", "__has_trivial_destructor", "__has_user_destructor", "__has_virtual_destructor", "__hook", "__identifier", "__if_exists", "__if_not_exists", "__inline", "__int128", "__int16", "__int32", "__int64", "__int8", "__interface", "__is_abstract", "__is_base_of", "__is_class", "__is_convertible_to", "__is_delegate", "__is_empty", "__is_enum", "__is_interface_class", "__is_pod", "__is_polymorphic", "__is_ref_array", "__is_ref_class", "__is_sealed", "__is_simple_value_class", "__is_union", "__is_value_class", "__leave", "__multiple_inheritance", "__newslot", "__nogc", "__nounwind", "__nvtordisp", "__offsetof", "__pin", "__pragma", "__property", "__ptr32", "__ptr64", "__raise", "__restrict", "__resume", "__sealed", "__single_inheritance", "__stdcall", "__super", "__thiscall", "__try", "__try_cast", "__typeof", "__unaligned", "__unhook", "__uuidof", "__value", "__virtual_inheritance", "__w64", "__wchar_t", "and", "and_eq", "asm", "auto", "bitand", "bitor", //"bool", //"break", //"case", //"catch", "cdecl", //"char", //"class", "compl", //"const", "const_cast", //"continue", //"default", "delete", //"do", //"double", "dynamic_cast", //"else", //"enum", //"explicit", "export", //"extern", //"false, //"float", //"for", "friend", "gcnew", "generic", //"goto", //"if", "inline", //"int", //"long", "mutable", //"namespace", //"new", "not", "not_eq", "nullptr", //"operator", "or", "or_eq", //"private", //"protected", //"public", "register", "reinterpret_cast", //"return", //"short", "signed", //"sizeof", //"static", "static_cast", //"struct", //"switch", "template", //"this", //"throw", //"true", //"try", "typedef", "typeid", "typename", "union", "unsigned", //"using", //"virtual", //"void", //"volatile", "wchar_t", //"while", "xor", "xor_eq" }.ToImmutableHashSet(StringComparer.Ordinal); private static readonly ImmutableDictionary<string, string> s_caseInsensitiveKeywords = new[] { "AddHandler", "AddressOf", "Alias", "And", "AndAlso", "As", "Boolean", "ByRef", "Byte", "ByVal", "Call", "Case", "Catch", "CBool", "CByte", "CChar", "CDate", "CDbl", "CDec", "Char", "CInt", "Class", "CLng", "CObj", "Const", "Continue", "CSByte", "CShort", "CSng", "CStr", "CType", "CUInt", "CULng", "CUShort", "Date", "Decimal", "Declare", "Default", "Delegate", "Dim", "DirectCast", "Do", "Double", "Each", "Else", "ElseIf", "End", "Enum", "Erase", "Error", "Event", "Exit", "False", "Finally", "For", "Friend", "Function", "Get", "GetType", "Global", "GoTo", "Handles", "If", "Implements", "Imports", "In", "Inherits", "Integer", "Interface", "Is", "IsNot", "Lib", "Like", "Long", "Loop", "Me", "Mod", "Module", "MustInherit", "MustOverride", "MyBase", "MyClass", "Namespace", "Narrowing", "New", "Next", "Not", "Nothing", "NotInheritable", "NotOverridable", "Object", "Of", "On", "Operator", "Option", "Optional", "Or", "OrElse", "Overloads", "Overridable", "Overrides", "ParamArray", "Partial", "Private", "Property", "Protected", "Public", "RaiseEvent", "ReadOnly", "ReDim", "REM", "RemoveHandler", "Resume", "Return", "SByte", "Select", "Set", "Shadows", "Shared", "Short", "Single", "Static", "Step", "Stop", "String", "Structure", "Sub", "SyncLock", "Then", "Throw", "To", "True", "Try", "TryCast", "TypeOf", "UInteger", "ULong", "UShort", "Using", "When", "While", "Widening", "With", "WithEvents", "WriteOnly", "Xor" // Listed as a keywords in Microsoft.CodeAnalysis.VisualBasic.SyntaxKind, but // omitted, at least for now, for compatibility with FxCop: //"Aggregate", //"All", //"Ansi", //"Ascending", //"Assembly", //"Async", //"Await", //"Auto", //"Binary", //"By", //"Compare", //"Custom", //"Descending", //"Disable", //"Distinct", //"Enable", //"EndIf", //"Equals", //"Explicit", //"ExternalChecksum", //"ExternalSource", //"From", //"GetXmlNamespace", //"Gosub", //"Group", //"Infer", //"Into", //"IsFalse", //"IsTrue", //"Iterator", //"Yield", //"Join", //"Key", //"Let", //"Mid", //"Off", //"Order", //"Out", //"Preserve", //"Reference", //"Region", //"Strict", //"Take", //"Text", //"Type", //"Unicode", //"Until", //"Warning", //"Variant", //"Wend", //"Where", //"Xml" }.ToImmutableDictionary(key => key, StringComparer.OrdinalIgnoreCase); } }
/* ==================================================================== 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 NPOI.POIFS.FileSystem { using System; using System.IO; using NPOI.Util; using System.Text; /** * Represents an Ole10Native record which is wrapped around certain binary * files being embedded in OLE2 documents. * * @author Rainer Schwarze */ public class Ole10Native { public static String OLE10_NATIVE = "\x0001Ole10Native"; protected static String ISO1 = "ISO-8859-1"; // (the fields as they appear in the raw record:) private int totalSize; // 4 bytes, total size of record not including this field private short flags1 = 2; // 2 bytes, unknown, mostly [02 00] private String label; // ASCIIZ, stored in this field without the terminating zero private String fileName; // ASCIIZ, stored in this field without the terminating zero private short flags2 = 0; // 2 bytes, unknown, mostly [00 00] private short unknown1 = 3; // see below private String command; // ASCIIZ, stored in this field without the terminating zero private byte[] dataBuffer; // varying size, the actual native data private short flags3 = 0; // some final flags? or zero terminators?, sometimes not there /** * the field encoding mode - merely a try-and-error guess ... **/ private enum EncodingMode { /** * the data is stored in parsed format - including label, command, etc. */ parsed, /** * the data is stored raw after the length field */ unparsed, /** * the data is stored raw after the length field and the flags1 field */ compact } private EncodingMode mode; /// <summary> /// Creates an instance of this class from an embedded OLE Object. The OLE Object is expected /// to include a stream &quot;{01}Ole10Native&quot; which Contains the actual /// data relevant for this class. /// </summary> /// <param name="poifs">poifs POI Filesystem object</param> /// <returns>Returns an instance of this class</returns> public static Ole10Native CreateFromEmbeddedOleObject(POIFSFileSystem poifs) { return CreateFromEmbeddedOleObject(poifs.Root); } /// <summary> /// Creates an instance of this class from an embedded OLE Object. The OLE Object is expected /// to include a stream &quot;{01}Ole10Native&quot; which contains the actual /// data relevant for this class. /// </summary> /// <param name="directory">directory POI Filesystem object</param> /// <returns>Returns an instance of this class</returns> public static Ole10Native CreateFromEmbeddedOleObject(DirectoryNode directory) { DocumentEntry nativeEntry = (DocumentEntry)directory.GetEntry(OLE10_NATIVE); byte[] data = new byte[nativeEntry.Size]; directory.CreateDocumentInputStream(nativeEntry).Read(data); return new Ole10Native(data, 0); } /** * Creates an instance and fills the fields based on ... the fields */ public Ole10Native(String label, String filename, String command, byte[] data) { Label=(label); FileName=(filename); Command=(command); DataBuffer=(data); mode = EncodingMode.parsed; } /** * Creates an instance and Fills the fields based on the data in the given buffer. * * @param data The buffer Containing the Ole10Native record * @param offset The start offset of the record in the buffer * @param plain as of POI 3.11 this parameter is ignored * @throws Ole10NativeException on invalid or unexcepted data format */ [Obsolete("parameter plain is ignored, use {@link #Ole10Native(byte[],int)}")] public Ole10Native(byte[] data, int offset, bool plain) : this(data, offset) { } /** * Creates an instance and Fills the fields based on the data in the given buffer. * * @param data The buffer Containing the Ole10Native record * @param offset The start offset of the record in the buffer * @throws Ole10NativeException on invalid or unexcepted data format */ public Ole10Native(byte[] data, int offset) { int ofs = offset; // current offset, Initialized to start if (data.Length < offset + 2) { throw new Ole10NativeException("data is too small"); } totalSize = LittleEndian.GetInt(data, ofs); ofs += LittleEndianConsts.INT_SIZE; mode = EncodingMode.unparsed; if (LittleEndian.GetShort(data, ofs) == 2) { // some files like equations don't have a valid filename, // but somehow encode the formula right away in the ole10 header if (char.IsControl((char)data[ofs + LittleEndianConsts.SHORT_SIZE])) { mode = EncodingMode.compact; } else { mode = EncodingMode.parsed; } } int dataSize = 0; switch (mode) { case EncodingMode.parsed: flags1 = LittleEndian.GetShort(data, ofs); ofs += LittleEndianConsts.SHORT_SIZE; int len = GetStringLength(data, ofs); label = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1); ofs += len; len = GetStringLength(data, ofs); fileName = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1); ofs += len; flags2 = LittleEndian.GetShort(data, ofs); ofs += LittleEndianConsts.SHORT_SIZE; unknown1 = LittleEndian.GetShort(data, ofs); ofs += LittleEndianConsts.SHORT_SIZE; len = LittleEndian.GetInt(data, ofs); ofs += LittleEndianConsts.INT_SIZE; command = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1); ofs += len; if (totalSize < ofs) { throw new Ole10NativeException("Invalid Ole10Native"); } dataSize = LittleEndian.GetInt(data, ofs); ofs += LittleEndianConsts.INT_SIZE; if (dataSize < 0 || totalSize - (ofs - LittleEndianConsts.INT_SIZE) < dataSize) { throw new Ole10NativeException("Invalid Ole10Native"); } break; case EncodingMode.compact: flags1 = LittleEndian.GetShort(data, ofs); ofs += LittleEndianConsts.SHORT_SIZE; dataSize = totalSize - LittleEndianConsts.SHORT_SIZE; break; case EncodingMode.unparsed: dataSize = totalSize; break; } dataBuffer = new byte[dataSize]; Array.Copy(data, ofs, dataBuffer, 0, dataSize); ofs += dataSize; } /* * Helper - determine length of zero terminated string (ASCIIZ). */ private static int GetStringLength(byte[] data, int ofs) { int len = 0; while (len + ofs < data.Length && data[ofs + len] != 0) { len++; } len++; return len; } /** * Returns the value of the totalSize field - the total length of the structure * is totalSize + 4 (value of this field + size of this field). * * @return the totalSize */ public int TotalSize { get { return totalSize; } } /** * Returns flags1 - currently unknown - usually 0x0002. * * @return the flags1 */ public short Flags1 { get { return flags1; } set { flags1 = value; } } /** * Returns the label field - usually the name of the file (without directory) but * probably may be any name specified during packaging/embedding the data. * * @return the label */ public String Label { get { return label; } set { label = value; } } /** * Returns the fileName field - usually the name of the file being embedded * including the full path. * * @return the fileName */ public String FileName { get { return fileName; } set { fileName = value; } } /** * Returns flags2 - currently unknown - mostly 0x0000. * * @return the flags2 */ public short Flags2 { get { return flags2; } set { flags2 = value; } } /** * Returns unknown1 field - currently unknown. * * @return the unknown1 */ public short Unknown1 { get { return unknown1; } set { unknown1 = value; } } /** * Returns the command field - usually the name of the file being embedded * including the full path, may be a command specified during embedding the file. * * @return the command */ public String Command { get { return command; } set { command = value; } } /** * Returns the size of the embedded file. If the size is 0 (zero), no data has been * embedded. To be sure, that no data has been embedded, check whether * {@link #getDataBuffer()} returns <code>null</code>. * * @return the dataSize */ public int DataSize { get{return dataBuffer.Length;} } /** * Returns the buffer Containing the embedded file's data, or <code>null</code> * if no data was embedded. Note that an embedding may provide information about * the data, but the actual data is not included. (So label, filename etc. are * available, but this method returns <code>null</code>.) * * @return the dataBuffer */ public byte[] DataBuffer { get{return dataBuffer;} set { dataBuffer = value; } } /** * Returns the flags3 - currently unknown. * * @return the flags3 */ public short Flags3 { get { return flags3; } set { flags3 = value; } } /** * Have the contents printer out into an OutputStream, used when writing a * file back out to disk (Normally, atom classes will keep their bytes * around, but non atom classes will just request the bytes from their * children, then chuck on their header and return) */ public void WriteOut(Stream out1) { byte[] intbuf = new byte[LittleEndianConsts.INT_SIZE]; byte[] shortbuf = new byte[LittleEndianConsts.SHORT_SIZE]; byte[] zerobuf = { 0, 0, 0, 0 }; LittleEndianOutputStream leosOut = new LittleEndianOutputStream(out1); switch (mode) { case EncodingMode.parsed: { MemoryStream bos = new MemoryStream(); LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); // total size, will be determined later .. leos.WriteShort(Flags1); leos.Write(Encoding.GetEncoding(ISO1).GetBytes(Label)); leos.WriteByte(0); leos.Write(Encoding.GetEncoding(ISO1).GetBytes(FileName)); leos.WriteByte(0); leos.WriteShort(Flags2); leos.WriteShort(Unknown1); leos.WriteInt(Command.Length + 1); leos.Write(Encoding.GetEncoding(ISO1).GetBytes(Command)); leos.WriteByte(0); leos.WriteInt(DataSize); leos.Write(DataBuffer); leos.WriteShort(Flags3); //leos.Close(); // satisfy compiler ... leosOut.WriteInt((int)bos.Length); // total size bos.WriteTo(out1); break; } case EncodingMode.compact: leosOut.WriteInt(DataSize + LittleEndianConsts.SHORT_SIZE); leosOut.WriteShort(Flags1); out1.Write(DataBuffer, 0, DataBuffer.Length); break; default: case EncodingMode.unparsed: leosOut.WriteInt(DataSize); out1.Write(DataBuffer, 0, DataBuffer.Length); break; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Collections.Generic; using System.Collections; using System.Globalization; using System.Net; using Xunit; using System.Threading; using System.DirectoryServices.Tests; using System.DirectoryServices.Protocols; namespace System.DirectoryServicesProtocols.Tests { public partial class DirectoryServicesProtocolsTests { internal static bool IsLdapConfigurationExist => LdapConfiguration.Configuration != null; internal static bool IsActiveDirectoryServer => IsLdapConfigurationExist && LdapConfiguration.Configuration.IsActiveDirectoryServer; [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestAddingOU() { using (LdapConnection connection = GetConnection()) { string ouName = "ProtocolsGroup1"; string dn = "ou=" + ouName; try { DeleteEntry(connection, dn); AddOrganizationalUnit(connection, dn); SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); } finally { DeleteEntry(connection, dn); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestDeleteOU() { using (LdapConnection connection = GetConnection()) { string ouName = "ProtocolsGroup2"; string dn = "ou=" + ouName; try { DeleteEntry(connection, dn); AddOrganizationalUnit(connection, dn); SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); DeleteEntry(connection, dn); sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.Null(sre); } finally { DeleteEntry(connection, dn); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestAddAndModifyAttribute() { using (LdapConnection connection = GetConnection()) { string ouName = "ProtocolsGroup3"; string dn = "ou=" + ouName; try { DeleteEntry(connection, dn); AddOrganizationalUnit(connection, dn); AddAttribute(connection, dn, "description", "Protocols Group 3"); SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); Assert.Equal("Protocols Group 3", (string) sre.Attributes["description"][0]); Assert.Throws<DirectoryOperationException>(() => AddAttribute(connection, dn, "description", "Protocols Group 3")); ModifyAttribute(connection, dn, "description", "Modified Protocols Group 3"); sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); Assert.Equal("Modified Protocols Group 3", (string) sre.Attributes["description"][0]); DeleteAttribute(connection, dn, "description"); sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); Assert.Null(sre.Attributes["description"]); } finally { DeleteEntry(connection, dn); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestNestedOUs() { using (LdapConnection connection = GetConnection()) { string ouLevel1Name = "ProtocolsGroup4-1"; string dnLevel1 = "ou=" + ouLevel1Name; string ouLevel2Name = "ProtocolsGroup4-2"; string dnLevel2 = "ou=" + ouLevel2Name+ "," + dnLevel1; DeleteEntry(connection, dnLevel2); DeleteEntry(connection, dnLevel1); try { AddOrganizationalUnit(connection, dnLevel1); SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouLevel1Name); Assert.NotNull(sre); AddOrganizationalUnit(connection, dnLevel2); sre = SearchOrganizationalUnit(connection, dnLevel1 + "," + LdapConfiguration.Configuration.Domain, ouLevel2Name); Assert.NotNull(sre); } finally { DeleteEntry(connection, dnLevel2); DeleteEntry(connection, dnLevel1); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestAddUser() { using (LdapConnection connection = GetConnection()) { string ouName = "ProtocolsGroup5"; string dn = "ou=" + ouName; string user1Dn = "cn=protocolUser1" + "," + dn; string user2Dn = "cn=protocolUser2" + "," + dn; DeleteEntry(connection, user1Dn); DeleteEntry(connection, user2Dn); DeleteEntry(connection, dn); try { AddOrganizationalUnit(connection, dn); SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); AddOrganizationalRole(connection, user1Dn); AddOrganizationalRole(connection, user2Dn); string usersRoot = dn + "," + LdapConfiguration.Configuration.Domain; sre = SearchUser(connection, usersRoot, "protocolUser1"); Assert.NotNull(sre); sre = SearchUser(connection, usersRoot, "protocolUser2"); Assert.NotNull(sre); DeleteEntry(connection, user1Dn); sre = SearchUser(connection, usersRoot, "protocolUser1"); Assert.Null(sre); DeleteEntry(connection, user2Dn); sre = SearchUser(connection, usersRoot, "protocolUser2"); Assert.Null(sre); DeleteEntry(connection, dn); sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.Null(sre); } finally { DeleteEntry(connection, user1Dn); DeleteEntry(connection, user2Dn); DeleteEntry(connection, dn); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestAddingMultipleAttributes() { using (LdapConnection connection = GetConnection()) { string ouName = "ProtocolsGroup6"; string dn = "ou=" + ouName; try { DeleteEntry(connection, dn); AddOrganizationalUnit(connection, dn); DirectoryAttributeModification mod1 = new DirectoryAttributeModification(); mod1.Operation = DirectoryAttributeOperation.Add; mod1.Name = "description"; mod1.Add("Description 5"); DirectoryAttributeModification mod2 = new DirectoryAttributeModification(); mod2.Operation = DirectoryAttributeOperation.Add; mod2.Name = "postalAddress"; mod2.Add("123 4th Ave NE, State, Country"); DirectoryAttributeModification[] mods = new DirectoryAttributeModification[2] { mod1, mod2 }; string fullDn = dn + "," + LdapConfiguration.Configuration.Domain; ModifyRequest modRequest = new ModifyRequest(fullDn, mods); ModifyResponse modResponse = (ModifyResponse) connection.SendRequest(modRequest); Assert.Equal(ResultCode.Success, modResponse.ResultCode); Assert.Throws<DirectoryOperationException>(() => (ModifyResponse) connection.SendRequest(modRequest)); SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); Assert.Equal("Description 5", (string) sre.Attributes["description"][0]); Assert.Throws<DirectoryOperationException>(() => AddAttribute(connection, dn, "description", "Description 5")); Assert.Equal("123 4th Ave NE, State, Country", (string) sre.Attributes["postalAddress"][0]); Assert.Throws<DirectoryOperationException>(() => AddAttribute(connection, dn, "postalAddress", "123 4th Ave NE, State, Country")); mod1 = new DirectoryAttributeModification(); mod1.Operation = DirectoryAttributeOperation.Replace; mod1.Name = "description"; mod1.Add("Modified Description 5"); mod2 = new DirectoryAttributeModification(); mod2.Operation = DirectoryAttributeOperation.Replace; mod2.Name = "postalAddress"; mod2.Add("689 5th Ave NE, State, Country"); mods = new DirectoryAttributeModification[2] { mod1, mod2 }; modRequest = new ModifyRequest(fullDn, mods); modResponse = (ModifyResponse) connection.SendRequest(modRequest); Assert.Equal(ResultCode.Success, modResponse.ResultCode); sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); Assert.Equal("Modified Description 5", (string) sre.Attributes["description"][0]); Assert.Throws<DirectoryOperationException>(() => AddAttribute(connection, dn, "description", "Modified Description 5")); Assert.Equal("689 5th Ave NE, State, Country", (string) sre.Attributes["postalAddress"][0]); Assert.Throws<DirectoryOperationException>(() => AddAttribute(connection, dn, "postalAddress", "689 5th Ave NE, State, Country")); mod1 = new DirectoryAttributeModification(); mod1.Operation = DirectoryAttributeOperation.Delete; mod1.Name = "description"; mod2 = new DirectoryAttributeModification(); mod2.Operation = DirectoryAttributeOperation.Delete; mod2.Name = "postalAddress"; mods = new DirectoryAttributeModification[2] { mod1, mod2 }; modRequest = new ModifyRequest(fullDn, mods); modResponse = (ModifyResponse) connection.SendRequest(modRequest); Assert.Equal(ResultCode.Success, modResponse.ResultCode); sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); Assert.Null(sre.Attributes["description"]); Assert.Null(sre.Attributes["postalAddress"]); } finally { DeleteEntry(connection, dn); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestMoveAndRenameUser() { using (LdapConnection connection = GetConnection()) { string ouName1 = "ProtocolsGroup7.1"; string dn1 = "ou=" + ouName1; string ouName2 = "ProtocolsGroup7.2"; string dn2 = "ou=" + ouName2; string userDn1 = "cn=protocolUser7.1" + "," + dn1; string userDn2 = "cn=protocolUser7.2" + "," + dn2; DeleteEntry(connection, userDn1); DeleteEntry(connection, userDn2); DeleteEntry(connection, dn1); DeleteEntry(connection, dn2); try { AddOrganizationalUnit(connection, dn1); SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName1); Assert.NotNull(sre); AddOrganizationalUnit(connection, dn2); sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName2); Assert.NotNull(sre); AddOrganizationalRole(connection, userDn1); string user1Root = dn1 + "," + LdapConfiguration.Configuration.Domain; string user2Root = dn2 + "," + LdapConfiguration.Configuration.Domain; sre = SearchUser(connection, user1Root, "protocolUser7.1"); Assert.NotNull(sre); ModifyDNRequest modDnRequest = new ModifyDNRequest( userDn1 + "," + LdapConfiguration.Configuration.Domain, dn2 + "," + LdapConfiguration.Configuration.Domain, "cn=protocolUser7.2"); ModifyDNResponse modDnResponse = (ModifyDNResponse) connection.SendRequest(modDnRequest); Assert.Equal(ResultCode.Success, modDnResponse.ResultCode); sre = SearchUser(connection, user1Root, "protocolUser7.1"); Assert.Null(sre); sre = SearchUser(connection, user2Root, "protocolUser7.2"); Assert.NotNull(sre); } finally { DeleteEntry(connection, userDn1); DeleteEntry(connection, userDn2); DeleteEntry(connection, dn1); DeleteEntry(connection, dn2); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestAsyncSearch() { using (LdapConnection connection = GetConnection()) { string ouName = "ProtocolsGroup9"; string dn = "ou=" + ouName; try { for (int i=0; i<20; i++) { DeleteEntry(connection, "ou=ProtocolsSubGroup9." + i + "," + dn); } DeleteEntry(connection, dn); AddOrganizationalUnit(connection, dn); SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); for (int i=0; i<20; i++) { AddOrganizationalUnit(connection, "ou=ProtocolsSubGroup9." + i + "," + dn); } string filter = "(objectClass=organizationalUnit)"; SearchRequest searchRequest = new SearchRequest( dn + "," + LdapConfiguration.Configuration.Domain, filter, SearchScope.OneLevel, null); ASyncOperationState state = new ASyncOperationState(connection); IAsyncResult asyncResult = connection.BeginSendRequest( searchRequest, PartialResultProcessing.ReturnPartialResultsAndNotifyCallback, RunAsyncSearch, state); asyncResult.AsyncWaitHandle.WaitOne(); Assert.True(state.Exception == null, state.Exception == null ? "" : state.Exception.ToString()); } finally { for (int i=0; i<20; i++) { DeleteEntry(connection, "ou=ProtocolsSubGroup9." + i + "," + dn); } DeleteEntry(connection, dn); } } } private static void RunAsyncSearch(IAsyncResult asyncResult) { ASyncOperationState state = (ASyncOperationState) asyncResult.AsyncState; try { if (!asyncResult.IsCompleted) { PartialResultsCollection partialResult = null; partialResult = state.Connection.GetPartialResults(asyncResult); if (partialResult != null) { for (int i = 0; i < partialResult.Count; i++) { if (partialResult[i] is SearchResultEntry) { Assert.Contains("Group9", ((SearchResultEntry)partialResult[i]).DistinguishedName); } } } } else { SearchResponse response = (SearchResponse) state.Connection.EndSendRequest(asyncResult); if (response != null) { foreach (SearchResultEntry entry in response.Entries) { Assert.Contains("Group9", entry.DistinguishedName); } } } } catch (Exception e) { state.Exception = e; } } [ConditionalFact(nameof(IsActiveDirectoryServer))] public void TestPageRequests() { using (LdapConnection connection = GetConnection()) { string ouName = "ProtocolsGroup8"; string dn = "ou=" + ouName; try { for (int i=0; i<20; i++) { DeleteEntry(connection, "ou=ProtocolsSubGroup8." + i + "," + dn); } DeleteEntry(connection, dn); AddOrganizationalUnit(connection, dn); SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); for (int i=0; i<20; i++) { AddOrganizationalUnit(connection, "ou=ProtocolsSubGroup8." + i + "," + dn); } string filter = "(objectClass=*)"; SearchRequest searchRequest = new SearchRequest( dn + "," + LdapConfiguration.Configuration.Domain, filter, SearchScope.Subtree, null); PageResultRequestControl pageRequest = new PageResultRequestControl(5); searchRequest.Controls.Add(pageRequest); SearchOptionsControl searchOptions = new SearchOptionsControl(SearchOption.DomainScope); searchRequest.Controls.Add(searchOptions); while (true) { SearchResponse searchResponse = (SearchResponse) connection.SendRequest(searchRequest); Assert.Equal(1, searchResponse.Controls.Length); Assert.True(searchResponse.Controls[0] is PageResultResponseControl); PageResultResponseControl pageResponse = (PageResultResponseControl) searchResponse.Controls[0]; if (pageResponse.Cookie.Length == 0) break; pageRequest.Cookie = pageResponse.Cookie; } } finally { for (int i=0; i<20; i++) { DeleteEntry(connection, "ou=ProtocolsSubGroup8." + i + "," + dn); } DeleteEntry(connection, dn); } } } private void DeleteAttribute(LdapConnection connection, string entryDn, string attributeName) { string dn = entryDn + "," + LdapConfiguration.Configuration.Domain; ModifyRequest modifyRequest = new ModifyRequest(dn, DirectoryAttributeOperation.Delete, attributeName); ModifyResponse modifyResponse = (ModifyResponse) connection.SendRequest(modifyRequest); Assert.Equal(ResultCode.Success, modifyResponse.ResultCode); } private void ModifyAttribute(LdapConnection connection, string entryDn, string attributeName, string attributeValue) { string dn = entryDn + "," + LdapConfiguration.Configuration.Domain; ModifyRequest modifyRequest = new ModifyRequest(dn, DirectoryAttributeOperation.Replace, attributeName, attributeValue); ModifyResponse modifyResponse = (ModifyResponse) connection.SendRequest(modifyRequest); Assert.Equal(ResultCode.Success, modifyResponse.ResultCode); } private void AddAttribute(LdapConnection connection, string entryDn, string attributeName, string attributeValue) { string dn = entryDn + "," + LdapConfiguration.Configuration.Domain; ModifyRequest modifyRequest = new ModifyRequest(dn, DirectoryAttributeOperation.Add, attributeName, attributeValue); ModifyResponse modifyResponse = (ModifyResponse) connection.SendRequest(modifyRequest); Assert.Equal(ResultCode.Success, modifyResponse.ResultCode); } private void AddOrganizationalUnit(LdapConnection connection, string entryDn) { string dn = entryDn + "," + LdapConfiguration.Configuration.Domain; AddRequest addRequest = new AddRequest(dn, "organizationalUnit"); AddResponse addResponse = (AddResponse) connection.SendRequest(addRequest); Assert.Equal(ResultCode.Success, addResponse.ResultCode); } private void AddOrganizationalRole(LdapConnection connection, string entryDn) { string dn = entryDn + "," + LdapConfiguration.Configuration.Domain; AddRequest addRequest = new AddRequest(dn, "organizationalRole"); AddResponse addResponse = (AddResponse) connection.SendRequest(addRequest); Assert.Equal(ResultCode.Success, addResponse.ResultCode); } private void DeleteEntry(LdapConnection connection, string entryDn) { try { string dn = entryDn + "," + LdapConfiguration.Configuration.Domain; DeleteRequest delRequest = new DeleteRequest(dn); DeleteResponse delResponse = (DeleteResponse) connection.SendRequest(delRequest); Assert.Equal(ResultCode.Success, delResponse.ResultCode); } catch { // ignore the exception as we use this for clean up } } private SearchResultEntry SearchOrganizationalUnit(LdapConnection connection, string rootDn, string ouName) { string filter = $"(&(objectClass=organizationalUnit)(ou={ouName}))"; SearchRequest searchRequest = new SearchRequest(rootDn, filter, SearchScope.OneLevel, null); SearchResponse searchResponse = (SearchResponse) connection.SendRequest(searchRequest); if (searchResponse.Entries.Count > 0) return searchResponse.Entries[0]; return null; } private SearchResultEntry SearchUser(LdapConnection connection, string rootDn, string userName) { string filter = $"(&(objectClass=organizationalRole)(cn={userName}))"; SearchRequest searchRequest = new SearchRequest(rootDn, filter, SearchScope.OneLevel, null); SearchResponse searchResponse = (SearchResponse) connection.SendRequest(searchRequest); if (searchResponse.Entries.Count > 0) return searchResponse.Entries[0]; return null; } private LdapConnection GetConnection() { LdapDirectoryIdentifier directoryIdentifier = string.IsNullOrEmpty(LdapConfiguration.Configuration.Port) ? new LdapDirectoryIdentifier(LdapConfiguration.Configuration.ServerName, true, false) : new LdapDirectoryIdentifier(LdapConfiguration.Configuration.ServerName, int.Parse(LdapConfiguration.Configuration.Port, NumberStyles.None, CultureInfo.InvariantCulture), true, false); NetworkCredential credential = new NetworkCredential(LdapConfiguration.Configuration.UserName, LdapConfiguration.Configuration.Password); LdapConnection connection = new LdapConnection(directoryIdentifier, credential) { AuthType = AuthType.Basic }; connection.Bind(); connection.SessionOptions.ProtocolVersion = 3; connection.Timeout = new TimeSpan(0, 3, 0); return connection; } } internal class ASyncOperationState { internal ASyncOperationState(LdapConnection connection) { Connection = connection; } internal LdapConnection Connection { get; set; } internal Exception Exception { get; set; } } }
namespace Macabresoft.Macabre2D.Framework; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using Macabresoft.Core; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; /// <summary> /// Represents a camera into the game world. /// </summary> [Display(Name = "Camera")] public sealed class Camera : Entity, ICamera { private readonly ResettableLazy<BoundingArea> _boundingArea; [DataMember(Name = "Shader")] private readonly ShaderReference _shaderReference = new(); private Layers _layersToRender = ~Layers.None; private int _renderOrder; private SamplerStateType _samplerStateType = SamplerStateType.PointClamp; private bool _snapToPixels; private float _viewHeight = 10f; /// <summary> /// Initializes a new instance of the <see cref="Camera" /> class. /// </summary> public Camera() : base() { this._boundingArea = new ResettableLazy<BoundingArea>(this.CreateBoundingArea); } /// <inheritdoc /> public BoundingArea BoundingArea => this._boundingArea.Value; /// <inheritdoc /> [DataMember(Name = "Offset Settings")] public OffsetSettings OffsetSettings { get; } = new(Vector2.Zero, PixelOffsetType.Center); /// <inheritdoc /> [DataMember(Name = "Layers to Render")] public Layers LayersToRender { get => this._layersToRender; set => this.Set(ref this._layersToRender, value); } /// <inheritdoc /> [DataMember] public int RenderOrder { get => this._renderOrder; set => this.Set(ref this._renderOrder, value, true); } /// <inheritdoc /> public SamplerState SamplerState { get; private set; } = SamplerState.PointClamp; /// <summary> /// Gets or sets the type of the sampler state. /// </summary> /// <value>The type of the sampler state.</value> [DataMember(Name = "Sampler State")] public SamplerStateType SamplerStateType { get => this._samplerStateType; set { this.Set(ref this._samplerStateType, value); this.SamplerState = this._samplerStateType.ToSamplerState(); this.RaisePropertyChanged(nameof(this.SamplerState)); } } /// <summary> /// Gets or sets a value indicating whether this camera should snap to the pixel ratio /// defined in <see cref="IGameSettings" />. /// </summary> /// <value><c>true</c> if this should snap to pixels; otherwise, <c>false</c>.</value> [DataMember(Name = "Snap to Pixels")] public bool SnapToPixels { get => this._snapToPixels; set { if (this.Set(ref this._snapToPixels, value)) { this.ResetBoundingArea(); } } } /// <summary> /// Gets the height of the view. /// </summary> /// <value>The height of the view.</value> [DataMember(Name = "View Height")] public float ViewHeight { get => this._viewHeight; set { // This is kind of an arbitrary value, but imagine the chaos if we allowed the // camera to reach 0. if (value <= 0.1f) { value = 0.1f; } if (this.Set(ref this._viewHeight, value)) { this.ResetBoundingArea(); } } } /// <inheritdoc /> public Vector2 ConvertPointFromScreenSpaceToWorldSpace(Point point) { var result = Vector2.Zero; if (this.OffsetSettings.Size.Y != 0f) { var ratio = this.ViewHeight / this.OffsetSettings.Size.Y; var pointVector = point.ToVector2(); var vectorPosition = new Vector2(pointVector.X + this.OffsetSettings.Offset.X, -pointVector.Y + this.OffsetSettings.Size.Y + this.OffsetSettings.Offset.Y) * ratio; result = this.GetWorldTransform(vectorPosition).Position; } return result; } /// <inheritdoc /> public Matrix GetViewMatrix() { var settings = this.Scene.Game.Project.Settings; var pixelsPerUnit = settings.PixelsPerUnit; var zoom = 1f / settings.GetPixelAgnosticRatio(this.ViewHeight, (int)this.OffsetSettings.Size.Y); var worldTransform = this.Transform; return Matrix.CreateTranslation(new Vector3(-worldTransform.Position.ToPixelSnappedValue(this.Scene.Game.Project.Settings) * pixelsPerUnit, 0f)) * Matrix.CreateScale(zoom, -zoom, 0f) * Matrix.CreateTranslation(new Vector3(-this.OffsetSettings.Offset.X, this.OffsetSettings.Size.Y + this.OffsetSettings.Offset.Y, 0f)); } /// <summary> /// Gets the width of the view. /// </summary> /// <returns>The width of the view.</returns> public float GetViewWidth() { var size = this.OffsetSettings.Size; var ratio = size.Y != 0 ? this.ViewHeight / this.OffsetSettings.Size.Y : 0f; return size.X * ratio; } /// <inheritdoc /> public override void Initialize(IScene scene, IEntity parent) { base.Initialize(scene, parent); this.OffsetSettings.Initialize(this.CreateSize); this.ResetBoundingArea(); this.SamplerState = this._samplerStateType.ToSamplerState(); this.Scene.Game.ViewportSizeChanged += this.Game_ViewportSizeChanged; this.OffsetSettings.PropertyChanged += this.OffsetSettings_PropertyChanged; this.Scene.Assets.ResolveAsset<ShaderAsset, Effect>(this._shaderReference); } /// <inheritdoc /> public void Render(FrameTime frameTime, SpriteBatch spriteBatch, IEnumerable<IRenderableEntity> entities) { spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.AlphaBlend, this.SamplerState, null, RasterizerState.CullNone, this._shaderReference.Asset?.Content, this.GetViewMatrix()); foreach (var entity in entities) { entity.Render(frameTime, this.BoundingArea); } spriteBatch.End(); } /// <summary> /// Zooms to a world position. /// </summary> /// <param name="worldPosition">The world position.</param> /// <param name="zoomAmount">The zoom amount.</param> public void ZoomTo(Vector2 worldPosition, float zoomAmount) { var originalCameraPosition = this.Transform.Position; var originalDistanceFromCamera = worldPosition - originalCameraPosition; var originalViewHeight = this.ViewHeight; this.ViewHeight -= zoomAmount; var viewHeightRatio = this.ViewHeight / originalViewHeight; this.SetWorldPosition(worldPosition - originalDistanceFromCamera * viewHeightRatio); } /// <summary> /// Zooms to a screen position. /// </summary> /// <param name="screenPosition">The screen position.</param> /// <param name="zoomAmount">The zoom amount.</param> public void ZoomTo(Point screenPosition, float zoomAmount) { var worldPosition = this.ConvertPointFromScreenSpaceToWorldSpace(screenPosition); this.ZoomTo(worldPosition, zoomAmount); } /// <summary> /// Zooms to a boundable entity, fitting it into frame. /// </summary> /// <param name="boundable">The boundable.</param> public void ZoomTo(IBoundable boundable) { var area = boundable.BoundingArea; var difference = area.Maximum - area.Minimum; var origin = area.Minimum + difference * 0.5f; this.SetWorldPosition(origin); this.ViewHeight = difference.Y; var currentViewWidth = this.GetViewWidth(); if (currentViewWidth < difference.X) { this.ViewHeight *= difference.X / currentViewWidth; } } /// <inheritdoc /> protected override void OnPropertyChanged(object? sender, PropertyChangedEventArgs e) { base.OnPropertyChanged(sender, e); if (e.PropertyName == nameof(IEntity.Transform)) { this.ResetBoundingArea(); } } private BoundingArea CreateBoundingArea() { var ratio = this.ViewHeight / this.OffsetSettings.Size.Y; var width = this.OffsetSettings.Size.X * ratio; var height = this.OffsetSettings.Size.Y * ratio; var offset = this.OffsetSettings.Offset * ratio; var points = new List<Vector2> { this.GetWorldTransform(offset).Position, this.GetWorldTransform(offset + new Vector2(width, 0f)).Position, this.GetWorldTransform(offset + new Vector2(width, height)).Position, this.GetWorldTransform(offset + new Vector2(0f, height)).Position }; var minimumX = points.Min(x => x.X); var minimumY = points.Min(x => x.Y); var maximumX = points.Max(x => x.X); var maximumY = points.Max(x => x.Y); if (this.SnapToPixels) { minimumX = minimumX.ToPixelSnappedValue(this.Scene.Game.Project.Settings); minimumY = minimumY.ToPixelSnappedValue(this.Scene.Game.Project.Settings); maximumX = maximumX.ToPixelSnappedValue(this.Scene.Game.Project.Settings); maximumY = maximumY.ToPixelSnappedValue(this.Scene.Game.Project.Settings); } return new BoundingArea(new Vector2(minimumX, minimumY), new Vector2(maximumX, maximumY)); } private Vector2 CreateSize() { return new Vector2(this.Scene.Game.ViewportSize.X, this.Scene.Game.ViewportSize.Y); } private void Game_ViewportSizeChanged(object? sender, Point e) { this.OffsetSettings.InvalidateSize(); this.ResetBoundingArea(); } private void OffsetSettings_PropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(this.OffsetSettings.Offset)) { this.ResetBoundingArea(); } } private void ResetBoundingArea() { this._boundingArea.Reset(); } }
using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using GongSolutions.Shell.Interop; namespace GongSolutions.Shell { /// <summary> /// Provides support for displaying the context menu of a shell item. /// </summary> /// /// <remarks> /// <para> /// Use this class to display a context menu for a shell item, either /// as a popup menu, or as a main menu. /// </para> /// /// <para> /// To display a popup menu, simply call <see cref="ShowContextMenu"/> /// with the parent control and the position at which the menu should /// be shown. /// </para> /// /// <para> /// To display a shell context menu in a Form's main menu, call the /// <see cref="Populate"/> method to populate the menu. In addition, /// you must intercept a number of special messages that will be sent /// to the menu's parent form. To do this, you must override /// <see cref="Form.WndProc"/> like so: /// </para> /// /// <code> /// protected override void WndProc(ref Message m) { /// if ((m_ContextMenu == null) || (!m_ContextMenu.HandleMenuMessage(ref m))) { /// base.WndProc(ref m); /// } /// } /// </code> /// /// <para> /// Where m_ContextMenu is the <see cref="ShellContextMenu"/> being shown. /// </para> /// /// Standard menu commands can also be invoked from this class, for /// example <see cref="InvokeDelete"/> and <see cref="InvokeRename"/>. /// </remarks> public class ShellContextMenu { /// <summary> /// Initialises a new instance of the <see cref="ShellContextMenu"/> /// class. /// </summary> /// /// <param name="item"> /// The item to which the context menu should refer. /// </param> public ShellContextMenu(ShellItem item) { Initialize(new ShellItem[] { item }); } /// <summary> /// Initialises a new instance of the <see cref="ShellContextMenu"/> /// class. /// </summary> /// /// <param name="items"> /// The items to which the context menu should refer. /// </param> public ShellContextMenu(ShellItem[] items) { Initialize(items); } /// <summary> /// Handles context menu messages when the <see cref="ShellContextMenu"/> /// is displayed on a Form's main menu bar. /// </summary> /// /// <remarks> /// <para> /// To display a shell context menu in a Form's main menu, call the /// <see cref="Populate"/> method to populate the menu with the shell /// item's menu items. In addition, you must intercept a number of /// special messages that will be sent to the menu's parent form. To /// do this, you must override <see cref="Form.WndProc"/> like so: /// </para> /// /// <code> /// protected override void WndProc(ref Message m) { /// if ((m_ContextMenu == null) || (!m_ContextMenu.HandleMenuMessage(ref m))) { /// base.WndProc(ref m); /// } /// } /// </code> /// /// <para> /// Where m_ContextMenu is the <see cref="ShellContextMenu"/> being shown. /// </para> /// </remarks> /// /// <param name="m"> /// The message to handle. /// </param> /// /// <returns> /// <see langword="true"/> if the message was a Shell Context Menu /// message, <see langword="false"/> if not. If the method returns false, /// then the message should be passed down to the base class's /// <see cref="Form.WndProc"/> method. /// </returns> public bool HandleMenuMessage(ref Message m) { if ((m.Msg == (int)MSG.WM_COMMAND) && ((int)m.WParam >= m_CmdFirst)) { InvokeCommand((int)m.WParam - m_CmdFirst); return true; } else { if (m_ComInterface3 != null) { IntPtr result; if (m_ComInterface3.HandleMenuMsg2(m.Msg, m.WParam, m.LParam, out result) == HResult.S_OK) { m.Result = result; return true; } } else if (m_ComInterface2 != null) { if (m_ComInterface2.HandleMenuMsg(m.Msg, m.WParam, m.LParam) == HResult.S_OK) { m.Result = IntPtr.Zero; return true; } } } return false; } /// <summary> /// Invokes the Copy command on the shell item(s). /// </summary> public void InvokeCopy() { InvokeVerb("copy"); } /// <summary> /// Invokes the Copy command on the shell item(s). /// </summary> public void InvokeCut() { InvokeVerb("cut"); } /// <summary> /// Invokes the Delete command on the shell item(s). /// </summary> public void InvokeDelete() { try { InvokeVerb("delete"); } catch (COMException e) { // Ignore the exception raised when the user cancels // a delete operation. if (e.ErrorCode != unchecked((int)0x800704C7) && e.ErrorCode != unchecked((int)0x80270000)) { throw; } } } /// <summary> /// Invokes the Paste command on the shell item(s). /// </summary> public void InvokePaste() { InvokeVerb("paste"); } /// <summary> /// Invokes the Rename command on the shell item. /// </summary> public void InvokeRename() { InvokeVerb("rename"); } /// <summary> /// Invokes the specified verb on the shell item(s). /// </summary> public void InvokeVerb(string verb) { CMINVOKECOMMANDINFO invoke = new CMINVOKECOMMANDINFO(); invoke.cbSize = Marshal.SizeOf(invoke); invoke.lpVerb = verb; m_ComInterface.InvokeCommand(ref invoke); } /// <summary> /// Populates a <see cref="Menu"/> with the context menu items for /// a shell item. /// </summary> /// /// <remarks> /// If this method is being used to populate a Form's main menu /// then you need to call <see cref="HandleMenuMessage"/> in the /// Form's message handler. /// </remarks> /// /// <param name="menu"> /// The menu to populate. /// </param> public void Populate(Menu menu) { RemoveShellMenuItems(menu); m_ComInterface.QueryContextMenu(menu.Handle, 0, m_CmdFirst, int.MaxValue, CMF.EXPLORE); } /// <summary> /// Shows a context menu for a shell item. /// </summary> /// /// <param name="control"> /// The parent control. /// </param> /// /// <param name="pos"> /// The position on <paramref name="control"/> that the menu /// should be displayed at. /// </param> public void ShowContextMenu(Point pos) { using (ContextMenu menu = new ContextMenu()) { //pos = control.PointToScreen(pos); Populate(menu); int command = User32.TrackPopupMenuEx(menu.Handle, TPM.TPM_RETURNCMD, pos.X, pos.Y, m_MessageWindow.Handle, IntPtr.Zero); if (command > 0) { InvokeCommand(command - m_CmdFirst); } } } /// <summary> /// Gets the underlying COM <see cref="IContextMenu"/> interface. /// </summary> public IContextMenu ComInterface { get { return m_ComInterface; } set { m_ComInterface = value; } } void Initialize(ShellItem[] items) { IntPtr[] pidls = new IntPtr[items.Length]; ShellItem parent = null; IntPtr result; for (int n = 0; n < items.Length; ++n) { pidls[n] = Shell32.ILFindLastID(items[n].Pidl); if (parent == null) { if (items[n] == ShellItem.Desktop) { parent = ShellItem.Desktop; } else { parent = items[n].Parent; } } else { if (items[n].Parent != parent) { throw new Exception("All shell items must have the same parent"); } } } parent.GetIShellFolder().GetUIObjectOf(IntPtr.Zero, (uint)pidls.Length, pidls, typeof(IContextMenu).GUID, 0, out result); m_ComInterface = (IContextMenu) Marshal.GetTypedObjectForIUnknown(result, typeof(IContextMenu)); m_ComInterface2 = m_ComInterface as IContextMenu2; m_ComInterface3 = m_ComInterface as IContextMenu3; m_MessageWindow = new MessageWindow(this); } void InvokeCommand(int index) { const int SW_SHOWNORMAL = 1; CMINVOKECOMMANDINFO_ByIndex invoke = new CMINVOKECOMMANDINFO_ByIndex(); invoke.cbSize = Marshal.SizeOf(invoke); invoke.iVerb = index; invoke.nShow = SW_SHOWNORMAL; m_ComInterface2.InvokeCommand(ref invoke); } void TagManagedMenuItems(Menu menu, int tag) { MENUINFO info = new MENUINFO(); info.cbSize = (UInt32)Marshal.SizeOf(info); info.fMask = MIM.MIM_MENUDATA; info.dwMenuData = (UIntPtr)tag; foreach (MenuItem item in menu.MenuItems) { User32.SetMenuInfo(item.Handle, ref info); } } void RemoveShellMenuItems(Menu menu) { const int tag = 0xAB; List<int> remove = new List<int>(); int count = User32.GetMenuItemCount(menu.Handle); MENUINFO menuInfo = new MENUINFO(); MENUITEMINFO itemInfo = new MENUITEMINFO(); menuInfo.cbSize = (UInt32)Marshal.SizeOf(menuInfo); menuInfo.fMask = MIM.MIM_MENUDATA; itemInfo.cbSize = (UInt32)Marshal.SizeOf(itemInfo); itemInfo.fMask = MIIM.MIIM_ID | MIIM.MIIM_SUBMENU; // First, tag the managed menu items with an arbitary // value (0xAB). TagManagedMenuItems(menu, tag); for (int n = 0; n < count; ++n) { User32.GetMenuItemInfo(menu.Handle, n, true, ref itemInfo); if (itemInfo.hSubMenu == IntPtr.Zero) { // If the item has no submenu we can't get the tag, so // check its ID to determine if it was added by the shell. if (itemInfo.wID >= m_CmdFirst) remove.Add(n); } else { User32.GetMenuInfo(itemInfo.hSubMenu, ref menuInfo); if ((int)menuInfo.dwMenuData != tag) remove.Add(n); } } // Remove the unmanaged menu items. remove.Reverse(); foreach (int position in remove) { User32.DeleteMenu(menu.Handle, position, MF.MF_BYPOSITION); } } class MessageWindow : Control { public MessageWindow(ShellContextMenu parent) { m_Parent = parent; } protected override void WndProc(ref Message m) { if (!m_Parent.HandleMenuMessage(ref m)) { base.WndProc(ref m); } } ShellContextMenu m_Parent; } MessageWindow m_MessageWindow; IContextMenu m_ComInterface; IContextMenu2 m_ComInterface2; IContextMenu3 m_ComInterface3; const int m_CmdFirst = 0x8000; } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using OpenMetaverse; namespace OpenSim.Region.ClientStack.LindenUDP { /// <summary> /// Special collection that is optimized for tracking unacknowledged packets /// </summary> public sealed class UnackedPacketCollection { /// <summary> /// Holds the actual unacked packet data, sorted by sequence number /// </summary> private readonly Dictionary<uint, OutgoingPacket> m_packets = new Dictionary<uint, OutgoingPacket>(); /// <summary> /// Holds information about pending acknowledgements /// </summary> private readonly LocklessQueue<PendingAck> m_pendingAcknowledgements = new LocklessQueue<PendingAck>(); /// <summary> /// Holds packets that need to be added to the unacknowledged list /// </summary> private readonly LocklessQueue<OutgoingPacket> m_pendingAdds = new LocklessQueue<OutgoingPacket>(); /// <summary> /// Holds information about pending removals /// </summary> private readonly LocklessQueue<uint> m_pendingRemoves = new LocklessQueue<uint>(); /// <summary> /// Add an unacked packet to the collection /// </summary> /// <param name = "packet">Packet that is awaiting acknowledgement</param> /// <returns>True if the packet was successfully added, false if the /// packet already existed in the collection</returns> /// <remarks> /// This does not immediately add the ACK to the collection, /// it only queues it so it can be added in a thread-safe way later /// </remarks> public void Add(OutgoingPacket packet) { m_pendingAdds.Enqueue(packet); } /// <summary> /// Marks a packet as acknowledged /// This method is used when an acknowledgement is received from the network for a previously /// sent packet. Effects of removal this way are to update unacked byte count, adjust RTT /// and increase throttle to the coresponding client. /// </summary> /// <param name = "sequenceNumber">Sequence number of the packet to /// acknowledge</param> /// <param name = "currentTime">Current value of Environment.TickCount</param> /// <param name="fromResend"></param> /// <remarks> /// This does not immediately acknowledge the packet, it only /// queues the ack so it can be handled in a thread-safe way later /// </remarks> public void Acknowledge(uint sequenceNumber, int currentTime, bool fromResend) { m_pendingAcknowledgements.Enqueue(new PendingAck(sequenceNumber, currentTime, fromResend)); } /// <summary> /// Marks a packet as no longer needing acknowledgement without a received acknowledgement. /// This method is called when a packet expires and we no longer need an acknowledgement. /// When some reliable packet types expire, they are handled in a way other than simply /// resending them. The only effect of removal this way is to update unacked byte count. /// </summary> /// <param name = "sequenceNumber">Sequence number of the packet to /// acknowledge</param> /// <remarks> /// The does not immediately remove the packet, it only queues the removal /// so it can be handled in a thread safe way later /// </remarks> public void Remove(uint sequenceNumber) { m_pendingRemoves.Enqueue(sequenceNumber); } /// <summary> /// Returns a list of all of the packets with a TickCount older than /// the specified timeout /// </summary> /// <param name = "timeoutMS">Number of ticks (milliseconds) before a /// packet is considered expired</param> /// <returns>A list of all expired packets according to the given /// expiration timeout</returns> /// <remarks> /// This function is not thread safe, and cannot be called /// multiple times concurrently /// </remarks> public List<OutgoingPacket> GetExpiredPackets(int timeoutMS) { ProcessQueues(); List<OutgoingPacket> expiredPackets = null; //Note:This is never used int expiredPacketsBytes = 0; if (m_packets.Count > 0) { int now = Environment.TickCount & Int32.MaxValue; int i = 0; #if (!ISWIN) foreach (OutgoingPacket packet in m_packets.Values) { if (packet.TickCount != 0) { if (now - packet.TickCount >= timeoutMS) { if (expiredPackets == null) expiredPackets = new List<OutgoingPacket>(); // The TickCount will be set to the current time when the packet // is actually sent out again packet.TickCount = 0; expiredPackets.Add(packet); expiredPacketsBytes += packet.Buffer.DataLength; if (i++ > 50) // limit number of packets loop break; } } } #else foreach (OutgoingPacket packet in m_packets.Values.Where(packet => packet.TickCount != 0).Where(packet => now - packet.TickCount >= timeoutMS)) { if (expiredPackets == null) expiredPackets = new List<OutgoingPacket>(); // The TickCount will be set to the current time when the packet // is actually sent out again packet.TickCount = 0; expiredPackets.Add(packet); expiredPacketsBytes += packet.Buffer.DataLength; if (i++ > 50) // limit number of packets loop break; } #endif } if (expiredPackets != null && expiredPackets.Count > 0) { // As with other network applications, assume that an expired packet is // an indication of some network problem, slow transmission expiredPackets[0].Client.SlowDownSend(); } return expiredPackets; } private void ProcessQueues() { // Process all the pending adds if (m_pendingAdds != null) { OutgoingPacket pendingAdd; while (m_pendingAdds.TryDequeue(out pendingAdd)) { if (pendingAdd != null && m_packets != null) { m_packets[pendingAdd.SequenceNumber] = pendingAdd; } } } // Process all the pending removes, including updating statistics and round-trip times PendingAck pendingAcknowledgement; while (m_pendingAcknowledgements.TryDequeue(out pendingAcknowledgement)) { OutgoingPacket ackedPacket; if (m_packets != null && m_packets.TryGetValue(pendingAcknowledgement.SequenceNumber, out ackedPacket)) { if (ackedPacket != null) { m_packets.Remove(pendingAcknowledgement.SequenceNumber); // Update stats Interlocked.Add(ref ackedPacket.Client.UnackedBytes, -ackedPacket.Buffer.DataLength); if (!pendingAcknowledgement.FromResend) { // Calculate the round-trip time for this packet and its ACK int rtt = pendingAcknowledgement.RemoveTime - ackedPacket.TickCount; if (rtt > 0) ackedPacket.Client.UpdateRoundTrip(rtt); } } } } uint pendingRemove; while (m_pendingRemoves.TryDequeue(out pendingRemove)) { OutgoingPacket removedPacket; if (m_packets != null && m_packets.TryGetValue(pendingRemove, out removedPacket)) { if (removedPacket != null) { m_packets.Remove(pendingRemove); // Update stats Interlocked.Add(ref removedPacket.Client.UnackedBytes, -removedPacket.Buffer.DataLength); removedPacket.Destroy(3); } } } } #region Nested type: PendingAck /// <summary> /// Holds information about a pending acknowledgement /// </summary> private struct PendingAck { /// <summary> /// Whether or not this acknowledgement was attached to a /// resent packet. If so, round-trip time will not be calculated /// </summary> public readonly bool FromResend; /// <summary> /// Environment.TickCount value when the remove was queued. /// This is used to update round-trip times for packets /// </summary> public readonly int RemoveTime; /// <summary> /// Sequence number of the packet to remove /// </summary> public readonly uint SequenceNumber; public PendingAck(uint sequenceNumber, int currentTime, bool fromResend) { SequenceNumber = sequenceNumber; RemoveTime = currentTime; FromResend = fromResend; } } #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.Specialized; using System.Net.Mail; using System.Text; namespace System.Net.Mime { // Typed Content-Type header // // We parse the type during construction and set. // null and string.empty will throw for construction,set and mediatype/subtype // constructors set isPersisted to false. isPersisted needs to be tracked seperately // than isChanged because isChanged only determines if the cached value should be used. // isPersisted tracks if the object has been persisted. However, obviously if isChanged is true // the object isn't persisted. // If any subcomponents are changed, isChanged is set to true and isPersisted is false // ToString caches the value until a isChanged is true, then it recomputes the full value. public class ContentType { private readonly TrackingStringDictionary _parameters = new TrackingStringDictionary(); private string _mediaType; private string _subType; private bool _isChanged; private string _type; private bool _isPersisted; /// <summary> /// Default content type - can be used if the Content-Type header /// is not defined in the message headers. /// </summary> internal const string Default = "application/octet-stream"; public ContentType() : this(Default) { } /// <summary> /// ctor. /// </summary> /// <param name="fieldValue">Unparsed value of the Content-Type header.</param> public ContentType(string contentType) { if (contentType == null) { throw new ArgumentNullException(nameof(contentType)); } if (contentType == string.Empty) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(contentType)), nameof(contentType)); } _isChanged = true; _type = contentType; ParseValue(); } public string Boundary { get { return Parameters["boundary"]; } set { if (value == null || value == string.Empty) { Parameters.Remove("boundary"); } else { Parameters["boundary"] = value; } } } public string CharSet { get { return Parameters["charset"]; } set { if (value == null || value == string.Empty) { Parameters.Remove("charset"); } else { Parameters["charset"] = value; } } } /// <summary> /// Gets the media type. /// </summary> public string MediaType { get { return _mediaType + "/" + _subType; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value == string.Empty) { throw new ArgumentException(SR.net_emptystringset, nameof(value)); } int offset = 0; _mediaType = MailBnfHelper.ReadToken(value, ref offset, null); if (_mediaType.Length == 0 || offset >= value.Length || value[offset++] != '/') throw new FormatException(SR.MediaTypeInvalid); _subType = MailBnfHelper.ReadToken(value, ref offset, null); if (_subType.Length == 0 || offset < value.Length) { throw new FormatException(SR.MediaTypeInvalid); } _isChanged = true; _isPersisted = false; } } public string Name { get { string value = Parameters["name"]; Encoding nameEncoding = MimeBasePart.DecodeEncoding(value); if (nameEncoding != null) { value = MimeBasePart.DecodeHeaderValue(value); } return value; } set { if (value == null || value == string.Empty) { Parameters.Remove("name"); } else { Parameters["name"] = value; } } } public StringDictionary Parameters => _parameters; internal void Set(string contentType, HeaderCollection headers) { _type = contentType; ParseValue(); headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType), ToString()); _isPersisted = true; } internal void PersistIfNeeded(HeaderCollection headers, bool forcePersist) { if (IsChanged || !_isPersisted || forcePersist) { headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType), ToString()); _isPersisted = true; } } internal bool IsChanged => _isChanged || _parameters != null && _parameters.IsChanged; public override string ToString() { if (_type == null || IsChanged) { _type = Encode(false); // Legacy wire-safe format _isChanged = false; _parameters.IsChanged = false; _isPersisted = false; } return _type; } internal string Encode(bool allowUnicode) { var builder = new StringBuilder(); builder.Append(_mediaType); // Must not have unicode, already validated builder.Append('/'); builder.Append(_subType); // Must not have unicode, already validated // Validate and encode unicode where required foreach (string key in Parameters.Keys) { builder.Append("; "); EncodeToBuffer(key, builder, allowUnicode); builder.Append('='); EncodeToBuffer(_parameters[key], builder, allowUnicode); } return builder.ToString(); } private static void EncodeToBuffer(string value, StringBuilder builder, bool allowUnicode) { Encoding encoding = MimeBasePart.DecodeEncoding(value); if (encoding != null) // Manually encoded elsewhere, pass through { builder.Append('\"').Append(value).Append('"'); } else if ((allowUnicode && !MailBnfHelper.HasCROrLF(value)) // Unicode without CL or LF's || MimeBasePart.IsAscii(value, false)) // Ascii { MailBnfHelper.GetTokenOrQuotedString(value, builder, allowUnicode); } else { // MIME Encoding required encoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet); builder.Append('"').Append(MimeBasePart.EncodeHeaderValue(value, encoding, MimeBasePart.ShouldUseBase64Encoding(encoding))).Append('"'); } } public override bool Equals(object rparam) => rparam == null ? false : string.Equals(ToString(), rparam.ToString(), StringComparison.OrdinalIgnoreCase); public override int GetHashCode() => ToString().ToLowerInvariant().GetHashCode(); // Helper methods. private void ParseValue() { int offset = 0; Exception exception = null; try { _mediaType = MailBnfHelper.ReadToken(_type, ref offset, null); if (_mediaType == null || _mediaType.Length == 0 || offset >= _type.Length || _type[offset++] != '/') { exception = new FormatException(SR.ContentTypeInvalid); } if (exception == null) { _subType = MailBnfHelper.ReadToken(_type, ref offset, null); if (_subType == null || _subType.Length == 0) { exception = new FormatException(SR.ContentTypeInvalid); } } if (exception == null) { while (MailBnfHelper.SkipCFWS(_type, ref offset)) { if (_type[offset++] != ';') { exception = new FormatException(SR.ContentTypeInvalid); break; } if (!MailBnfHelper.SkipCFWS(_type, ref offset)) { break; } string paramAttribute = MailBnfHelper.ReadParameterAttribute(_type, ref offset, null); if (paramAttribute == null || paramAttribute.Length == 0) { exception = new FormatException(SR.ContentTypeInvalid); break; } string paramValue; if (offset >= _type.Length || _type[offset++] != '=') { exception = new FormatException(SR.ContentTypeInvalid); break; } if (!MailBnfHelper.SkipCFWS(_type, ref offset)) { exception = new FormatException(SR.ContentTypeInvalid); break; } paramValue = _type[offset] == '"' ? MailBnfHelper.ReadQuotedString(_type, ref offset, null) : MailBnfHelper.ReadToken(_type, ref offset, null); if (paramValue == null) { exception = new FormatException(SR.ContentTypeInvalid); break; } _parameters.Add(paramAttribute, paramValue); } } _parameters.IsChanged = false; } catch (FormatException) { throw new FormatException(SR.ContentTypeInvalid); } if (exception != null) { throw new FormatException(SR.ContentTypeInvalid); } } } }
/* * Copyright 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using ZXing.Common; using ZXing.Common.ReedSolomon; namespace ZXing.Aztec.Internal { /// <summary> /// The main class which implements Aztec Code decoding -- as opposed to locating and extracting /// the Aztec Code from an image. /// </summary> /// <author>David Olivier</author> public sealed class Decoder { private enum Table { UPPER, LOWER, MIXED, DIGIT, PUNCT, BINARY } private static readonly String[] UPPER_TABLE = { "CTRL_PS", " ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "CTRL_LL", "CTRL_ML", "CTRL_DL", "CTRL_BS" }; private static readonly String[] LOWER_TABLE = { "CTRL_PS", " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "CTRL_US", "CTRL_ML", "CTRL_DL", "CTRL_BS" }; private static readonly String[] MIXED_TABLE = { "CTRL_PS", " ", "\x1", "\x2", "\x3", "\x4", "\x5", "\x6", "\x7", "\b", "\t", "\n", "\xD", "\f", "\r", "\x21", "\x22", "\x23", "\x24", "\x25", "@", "\\", "^", "_", "`", "|", "~", "\xB1", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS" }; private static readonly String[] PUNCT_TABLE = { "", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL" }; private static readonly String[] DIGIT_TABLE = { "CTRL_PS", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", "CTRL_UL", "CTRL_US" }; private static readonly IDictionary<Table, String[]> codeTables = new Dictionary<Table, String[]> { {Table.UPPER, UPPER_TABLE}, {Table.LOWER, LOWER_TABLE}, {Table.MIXED, MIXED_TABLE}, {Table.PUNCT, PUNCT_TABLE}, {Table.DIGIT, DIGIT_TABLE}, {Table.BINARY, null} }; private static readonly IDictionary<char, Table> codeTableMap = new Dictionary<char, Table> { {'U', Table.UPPER}, {'L', Table.LOWER}, {'M', Table.MIXED}, {'P', Table.PUNCT}, {'D', Table.DIGIT}, {'B', Table.BINARY} }; private AztecDetectorResult ddata; /// <summary> /// Decodes the specified detector result. /// </summary> /// <param name="detectorResult">The detector result.</param> /// <returns></returns> public DecoderResult decode(AztecDetectorResult detectorResult) { ddata = detectorResult; BitMatrix matrix = detectorResult.Bits; bool[] rawbits = extractBits(matrix); if (rawbits == null) return null; bool[] correctedBits = correctBits(rawbits); if (correctedBits == null) return null; String result = getEncodedData(correctedBits); if (result == null) return null; return new DecoderResult(null, result, null, null); } /// <summary> /// This method is used for testing the high-level encoder /// </summary> /// <param name="correctedBits"></param> /// <returns></returns> public static String highLevelDecode(bool[] correctedBits) { return getEncodedData(correctedBits); } /// <summary> /// Gets the string encoded in the aztec code bits /// </summary> /// <param name="correctedBits">The corrected bits.</param> /// <returns>the decoded string</returns> private static String getEncodedData(bool[] correctedBits) { var endIndex = correctedBits.Length; var latchTable = Table.UPPER; // table most recently latched to var shiftTable = Table.UPPER; // table to use for the next read var strTable = UPPER_TABLE; var result = new StringBuilder(20); var index = 0; while (index < endIndex) { if (shiftTable == Table.BINARY) { if (endIndex - index < 5) { break; } int length = readCode(correctedBits, index, 5); index += 5; if (length == 0) { if (endIndex - index < 11) { break; } length = readCode(correctedBits, index, 11) + 31; index += 11; } for (int charCount = 0; charCount < length; charCount++) { if (endIndex - index < 8) { index = endIndex; // Force outer loop to exit break; } int code = readCode(correctedBits, index, 8); result.Append((char) code); index += 8; } // Go back to whatever mode we had been in shiftTable = latchTable; strTable = codeTables[shiftTable]; } else { int size = shiftTable == Table.DIGIT ? 4 : 5; if (endIndex - index < size) { break; } int code = readCode(correctedBits, index, size); index += size; String str = getCharacter(strTable, code); if (str.StartsWith("CTRL_")) { // Table changes shiftTable = getTable(str[5]); strTable = codeTables[shiftTable]; if (str[6] == 'L') { latchTable = shiftTable; } } else { result.Append(str); // Go back to whatever mode we had been in shiftTable = latchTable; strTable = codeTables[shiftTable]; } } } return result.ToString(); } /// <summary> /// gets the table corresponding to the char passed /// </summary> /// <param name="t">The t.</param> /// <returns></returns> private static Table getTable(char t) { if (!codeTableMap.ContainsKey(t)) return codeTableMap['U']; return codeTableMap[t]; } /// <summary> /// Gets the character (or string) corresponding to the passed code in the given table /// </summary> /// <param name="table">the table used</param> /// <param name="code">the code of the character</param> /// <returns></returns> private static String getCharacter(String[] table, int code) { return table[code]; } /// <summary> ///Performs RS error correction on an array of bits. /// </summary> /// <param name="rawbits">The rawbits.</param> /// <returns>the corrected array</returns> private bool[] correctBits(bool[] rawbits) { GenericGF gf; int codewordSize; if (ddata.NbLayers <= 2) { codewordSize = 6; gf = GenericGF.AZTEC_DATA_6; } else if (ddata.NbLayers <= 8) { codewordSize = 8; gf = GenericGF.AZTEC_DATA_8; } else if (ddata.NbLayers <= 22) { codewordSize = 10; gf = GenericGF.AZTEC_DATA_10; } else { codewordSize = 12; gf = GenericGF.AZTEC_DATA_12; } int numDataCodewords = ddata.NbDatablocks; int numCodewords = rawbits.Length/codewordSize; if (numCodewords < numDataCodewords) return null; int offset = rawbits.Length % codewordSize; int numECCodewords = numCodewords - numDataCodewords; int[] dataWords = new int[numCodewords]; for (int i = 0; i < numCodewords; i++, offset += codewordSize) { dataWords[i] = readCode(rawbits, offset, codewordSize); } var rsDecoder = new ReedSolomonDecoder(gf); if (!rsDecoder.decode(dataWords, numECCodewords)) return null; // Now perform the unstuffing operation. // First, count how many bits are going to be thrown out as stuffing int mask = (1 << codewordSize) - 1; int stuffedBits = 0; for (int i = 0; i < numDataCodewords; i++) { int dataWord = dataWords[i]; if (dataWord == 0 || dataWord == mask) { return null; } else if (dataWord == 1 || dataWord == mask - 1) { stuffedBits++; } } // Now, actually unpack the bits and remove the stuffing bool[] correctedBits = new bool[numDataCodewords*codewordSize - stuffedBits]; int index = 0; for (int i = 0; i < numDataCodewords; i++) { int dataWord = dataWords[i]; if (dataWord == 1 || dataWord == mask - 1) { // next codewordSize-1 bits are all zeros or all ones SupportClass.Fill(correctedBits, index, index + codewordSize - 1, dataWord > 1); index += codewordSize - 1; } else { for (int bit = codewordSize - 1; bit >= 0; --bit) { correctedBits[index++] = (dataWord & (1 << bit)) != 0; } } } if (index != correctedBits.Length) return null; return correctedBits; } /// <summary> /// Gets the array of bits from an Aztec Code matrix /// </summary> /// <param name="matrix">The matrix.</param> /// <returns>the array of bits</returns> private bool[] extractBits(BitMatrix matrix) { bool compact = ddata.Compact; int layers = ddata.NbLayers; int baseMatrixSize = compact ? 11 + layers*4 : 14 + layers*4; // not including alignment lines int[] alignmentMap = new int[baseMatrixSize]; bool[] rawbits = new bool[totalBitsInLayer(layers, compact)]; if (compact) { for (int i = 0; i < alignmentMap.Length; i++) { alignmentMap[i] = i; } } else { int matrixSize = baseMatrixSize + 1 + 2*((baseMatrixSize/2 - 1)/15); int origCenter = baseMatrixSize/2; int center = matrixSize/2; for (int i = 0; i < origCenter; i++) { int newOffset = i + i/15; alignmentMap[origCenter - i - 1] = center - newOffset - 1; alignmentMap[origCenter + i] = center + newOffset + 1; } } for (int i = 0, rowOffset = 0; i < layers; i++) { int rowSize = compact ? (layers - i)*4 + 9 : (layers - i)*4 + 12; // The top-left most point of this layer is <low, low> (not including alignment lines) int low = i*2; // The bottom-right most point of this layer is <high, high> (not including alignment lines) int high = baseMatrixSize - 1 - low; // We pull bits from the two 2 x rowSize columns and two rowSize x 2 rows for (int j = 0; j < rowSize; j++) { int columnOffset = j*2; for (int k = 0; k < 2; k++) { // left column rawbits[rowOffset + columnOffset + k] = matrix[alignmentMap[low + k], alignmentMap[low + j]]; // bottom row rawbits[rowOffset + 2*rowSize + columnOffset + k] = matrix[alignmentMap[low + j], alignmentMap[high - k]]; // right column rawbits[rowOffset + 4*rowSize + columnOffset + k] = matrix[alignmentMap[high - k], alignmentMap[high - j]]; // top row rawbits[rowOffset + 6*rowSize + columnOffset + k] = matrix[alignmentMap[high - j], alignmentMap[low + k]]; } } rowOffset += rowSize*8; } return rawbits; } /// <summary> /// Reads a code of given length and at given index in an array of bits /// </summary> /// <param name="rawbits">The rawbits.</param> /// <param name="startIndex">The start index.</param> /// <param name="length">The length.</param> /// <returns></returns> private static int readCode(bool[] rawbits, int startIndex, int length) { int res = 0; for (int i = startIndex; i < startIndex + length; i++) { res <<= 1; if (rawbits[i]) { res++; } } return res; } private static int totalBitsInLayer(int layers, bool compact) { return ((compact ? 88 : 112) + 16*layers)*layers; } } }
// // System.Security.Cryptography.SHA512Managed.cs // // Authors: // Dan Lewis (dihlewis@yahoo.co.uk) // Sebastien Pouliot (sebastien@ximian.com) // // (C) 2002 // Implementation translated from Bouncy Castle JCE (http://www.bouncycastle.org/) // See bouncycastle.txt for license. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Runtime.InteropServices; namespace System.Security.Cryptography { internal class SHA512Managed : SHA512 { private byte[] xBuf; private int xBufOff; private ulong byteCount1; private ulong byteCount2; private ulong H1, H2, H3, H4, H5, H6, H7, H8; private ulong[] W; private int wOff; public SHA512Managed() { xBuf = new byte[8]; W = new ulong[80]; Initialize(false); // limited initialization } private void Initialize(bool reuse) { // SHA-512 initial hash value // The first 64 bits of the fractional parts of the square roots // of the first eight prime numbers H1 = 0x6a09e667f3bcc908L; H2 = 0xbb67ae8584caa73bL; H3 = 0x3c6ef372fe94f82bL; H4 = 0xa54ff53a5f1d36f1L; H5 = 0x510e527fade682d1L; H6 = 0x9b05688c2b3e6c1fL; H7 = 0x1f83d9abfb41bd6bL; H8 = 0x5be0cd19137e2179L; if (reuse) { byteCount1 = 0; byteCount2 = 0; xBufOff = 0; for (int i = 0; i < xBuf.Length; i++) xBuf[i] = 0; wOff = 0; for (int i = 0; i != W.Length; i++) W[i] = 0; } } public override void Initialize() { Initialize(true); // reuse instance } // protected protected override void HashCore(byte[] rgb, int ibStart, int cbSize) { // fill the current word while ((xBufOff != 0) && (cbSize > 0)) { update(rgb[ibStart]); ibStart++; cbSize--; } // process whole words. while (cbSize > xBuf.Length) { processWord(rgb, ibStart); ibStart += xBuf.Length; cbSize -= xBuf.Length; byteCount1 += (ulong)xBuf.Length; } // load in the remainder. while (cbSize > 0) { update(rgb[ibStart]); ibStart++; cbSize--; } } protected override byte[] HashFinal() { adjustByteCounts(); ulong lowBitLength = byteCount1 << 3; ulong hiBitLength = byteCount2; // add the pad bytes. update(128); while (xBufOff != 0) update(0); processLength(lowBitLength, hiBitLength); processBlock(); byte[] output = new byte[64]; unpackWord(H1, output, 0); unpackWord(H2, output, 8); unpackWord(H3, output, 16); unpackWord(H4, output, 24); unpackWord(H5, output, 32); unpackWord(H6, output, 40); unpackWord(H7, output, 48); unpackWord(H8, output, 56); Initialize(); return output; } private void update(byte input) { xBuf[xBufOff++] = input; if (xBufOff == xBuf.Length) { processWord(xBuf, 0); xBufOff = 0; } byteCount1++; } private void processWord(byte[] input, int inOff) { W[wOff++] = ((ulong)input[inOff] << 56) | ((ulong)input[inOff + 1] << 48) | ((ulong)input[inOff + 2] << 40) | ((ulong)input[inOff + 3] << 32) | ((ulong)input[inOff + 4] << 24) | ((ulong)input[inOff + 5] << 16) | ((ulong)input[inOff + 6] << 8) | ((ulong)input[inOff + 7]); if (wOff == 16) processBlock(); } private void unpackWord(ulong word, byte[] output, int outOff) { output[outOff] = (byte)(word >> 56); output[outOff + 1] = (byte)(word >> 48); output[outOff + 2] = (byte)(word >> 40); output[outOff + 3] = (byte)(word >> 32); output[outOff + 4] = (byte)(word >> 24); output[outOff + 5] = (byte)(word >> 16); output[outOff + 6] = (byte)(word >> 8); output[outOff + 7] = (byte)word; } // adjust the byte counts so that byteCount2 represents the // upper long (less 3 bits) word of the byte count. private void adjustByteCounts() { if (byteCount1 > 0x1fffffffffffffffL) { byteCount2 += (byteCount1 >> 61); byteCount1 &= 0x1fffffffffffffffL; } } private void processLength(ulong lowW, ulong hiW) { if (wOff > 14) processBlock(); W[14] = hiW; W[15] = lowW; } private void processBlock() { adjustByteCounts(); // expand 16 word block into 80 word blocks. for (int t = 16; t <= 79; t++) W[t] = Sigma1(W[t - 2]) + W[t - 7] + Sigma0(W[t - 15]) + W[t - 16]; // set up working variables. ulong a = H1; ulong b = H2; ulong c = H3; ulong d = H4; ulong e = H5; ulong f = H6; ulong g = H7; ulong h = H8; for (int t = 0; t <= 79; t++) { ulong T1 = h + Sum1(e) + Ch(e, f, g) + K2[t] + W[t]; ulong T2 = Sum0(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // reset the offset and clean out the word buffer. wOff = 0; for (int i = 0; i != W.Length; i++) W[i] = 0; } private ulong rotateRight(ulong x, int n) { return (x >> n) | (x << (64 - n)); } /* SHA-512 and SHA-512 functions (as for SHA-256 but for longs) */ private ulong Ch(ulong x, ulong y, ulong z) { return ((x & y) ^ ((~x) & z)); } private ulong Maj(ulong x, ulong y, ulong z) { return ((x & y) ^ (x & z) ^ (y & z)); } private ulong Sum0(ulong x) { return rotateRight(x, 28) ^ rotateRight(x, 34) ^ rotateRight(x, 39); } private ulong Sum1(ulong x) { return rotateRight(x, 14) ^ rotateRight(x, 18) ^ rotateRight(x, 41); } private ulong Sigma0(ulong x) { return rotateRight(x, 1) ^ rotateRight(x, 8) ^ (x >> 7); } private ulong Sigma1(ulong x) { return rotateRight(x, 19) ^ rotateRight(x, 61) ^ (x >> 6); } // SHA-384 and SHA-512 Constants // Represent the first 64 bits of the fractional parts of the // cube roots of the first sixty-four prime numbers public readonly static ulong[] K2 = { 0x428a2f98d728ae22L, 0x7137449123ef65cdL, 0xb5c0fbcfec4d3b2fL, 0xe9b5dba58189dbbcL, 0x3956c25bf348b538L, 0x59f111f1b605d019L, 0x923f82a4af194f9bL, 0xab1c5ed5da6d8118L, 0xd807aa98a3030242L, 0x12835b0145706fbeL, 0x243185be4ee4b28cL, 0x550c7dc3d5ffb4e2L, 0x72be5d74f27b896fL, 0x80deb1fe3b1696b1L, 0x9bdc06a725c71235L, 0xc19bf174cf692694L, 0xe49b69c19ef14ad2L, 0xefbe4786384f25e3L, 0x0fc19dc68b8cd5b5L, 0x240ca1cc77ac9c65L, 0x2de92c6f592b0275L, 0x4a7484aa6ea6e483L, 0x5cb0a9dcbd41fbd4L, 0x76f988da831153b5L, 0x983e5152ee66dfabL, 0xa831c66d2db43210L, 0xb00327c898fb213fL, 0xbf597fc7beef0ee4L, 0xc6e00bf33da88fc2L, 0xd5a79147930aa725L, 0x06ca6351e003826fL, 0x142929670a0e6e70L, 0x27b70a8546d22ffcL, 0x2e1b21385c26c926L, 0x4d2c6dfc5ac42aedL, 0x53380d139d95b3dfL, 0x650a73548baf63deL, 0x766a0abb3c77b2a8L, 0x81c2c92e47edaee6L, 0x92722c851482353bL, 0xa2bfe8a14cf10364L, 0xa81a664bbc423001L, 0xc24b8b70d0f89791L, 0xc76c51a30654be30L, 0xd192e819d6ef5218L, 0xd69906245565a910L, 0xf40e35855771202aL, 0x106aa07032bbd1b8L, 0x19a4c116b8d2d0c8L, 0x1e376c085141ab53L, 0x2748774cdf8eeb99L, 0x34b0bcb5e19b48a8L, 0x391c0cb3c5c95a63L, 0x4ed8aa4ae3418acbL, 0x5b9cca4f7763e373L, 0x682e6ff3d6b2b8a3L, 0x748f82ee5defb2fcL, 0x78a5636f43172f60L, 0x84c87814a1f0ab72L, 0x8cc702081a6439ecL, 0x90befffa23631e28L, 0xa4506cebde82bde9L, 0xbef9a3f7b2c67915L, 0xc67178f2e372532bL, 0xca273eceea26619cL, 0xd186b8c721c0c207L, 0xeada7dd6cde0eb1eL, 0xf57d4f7fee6ed178L, 0x06f067aa72176fbaL, 0x0a637dc5a2c898a6L, 0x113f9804bef90daeL, 0x1b710b35131c471bL, 0x28db77f523047d84L, 0x32caab7b40c72493L, 0x3c9ebe0a15c9bebcL, 0x431d67c49c100d4cL, 0x4cc5d4becb3e42b6L, 0x597f299cfc657e2aL, 0x5fcb6fab3ad6faecL, 0x6c44198c4a475817L }; } }
// Generated from https://github.com/nuke-build/nuke/blob/master/source/Nuke.Common/Tools/CorFlags/CorFlags.json using JetBrains.Annotations; using Newtonsoft.Json; using Nuke.Common; using Nuke.Common.Execution; using Nuke.Common.Tooling; using Nuke.Common.Tools; using Nuke.Common.Utilities.Collections; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; namespace Nuke.Common.Tools.CorFlags { /// <summary> /// <p>The CorFlags Conversion tool allows you to configure the CorFlags section of the header of a portable executable image.</p> /// <p>For more details, visit the <a href="https://docs.microsoft.com/en-us/dotnet/framework/tools/corflags-exe-corflags-conversion-tool">official website</a>.</p> /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] public static partial class CorFlagsTasks { /// <summary> /// Path to the CorFlags executable. /// </summary> public static string CorFlagsPath => ToolPathResolver.TryGetEnvironmentExecutable("CORFLAGS_EXE") ?? ToolPathResolver.GetPathExecutable("CorFlags.exe"); public static Action<OutputType, string> CorFlagsLogger { get; set; } = ProcessTasks.DefaultLogger; /// <summary> /// <p>The CorFlags Conversion tool allows you to configure the CorFlags section of the header of a portable executable image.</p> /// <p>For more details, visit the <a href="https://docs.microsoft.com/en-us/dotnet/framework/tools/corflags-exe-corflags-conversion-tool">official website</a>.</p> /// </summary> public static IReadOnlyCollection<Output> CorFlags(string arguments, string workingDirectory = null, IReadOnlyDictionary<string, string> environmentVariables = null, int? timeout = null, bool? logOutput = null, bool? logInvocation = null, Func<string, string> outputFilter = null) { using var process = ProcessTasks.StartProcess(CorFlagsPath, arguments, workingDirectory, environmentVariables, timeout, logOutput, logInvocation, CorFlagsLogger, outputFilter); process.AssertZeroExitCode(); return process.Output; } /// <summary> /// <p>The CorFlags Conversion tool allows you to configure the CorFlags section of the header of a portable executable image.</p> /// <p>For more details, visit the <a href="https://docs.microsoft.com/en-us/dotnet/framework/tools/corflags-exe-corflags-conversion-tool">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>&lt;assembly&gt;</c> via <see cref="CorFlagsSettings.Assembly"/></li> /// <li><c>-32BIT</c> via <see cref="CorFlagsSettings.Require32Bit"/></li> /// <li><c>-32BITPREF</c> via <see cref="CorFlagsSettings.Prefer32Bit"/></li> /// <li><c>-Force</c> via <see cref="CorFlagsSettings.Force"/></li> /// <li><c>-ILONLY</c> via <see cref="CorFlagsSettings.ILOnly"/></li> /// <li><c>-nologo</c> via <see cref="CorFlagsSettings.NoLogo"/></li> /// <li><c>-RevertCLRHeader</c> via <see cref="CorFlagsSettings.RevertCLRHeader"/></li> /// <li><c>-UpgradeCLRHeader</c> via <see cref="CorFlagsSettings.UpgradeCLRHeader"/></li> /// </ul> /// </remarks> public static IReadOnlyCollection<Output> CorFlags(CorFlagsSettings toolSettings = null) { toolSettings = toolSettings ?? new CorFlagsSettings(); using var process = ProcessTasks.StartProcess(toolSettings); process.AssertZeroExitCode(); return process.Output; } /// <summary> /// <p>The CorFlags Conversion tool allows you to configure the CorFlags section of the header of a portable executable image.</p> /// <p>For more details, visit the <a href="https://docs.microsoft.com/en-us/dotnet/framework/tools/corflags-exe-corflags-conversion-tool">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>&lt;assembly&gt;</c> via <see cref="CorFlagsSettings.Assembly"/></li> /// <li><c>-32BIT</c> via <see cref="CorFlagsSettings.Require32Bit"/></li> /// <li><c>-32BITPREF</c> via <see cref="CorFlagsSettings.Prefer32Bit"/></li> /// <li><c>-Force</c> via <see cref="CorFlagsSettings.Force"/></li> /// <li><c>-ILONLY</c> via <see cref="CorFlagsSettings.ILOnly"/></li> /// <li><c>-nologo</c> via <see cref="CorFlagsSettings.NoLogo"/></li> /// <li><c>-RevertCLRHeader</c> via <see cref="CorFlagsSettings.RevertCLRHeader"/></li> /// <li><c>-UpgradeCLRHeader</c> via <see cref="CorFlagsSettings.UpgradeCLRHeader"/></li> /// </ul> /// </remarks> public static IReadOnlyCollection<Output> CorFlags(Configure<CorFlagsSettings> configurator) { return CorFlags(configurator(new CorFlagsSettings())); } /// <summary> /// <p>The CorFlags Conversion tool allows you to configure the CorFlags section of the header of a portable executable image.</p> /// <p>For more details, visit the <a href="https://docs.microsoft.com/en-us/dotnet/framework/tools/corflags-exe-corflags-conversion-tool">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>&lt;assembly&gt;</c> via <see cref="CorFlagsSettings.Assembly"/></li> /// <li><c>-32BIT</c> via <see cref="CorFlagsSettings.Require32Bit"/></li> /// <li><c>-32BITPREF</c> via <see cref="CorFlagsSettings.Prefer32Bit"/></li> /// <li><c>-Force</c> via <see cref="CorFlagsSettings.Force"/></li> /// <li><c>-ILONLY</c> via <see cref="CorFlagsSettings.ILOnly"/></li> /// <li><c>-nologo</c> via <see cref="CorFlagsSettings.NoLogo"/></li> /// <li><c>-RevertCLRHeader</c> via <see cref="CorFlagsSettings.RevertCLRHeader"/></li> /// <li><c>-UpgradeCLRHeader</c> via <see cref="CorFlagsSettings.UpgradeCLRHeader"/></li> /// </ul> /// </remarks> public static IEnumerable<(CorFlagsSettings Settings, IReadOnlyCollection<Output> Output)> CorFlags(CombinatorialConfigure<CorFlagsSettings> configurator, int degreeOfParallelism = 1, bool completeOnFailure = false) { return configurator.Invoke(CorFlags, CorFlagsLogger, degreeOfParallelism, completeOnFailure); } } #region CorFlagsSettings /// <summary> /// Used within <see cref="CorFlagsTasks"/>. /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] [Serializable] public partial class CorFlagsSettings : ToolSettings { /// <summary> /// Path to the CorFlags executable. /// </summary> public override string ProcessToolPath => base.ProcessToolPath ?? CorFlagsTasks.CorFlagsPath; public override Action<OutputType, string> ProcessCustomLogger => CorFlagsTasks.CorFlagsLogger; /// <summary> /// Suppresses the Microsoft startup banner display. /// </summary> public virtual bool? NoLogo { get; internal set; } /// <summary> /// Upgrades the CLR header version to 2.5. <em>Note</em>: Assemblies must have a CLR header version of 2.5 or greater to run natively. /// </summary> public virtual bool? UpgradeCLRHeader { get; internal set; } /// <summary> /// Reverts the CLR header version to 2.0. /// </summary> public virtual bool? RevertCLRHeader { get; internal set; } /// <summary> /// Forces an update even if the assembly is strong-named. <em>Important</em>: If you update a strong-named assembly, you must sign it again before executing its code. /// </summary> public virtual bool? Force { get; internal set; } /// <summary> /// The name of the assembly for which to configure the CorFlags. /// </summary> public virtual string Assembly { get; internal set; } /// <summary> /// Sets/clears the ILONLY flag. /// </summary> public virtual bool? ILOnly { get; internal set; } /// <summary> /// Sets/clears the 32BITREQUIRED flag. /// </summary> public virtual bool? Require32Bit { get; internal set; } /// <summary> /// Sets/clears the 32BITPREFERRED flag. /// </summary> public virtual bool? Prefer32Bit { get; internal set; } protected override Arguments ConfigureProcessArguments(Arguments arguments) { arguments .Add("-nologo", NoLogo) .Add("-UpgradeCLRHeader", UpgradeCLRHeader) .Add("-RevertCLRHeader", RevertCLRHeader) .Add("-Force", Force) .Add("{value}", Assembly) .Add("-ILONLY{value}", GetILOnly(), customValue: true) .Add("-32BIT{value}", GetRequire32Bit(), customValue: true) .Add("-32BITPREF{value}", GetPrefer32Bit(), customValue: true); return base.ConfigureProcessArguments(arguments); } } #endregion #region CorFlagsSettingsExtensions /// <summary> /// Used within <see cref="CorFlagsTasks"/>. /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] public static partial class CorFlagsSettingsExtensions { #region NoLogo /// <summary> /// <p><em>Sets <see cref="CorFlagsSettings.NoLogo"/></em></p> /// <p>Suppresses the Microsoft startup banner display.</p> /// </summary> [Pure] public static T SetNoLogo<T>(this T toolSettings, bool? noLogo) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.NoLogo = noLogo; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CorFlagsSettings.NoLogo"/></em></p> /// <p>Suppresses the Microsoft startup banner display.</p> /// </summary> [Pure] public static T ResetNoLogo<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.NoLogo = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="CorFlagsSettings.NoLogo"/></em></p> /// <p>Suppresses the Microsoft startup banner display.</p> /// </summary> [Pure] public static T EnableNoLogo<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.NoLogo = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="CorFlagsSettings.NoLogo"/></em></p> /// <p>Suppresses the Microsoft startup banner display.</p> /// </summary> [Pure] public static T DisableNoLogo<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.NoLogo = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="CorFlagsSettings.NoLogo"/></em></p> /// <p>Suppresses the Microsoft startup banner display.</p> /// </summary> [Pure] public static T ToggleNoLogo<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.NoLogo = !toolSettings.NoLogo; return toolSettings; } #endregion #region UpgradeCLRHeader /// <summary> /// <p><em>Sets <see cref="CorFlagsSettings.UpgradeCLRHeader"/></em></p> /// <p>Upgrades the CLR header version to 2.5. <em>Note</em>: Assemblies must have a CLR header version of 2.5 or greater to run natively.</p> /// </summary> [Pure] public static T SetUpgradeCLRHeader<T>(this T toolSettings, bool? upgradeCLRHeader) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.UpgradeCLRHeader = upgradeCLRHeader; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CorFlagsSettings.UpgradeCLRHeader"/></em></p> /// <p>Upgrades the CLR header version to 2.5. <em>Note</em>: Assemblies must have a CLR header version of 2.5 or greater to run natively.</p> /// </summary> [Pure] public static T ResetUpgradeCLRHeader<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.UpgradeCLRHeader = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="CorFlagsSettings.UpgradeCLRHeader"/></em></p> /// <p>Upgrades the CLR header version to 2.5. <em>Note</em>: Assemblies must have a CLR header version of 2.5 or greater to run natively.</p> /// </summary> [Pure] public static T EnableUpgradeCLRHeader<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.UpgradeCLRHeader = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="CorFlagsSettings.UpgradeCLRHeader"/></em></p> /// <p>Upgrades the CLR header version to 2.5. <em>Note</em>: Assemblies must have a CLR header version of 2.5 or greater to run natively.</p> /// </summary> [Pure] public static T DisableUpgradeCLRHeader<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.UpgradeCLRHeader = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="CorFlagsSettings.UpgradeCLRHeader"/></em></p> /// <p>Upgrades the CLR header version to 2.5. <em>Note</em>: Assemblies must have a CLR header version of 2.5 or greater to run natively.</p> /// </summary> [Pure] public static T ToggleUpgradeCLRHeader<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.UpgradeCLRHeader = !toolSettings.UpgradeCLRHeader; return toolSettings; } #endregion #region RevertCLRHeader /// <summary> /// <p><em>Sets <see cref="CorFlagsSettings.RevertCLRHeader"/></em></p> /// <p>Reverts the CLR header version to 2.0.</p> /// </summary> [Pure] public static T SetRevertCLRHeader<T>(this T toolSettings, bool? revertCLRHeader) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.RevertCLRHeader = revertCLRHeader; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CorFlagsSettings.RevertCLRHeader"/></em></p> /// <p>Reverts the CLR header version to 2.0.</p> /// </summary> [Pure] public static T ResetRevertCLRHeader<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.RevertCLRHeader = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="CorFlagsSettings.RevertCLRHeader"/></em></p> /// <p>Reverts the CLR header version to 2.0.</p> /// </summary> [Pure] public static T EnableRevertCLRHeader<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.RevertCLRHeader = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="CorFlagsSettings.RevertCLRHeader"/></em></p> /// <p>Reverts the CLR header version to 2.0.</p> /// </summary> [Pure] public static T DisableRevertCLRHeader<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.RevertCLRHeader = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="CorFlagsSettings.RevertCLRHeader"/></em></p> /// <p>Reverts the CLR header version to 2.0.</p> /// </summary> [Pure] public static T ToggleRevertCLRHeader<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.RevertCLRHeader = !toolSettings.RevertCLRHeader; return toolSettings; } #endregion #region Force /// <summary> /// <p><em>Sets <see cref="CorFlagsSettings.Force"/></em></p> /// <p>Forces an update even if the assembly is strong-named. <em>Important</em>: If you update a strong-named assembly, you must sign it again before executing its code.</p> /// </summary> [Pure] public static T SetForce<T>(this T toolSettings, bool? force) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Force = force; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CorFlagsSettings.Force"/></em></p> /// <p>Forces an update even if the assembly is strong-named. <em>Important</em>: If you update a strong-named assembly, you must sign it again before executing its code.</p> /// </summary> [Pure] public static T ResetForce<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Force = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="CorFlagsSettings.Force"/></em></p> /// <p>Forces an update even if the assembly is strong-named. <em>Important</em>: If you update a strong-named assembly, you must sign it again before executing its code.</p> /// </summary> [Pure] public static T EnableForce<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Force = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="CorFlagsSettings.Force"/></em></p> /// <p>Forces an update even if the assembly is strong-named. <em>Important</em>: If you update a strong-named assembly, you must sign it again before executing its code.</p> /// </summary> [Pure] public static T DisableForce<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Force = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="CorFlagsSettings.Force"/></em></p> /// <p>Forces an update even if the assembly is strong-named. <em>Important</em>: If you update a strong-named assembly, you must sign it again before executing its code.</p> /// </summary> [Pure] public static T ToggleForce<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Force = !toolSettings.Force; return toolSettings; } #endregion #region Assembly /// <summary> /// <p><em>Sets <see cref="CorFlagsSettings.Assembly"/></em></p> /// <p>The name of the assembly for which to configure the CorFlags.</p> /// </summary> [Pure] public static T SetAssembly<T>(this T toolSettings, string assembly) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Assembly = assembly; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CorFlagsSettings.Assembly"/></em></p> /// <p>The name of the assembly for which to configure the CorFlags.</p> /// </summary> [Pure] public static T ResetAssembly<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Assembly = null; return toolSettings; } #endregion #region ILOnly /// <summary> /// <p><em>Sets <see cref="CorFlagsSettings.ILOnly"/></em></p> /// <p>Sets/clears the ILONLY flag.</p> /// </summary> [Pure] public static T SetILOnly<T>(this T toolSettings, bool? ilonly) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ILOnly = ilonly; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CorFlagsSettings.ILOnly"/></em></p> /// <p>Sets/clears the ILONLY flag.</p> /// </summary> [Pure] public static T ResetILOnly<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ILOnly = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="CorFlagsSettings.ILOnly"/></em></p> /// <p>Sets/clears the ILONLY flag.</p> /// </summary> [Pure] public static T EnableILOnly<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ILOnly = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="CorFlagsSettings.ILOnly"/></em></p> /// <p>Sets/clears the ILONLY flag.</p> /// </summary> [Pure] public static T DisableILOnly<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ILOnly = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="CorFlagsSettings.ILOnly"/></em></p> /// <p>Sets/clears the ILONLY flag.</p> /// </summary> [Pure] public static T ToggleILOnly<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ILOnly = !toolSettings.ILOnly; return toolSettings; } #endregion #region Require32Bit /// <summary> /// <p><em>Sets <see cref="CorFlagsSettings.Require32Bit"/></em></p> /// <p>Sets/clears the 32BITREQUIRED flag.</p> /// </summary> [Pure] public static T SetRequire32Bit<T>(this T toolSettings, bool? require32Bit) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Require32Bit = require32Bit; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CorFlagsSettings.Require32Bit"/></em></p> /// <p>Sets/clears the 32BITREQUIRED flag.</p> /// </summary> [Pure] public static T ResetRequire32Bit<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Require32Bit = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="CorFlagsSettings.Require32Bit"/></em></p> /// <p>Sets/clears the 32BITREQUIRED flag.</p> /// </summary> [Pure] public static T EnableRequire32Bit<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Require32Bit = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="CorFlagsSettings.Require32Bit"/></em></p> /// <p>Sets/clears the 32BITREQUIRED flag.</p> /// </summary> [Pure] public static T DisableRequire32Bit<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Require32Bit = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="CorFlagsSettings.Require32Bit"/></em></p> /// <p>Sets/clears the 32BITREQUIRED flag.</p> /// </summary> [Pure] public static T ToggleRequire32Bit<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Require32Bit = !toolSettings.Require32Bit; return toolSettings; } #endregion #region Prefer32Bit /// <summary> /// <p><em>Sets <see cref="CorFlagsSettings.Prefer32Bit"/></em></p> /// <p>Sets/clears the 32BITPREFERRED flag.</p> /// </summary> [Pure] public static T SetPrefer32Bit<T>(this T toolSettings, bool? prefer32Bit) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Prefer32Bit = prefer32Bit; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CorFlagsSettings.Prefer32Bit"/></em></p> /// <p>Sets/clears the 32BITPREFERRED flag.</p> /// </summary> [Pure] public static T ResetPrefer32Bit<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Prefer32Bit = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="CorFlagsSettings.Prefer32Bit"/></em></p> /// <p>Sets/clears the 32BITPREFERRED flag.</p> /// </summary> [Pure] public static T EnablePrefer32Bit<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Prefer32Bit = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="CorFlagsSettings.Prefer32Bit"/></em></p> /// <p>Sets/clears the 32BITPREFERRED flag.</p> /// </summary> [Pure] public static T DisablePrefer32Bit<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Prefer32Bit = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="CorFlagsSettings.Prefer32Bit"/></em></p> /// <p>Sets/clears the 32BITPREFERRED flag.</p> /// </summary> [Pure] public static T TogglePrefer32Bit<T>(this T toolSettings) where T : CorFlagsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Prefer32Bit = !toolSettings.Prefer32Bit; return toolSettings; } #endregion } #endregion }
using HtmlAgilityPack; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; namespace LibSiteScraper { public sealed class SiteScraper { public SiteScraper(ScrapePair scrapePair, bool isScraping) { m_scrapePair = scrapePair; m_isScraping = isScraping; m_directoryTree = new DirectoryTree(); } public async Task Scrape(Action<string> onNewLinkFound, CancellationToken token) { if (token.IsCancellationRequested) return; DirectoryTreeNode node = null; string scrapeFolder = m_isScraping ? (new Uri(Path.Combine(m_scrapePair.Path.AbsolutePath, m_scrapePair.Url.Authority))).AbsolutePath : (new Uri(Path.Combine(Path.GetTempPath(), AppDomain.CurrentDomain.FriendlyName, Path.GetRandomFileName()))).AbsolutePath; string basePath; if (!FileOrDirectoryExists(scrapeFolder)) { basePath = scrapeFolder; } else { int duplicateCount = 1; basePath = scrapeFolder + "(" + duplicateCount.ToString() + ")"; while (FileOrDirectoryExists(basePath)) basePath = scrapeFolder + "(" + (++duplicateCount).ToString() + ")"; } Console.CancelKeyPress += delegate { CleanUpDirectoryIfNecessary(basePath); }; Directory.CreateDirectory(basePath); try { Uri root = null; if (m_scrapePair.Url.AbsolutePath == "/") { root = new Uri(Path.Combine(basePath, "base")); if (File.Exists(root.AbsolutePath)) { Console.Error.WriteLine("File '{0}' already exists.", root.AbsolutePath); return; } else { node = await GetUrl(m_scrapePair.Url, root.AbsolutePath); } } onNewLinkFound(node.Path.AbsoluteUri); DirectoryTreeNode directoryTreeNode = m_directoryTree.AddLink(null, node.Path.AbsoluteUri, node.Status); if (root == null) return; List<string> resources = GetLinks(root, 0); foreach (string resource in resources) { if (resource.First() == '/') { Uri nextUrl; string urlInput = string.Format("{0}{1}{2}{3}", m_scrapePair.Url.Scheme, Uri.SchemeDelimiter, m_scrapePair.Url.Authority, resource); if (Uri.TryCreate(urlInput, UriKind.Absolute, out nextUrl)) { await Scrape(onNewLinkFound, token, directoryTreeNode, nextUrl, basePath); } else { Console.Error.WriteLine("Link '{0}' was of incorrect form.", urlInput); continue; } } else { //File that is an outside resource } } } catch (WebException ex) { Console.WriteLine(ex.Message); throw; } finally { CleanUpDirectoryIfNecessary(basePath); } } public static async Task Start(ConcurrentQueue<ScrapePair> crawlQueue, Action<string> onNewLinkFound, bool isScraping, CancellationToken token) { Console.WriteLine("pwd:{0}", Directory.GetCurrentDirectory()); while (!crawlQueue.IsEmpty) { ScrapePair scrapePair; if (crawlQueue.TryDequeue(out scrapePair)) { if (isScraping && !Directory.Exists(scrapePair.Path.AbsolutePath)) { Console.Error.WriteLine("The following path doesn't exist: {0}", scrapePair.Path); Directory.CreateDirectory(scrapePair.Path.AbsolutePath); } // TODO(cm): Add support of other schemes (Issue ID: 1) if (scrapePair.Url.Scheme != Uri.UriSchemeHttp) { Console.Error.WriteLine("Scheme Not Supported: uri '{0}' is not of the HTTP scheme.", scrapePair.Url.AbsoluteUri); continue; } SiteScraper scraper = new SiteScraper(scrapePair, isScraping); await scraper.Scrape(onNewLinkFound, token); } else { Console.Error.WriteLine("Unable to dequeue the next site."); Environment.Exit(-1); } } } async Task Scrape(Action<string> onNewLinkFound, CancellationToken token, DirectoryTreeNode current, Uri url, string path) { if (token.IsCancellationRequested) return; try { int depth; string dataPath; DirectoryTreeNode node = null; DirectoryTreeNode directoryTreeNode = null; if (url.AbsolutePath != "/") { string[] directory = url.AbsolutePath.Split('/').Where(x => x != "").ToArray(); depth = directory.Length; dataPath = ""; foreach (string dir in directory.Reverse().Skip(1).Reverse()) { dataPath = Path.Combine(dataPath, dir); string currentLevel = (new Uri(Path.Combine(path, dataPath))).AbsolutePath; if (!FileOrDirectoryExists(currentLevel)) { Console.WriteLine("Creating Dir:@{1}:{0}", currentLevel, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber()); Directory.CreateDirectory(currentLevel); } } // If the file doesn't have an extension append html string filename = directory.Last(); IfNecessaryAppendHtml(ref filename); dataPath = Path.Combine(path, Path.Combine(dataPath, filename)); if (File.Exists(dataPath)) { Console.Error.WriteLine("{0} already exists", dataPath); return; } else { if (filename.Split('.').Where(x => x != "").Last().StartsWith("htm")) depth = directory.Length - 1; node = await GetUrl(url, dataPath); } onNewLinkFound(node.Path.AbsoluteUri); directoryTreeNode = m_directoryTree.AddLink(current, node.Path.AbsoluteUri, node.Status); } else { Console.Error.WriteLine("Attempting to retrieve root again."); return; } Uri data; if (!Uri.TryCreate(dataPath, UriKind.RelativeOrAbsolute, out data)) { Console.Error.WriteLine("The path '{0}' is not well formed.", dataPath); return; } List<string> resources = GetLinks(data, depth); foreach (string resource in resources) { if (!string.IsNullOrEmpty(resource) && resource.First() == '/') { Uri nextUrl; string urlInput = string.Format("{0}{1}{2}{3}", url.Scheme, Uri.SchemeDelimiter, url.Authority, resource); if (Uri.TryCreate(urlInput, UriKind.Absolute, out nextUrl)) { await Scrape(onNewLinkFound, token, current, nextUrl, path); } else { Console.Error.WriteLine("Link '{0}' was of incorrect form.", urlInput); continue; } } else { //File that is an outside resource } } } catch (WebException e) { Console.WriteLine("WebExceptionMessage :" + e.Message); if (e.Status == WebExceptionStatus.ProtocolError) { Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode); Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription); } } } async Task<DirectoryTreeNode> GetUrl(Uri url, string path) { HttpStatusCode status; HttpWebResponse response; try { HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; request.UserAgent = "TurtleSpider/0.1"; using (response = await request.GetResponseAsync() as HttpWebResponse) { status = response.StatusCode; if (response.StatusCode == HttpStatusCode.OK) { if (Directory.Exists(path)) path = Path.Combine(path, "root"); using (Stream fileOut = File.Create(path)) using (Stream responseStream = response.GetResponseStream()) { byte[] buffer = new byte[8 * 1024]; int len; while ((len = responseStream.Read(buffer, 0, buffer.Length)) > 0) { fileOut.Write(buffer, 0, len); } } } } } catch (WebException ex) { response = ex.Response as HttpWebResponse; status = response.StatusCode; if (response.StatusCode == HttpStatusCode.NotFound) Console.Error.WriteLine("Link '{0}' not found.", url.AbsoluteUri); else throw ex; } return new DirectoryTreeNode(url, status); } List<string> GetLinks(Uri urlData, int depth) { HtmlDocument doc = new HtmlDocument(); List<string> resources = new List<string>(); try { doc.Load(urlData.AbsolutePath); if (doc.ParseErrors == null || !doc.ParseErrors.Any()) { if (doc.DocumentNode != null) { foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//link[@href]").EmptyOrNotNull()) { HtmlAttribute att = link.Attributes["href"]; resources.Add(att.Value); string attributeValue = att.Value; IfNecessaryAppendHtml(ref attributeValue); if (attributeValue.ToCharArray().First() == '/') { string prependDepth = "."; for (int i = 0; i < depth; ++i) { prependDepth += "/.."; } attributeValue = string.Format("{1}{0}", attributeValue, prependDepth); } att.Value = attributeValue; link.Attributes["href"] = att; } foreach (HtmlNode imgLink in doc.DocumentNode.SelectNodes("//img[@src]").EmptyOrNotNull()) { HtmlAttribute att = imgLink.Attributes["src"]; resources.Add(att.Value); string attributeValue = att.Value; IfNecessaryAppendHtml(ref attributeValue); if (attributeValue.ToCharArray().First() == '/') { string prependDepth = "."; for (int i = 0; i < depth; ++i) { prependDepth += "/.."; } attributeValue = string.Format("{1}{0}", attributeValue, prependDepth); } att.Value = attributeValue; imgLink.Attributes["src"] = att; } foreach (HtmlNode hyperLink in doc.DocumentNode.SelectNodes("//a[@href]").EmptyOrNotNull()) { HtmlAttribute att = hyperLink.Attributes["href"]; if (att.Value.Length > 2 && att.Value.StartsWith("//")) continue; resources.Add(att.Value); string attributeValue = att.Value; IfNecessaryAppendHtml(ref attributeValue); if (attributeValue.ToCharArray().First() == '/') { string prependDepth = "."; for (int i = 0; i < depth; ++i) { prependDepth += "/.."; } attributeValue = string.Format("{1}{0}", attributeValue, prependDepth); } att.Value = attributeValue; hyperLink.Attributes["href"] = att; } doc.Save(urlData.AbsolutePath); } } } catch (IOException ex) { Console.WriteLine("'{0}' threw an error {1}", urlData.AbsoluteUri, ex.Message); } return resources; } public static bool FileOrDirectoryExists(string name) { return (Directory.Exists(name) || File.Exists(name)); } bool HasAFileExtension(string filename) { return filename.Split('.').Last() != filename && filename.Split('.').Last().Length <= 4; } void IfNecessaryAppendHtml(ref string filename) { if (!HasAFileExtension(filename)) filename = String.Format("{0}{1}", filename, c_noExtensionFile); } void CleanUpDirectoryIfNecessary(string path) { if (IsScraping || !FileOrDirectoryExists(path)) return; Console.WriteLine("Cleanup up directory '{0}'", path); DirectoryInfo directory = new DirectoryInfo(path); foreach (FileInfo file in directory.GetFiles()) file.Delete(); foreach (DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true); directory.Delete(); } public bool IsScraping { get { return m_isScraping; } } public const string c_noExtensionFile = ".html"; readonly bool m_isScraping; readonly ScrapePair m_scrapePair; readonly DirectoryTree m_directoryTree; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Eto.Forms; using Eto.Drawing; namespace Eto.Test { public class MainForm : Form { TextArea eventLog; Panel contentContainer; Navigation navigation; public TextArea EventLog { get { if (eventLog == null) { eventLog = new TextArea { Size = new Size(100, 100), ReadOnly = true, Wrap = false }; } return eventLog; } } public MainForm(IEnumerable<Section> topNodes = null) { Title = string.Format("Test Application [{0}]", Platform.ID); Style = "main"; MinimumSize = new Size(400, 400); topNodes = topNodes ?? TestSections.Get(TestApplication.DefaultTestAssemblies()); //SectionList = new SectionListGridView(topNodes); //SectionList = new SectionListTreeView(topNodes); if (Platform.IsAndroid) SectionList = new SectionListGridView(topNodes); else SectionList = new SectionListTreeGridView(topNodes); this.Icon = TestIcons.TestIcon; if (Platform.IsDesktop) ClientSize = new Size(900, 650); //Opacity = 0.5; Content = MainContent(); CreateMenuToolBar(); } public SectionList SectionList { get; set; } Control MainContent() { contentContainer = new Panel(); // set focus when the form is shown Shown += delegate { SectionList.Focus(); }; SectionList.SelectedItemChanged += (sender, e) => { try { var item = SectionList.SelectedItem; Control content = item != null ? item.CreateContent() : null; if (navigation != null) { if (content != null) navigation.Push(content, item != null ? item.Text : null); } else { contentContainer.Content = content; } } catch (Exception ex) { Log.Write(this, "Error loading section: {0}", ex.GetBaseException()); contentContainer.Content = null; } #if DEBUG GC.Collect(); GC.WaitForPendingFinalizers(); #endif }; if (Splitter.IsSupported) { var splitter = new Splitter { Position = 200, FixedPanel = SplitterFixedPanel.Panel1, Panel1 = SectionList.Control, // for now, don't show log in mobile Panel2 = Platform.IsMobile ? contentContainer : RightPane() }; return splitter; } if (Navigation.IsSupported) { navigation = new Navigation(SectionList.Control, "Eto.Test"); return navigation; } throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Platform must support splitter or navigation")); } Control RightPane() { return new Splitter { Orientation = Orientation.Vertical, FixedPanel = SplitterFixedPanel.Panel2, Panel1 = contentContainer, Panel2 = EventLogSection() }; } Control EventLogSection() { var layout = new DynamicLayout { Size = new Size(100, 120), DefaultSpacing = new Size(5, 5) }; layout.BeginHorizontal(); layout.Add(EventLog, true); layout.BeginVertical(new Padding(0, 0, 5, 0)); layout.Add(ClearButton()); layout.Add(MemoryButton()); layout.Add(null); layout.EndVertical(); layout.EndHorizontal(); return layout; } Control ClearButton() { var control = new Button { Text = "Clear" }; control.Click += (sender, e) => EventLog.Text = string.Empty; return control; } Control MemoryButton() { var control = new Button { Text = "Memory" }; control.Click += (sender, e) => { GC.Collect(); GC.WaitForPendingFinalizers(); Log.Write(null, "Memory: {0}", GC.GetTotalMemory(true)); }; return control; } void CreateMenuToolBar() { var about = new Commands.About(); var quit = new Commands.Quit(); if (Platform.Supports<MenuBar>()) { var file = new ButtonMenuItem { Text = "&File", Items = { new Command { MenuText = "File Command" } } }; var edit = new ButtonMenuItem { Text = "&Edit", Items = { new Command { MenuText = "Edit Command" } } }; var view = new ButtonMenuItem { Text = "&View", Items = { new Command { MenuText = "View Command" } } }; var window = new ButtonMenuItem { Text = "&Window", Order = 1000, Items = { new Command { MenuText = "Window Command" } } }; if (Platform.Supports<CheckMenuItem>()) { edit.Items.AddSeparator(); var checkMenuItem1 = new CheckMenuItem { Text = "Check Menu Item" }; checkMenuItem1.Click += (sender, e) => Log.Write(checkMenuItem1, "Click, {0}, Checked: {1}", checkMenuItem1.Text, checkMenuItem1.Checked); checkMenuItem1.CheckedChanged += (sender, e) => Log.Write(checkMenuItem1, "CheckedChanged, {0}: {1}", checkMenuItem1.Text, checkMenuItem1.Checked); edit.Items.Add(checkMenuItem1); var checkMenuItem2 = new CheckMenuItem { Text = "Initially Checked Menu Item", Checked = true }; checkMenuItem2.Click += (sender, e) => Log.Write(checkMenuItem2, "Click, {0}, Checked: {1}", checkMenuItem2.Text, checkMenuItem2.Checked); checkMenuItem2.CheckedChanged += (sender, e) => Log.Write(checkMenuItem2, "CheckedChanged, {0}: {1}", checkMenuItem2.Text, checkMenuItem2.Checked); edit.Items.Add(checkMenuItem2); } if (Platform.Supports<RadioMenuItem>()) { edit.Items.AddSeparator(); RadioMenuItem controller = null; for (int i = 0; i < 5; i++) { var radio = new RadioMenuItem(controller) { Text = "Radio Menu Item " + (i + 1) }; radio.Click += (sender, e) => Log.Write(radio, "Click, {0}, Checked: {1}", radio.Text, radio.Checked); radio.CheckedChanged += (sender, e) => Log.Write(radio, "CheckedChanged, {0}: {1}", radio.Text, radio.Checked); edit.Items.Add(radio); if (controller == null) { radio.Checked = true; // check the first item initially controller = radio; } } } Menu = new MenuBar { Items = { // custom top-level menu items file, edit, view, window }, ApplicationItems = { // custom menu items for the application menu (Application on OS X, File on others) new Command { MenuText = "Application command" }, new ButtonMenuItem { Text = "Application menu item" } }, HelpItems = { new Command { MenuText = "Help Command" } }, QuitItem = quit, AboutItem = about }; } if (Platform.Supports<ToolBar>()) { // create and set the toolbar ToolBar = new ToolBar(); ToolBar.Items.Add(about); if (Platform.Supports<CheckToolItem>()) { ToolBar.Items.Add(new SeparatorToolItem { Type = SeparatorToolItemType.Divider }); ToolBar.Items.Add(new CheckToolItem { Text = "Check", Image = TestIcons.TestImage }); } if (Platform.Supports<RadioToolItem>()) { ToolBar.Items.Add(new SeparatorToolItem { Type = SeparatorToolItemType.FlexibleSpace }); ToolBar.Items.Add(new RadioToolItem { Text = "Radio1", Image = TestIcons.TestIcon, Checked = true }); ToolBar.Items.Add(new RadioToolItem { Text = "Radio2", Image = TestIcons.TestImage }); }; } } protected override void OnWindowStateChanged(EventArgs e) { base.OnWindowStateChanged(e); Log.Write(this, "StateChanged: {0}", WindowState); } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); Log.Write(this, "Closing"); /* * Note that on OS X, windows usually close, but the application will keep running. It is * usually better to handle the Application.OnTerminating event instead. * var result = MessageBox.Show (this, "Are you sure you want to close?", MessageBoxButtons.YesNo); if (result == DialogResult.No) e.Cancel = true; */ } protected override void OnClosed(EventArgs e) { base.OnClosed(e); Log.Write(this, "Closed"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Diagnostics.SymbolStore; namespace Microsoft.Diagnostics.Runtime.Utilities.Pdb { internal class PdbFile { private PdbFile() // This class can't be instantiated. { } private static void LoadGuidStream(BitAccess bits, out Guid doctype, out Guid language, out Guid vendor, out Guid algorithmId, out byte[] checksum, out byte[] embeddedSource) { bits.ReadGuid(out language); bits.ReadGuid(out vendor); bits.ReadGuid(out doctype); bits.ReadGuid(out algorithmId); int checksumSize; bits.ReadInt32(out checksumSize); int sourceSize; bits.ReadInt32(out sourceSize); checksum = new byte[checksumSize]; bits.ReadBytes(checksum); embeddedSource = new byte[sourceSize]; bits.ReadBytes(embeddedSource); } private static Dictionary<string, int> LoadNameIndex(BitAccess bits, out int ver, out int sig, out int age, out Guid guid) { Dictionary<string, int> result = new Dictionary<string, int>(); bits.ReadInt32(out ver); // 0..3 Version bits.ReadInt32(out sig); // 4..7 Signature bits.ReadInt32(out age); // 8..11 Age bits.ReadGuid(out guid); // 12..27 GUID //if (ver != 20000404) { // throw new PdbDebugException("Unsupported PDB Stream version {0}", ver); //} // Read string buffer. int buf; bits.ReadInt32(out buf); // 28..31 Bytes of Strings int beg = bits.Position; int nxt = bits.Position + buf; bits.Position = nxt; // Read map index. int cnt; // n+0..3 hash size. int max; // n+4..7 maximum ni. bits.ReadInt32(out cnt); bits.ReadInt32(out max); BitSet present = new BitSet(bits); BitSet deleted = new BitSet(bits); if (!deleted.IsEmpty) { throw new PdbDebugException("Unsupported PDB deleted bitset is not empty."); } int j = 0; for (int i = 0; i < max; i++) { if (present.IsSet(i)) { int ns; int ni; bits.ReadInt32(out ns); bits.ReadInt32(out ni); string name; int saved = bits.Position; bits.Position = beg + ns; bits.ReadCString(out name); bits.Position = saved; result.Add(name.ToUpperInvariant(), ni); j++; } } if (j != cnt) { throw new PdbDebugException("Count mismatch. ({0} != {1})", j, cnt); } return result; } private static Dictionary<int, string> LoadNameStream(BitAccess bits) { Dictionary<int, string> ht = new Dictionary<int, string>(); uint sig; int ver; bits.ReadUInt32(out sig); // 0..3 Signature bits.ReadInt32(out ver); // 4..7 Version // Read (or skip) string buffer. int buf; bits.ReadInt32(out buf); // 8..11 Bytes of Strings if (sig != 0xeffeeffe || ver != 1) { throw new PdbDebugException("Unsupported Name Stream version. " + "(sig={0:x8}, ver={1})", sig, ver); } int beg = bits.Position; int nxt = bits.Position + buf; bits.Position = nxt; // Read hash table. int siz; bits.ReadInt32(out siz); // n+0..3 Number of hash buckets. nxt = bits.Position; for (int i = 0; i < siz; i++) { int ni; string name; bits.ReadInt32(out ni); if (ni != 0) { int saved = bits.Position; bits.Position = beg + ni; bits.ReadCString(out name); bits.Position = saved; ht.Add(ni, name); } } bits.Position = nxt; return ht; } private static PdbFunction s_match = new PdbFunction(); private static int FindFunction(PdbFunction[] funcs, ushort sec, uint off) { s_match.Segment = sec; s_match.Address = off; return Array.BinarySearch(funcs, s_match, PdbFunction.byAddress); } private static void LoadManagedLines(PdbFunction[] funcs, Dictionary<int, string> names, BitAccess bits, MsfDirectory dir, Dictionary<string, int> nameIndex, PdbStreamHelper reader, uint limit, Dictionary<string, PdbSource> sources) { Array.Sort(funcs, PdbFunction.byAddressAndToken); Dictionary<int, PdbSource> checks = new Dictionary<int, PdbSource>(); // Read the files first int begin = bits.Position; while (bits.Position < limit) { int sig; int siz; bits.ReadInt32(out sig); bits.ReadInt32(out siz); int place = bits.Position; int endSym = bits.Position + siz; switch ((DEBUG_S_SUBSECTION)sig) { case DEBUG_S_SUBSECTION.FILECHKSMS: while (bits.Position < endSym) { CV_FileCheckSum chk; int ni = bits.Position - place; bits.ReadUInt32(out chk.name); bits.ReadUInt8(out chk.len); bits.ReadUInt8(out chk.type); string name = names[(int)chk.name]; PdbSource src; if (!sources.TryGetValue(name.ToUpperInvariant(), out src)) { int guidStream; Guid doctypeGuid = Guid.Empty; Guid languageGuid = Guid.Empty; Guid vendorGuid = Guid.Empty; Guid algorithmId = Guid.Empty; byte[] checksum = null; byte[] source = null; if (nameIndex.TryGetValue("/SRC/FILES/" + name.ToUpperInvariant(), out guidStream)) { var guidBits = new BitAccess(0x100); dir._streams[guidStream].Read(reader, guidBits); LoadGuidStream(guidBits, out doctypeGuid, out languageGuid, out vendorGuid, out algorithmId, out checksum, out source); } src = new PdbSource(/*(uint)ni,*/ name, doctypeGuid, languageGuid, vendorGuid, algorithmId, checksum, source); sources.Add(name.ToUpperInvariant(), src); } checks.Add(ni, src); bits.Position += chk.len; bits.Align(4); } bits.Position = endSym; break; default: bits.Position = endSym; break; } } // Read the lines next. bits.Position = begin; while (bits.Position < limit) { int sig; int siz; bits.ReadInt32(out sig); bits.ReadInt32(out siz); int endSym = bits.Position + siz; switch ((DEBUG_S_SUBSECTION)sig) { case DEBUG_S_SUBSECTION.LINES: { CV_LineSection sec; bits.ReadUInt32(out sec.off); bits.ReadUInt16(out sec.sec); bits.ReadUInt16(out sec.flags); bits.ReadUInt32(out sec.cod); int funcIndex = FindFunction(funcs, sec.sec, sec.off); if (funcIndex < 0) break; var func = funcs[funcIndex]; if (func.SequencePoints == null) { while (funcIndex > 0) { var f = funcs[funcIndex - 1]; if (f.SequencePoints != null || f.Segment != sec.sec || f.Address != sec.off) break; func = f; funcIndex--; } } else { while (funcIndex < funcs.Length - 1 && func.SequencePoints != null) { var f = funcs[funcIndex + 1]; if (f.Segment != sec.sec || f.Address != sec.off) break; func = f; funcIndex++; } } if (func.SequencePoints != null) break; // Count the line blocks. int begSym = bits.Position; int blocks = 0; while (bits.Position < endSym) { CV_SourceFile file; bits.ReadUInt32(out file.index); bits.ReadUInt32(out file.count); bits.ReadUInt32(out file.linsiz); // Size of payload. int linsiz = (int)file.count * (8 + ((sec.flags & 1) != 0 ? 4 : 0)); bits.Position += linsiz; blocks++; } func.SequencePoints = new PdbSequencePointCollection[blocks]; int block = 0; bits.Position = begSym; while (bits.Position < endSym) { CV_SourceFile file; bits.ReadUInt32(out file.index); bits.ReadUInt32(out file.count); bits.ReadUInt32(out file.linsiz); // Size of payload. PdbSource src = (PdbSource)checks[(int)file.index]; PdbSequencePointCollection tmp = new PdbSequencePointCollection(src, file.count); func.SequencePoints[block++] = tmp; PdbSequencePoint[] lines = tmp.Lines; int plin = bits.Position; int pcol = bits.Position + 8 * (int)file.count; for (int i = 0; i < file.count; i++) { CV_Line line; CV_Column column = new CV_Column(); bits.Position = plin + 8 * i; bits.ReadUInt32(out line.offset); bits.ReadUInt32(out line.flags); uint lineBegin = line.flags & (uint)CV_Line_Flags.linenumStart; uint delta = (line.flags & (uint)CV_Line_Flags.deltaLineEnd) >> 24; //bool statement = ((line.flags & (uint)CV_Line_Flags.fStatement) == 0); if ((sec.flags & 1) != 0) { bits.Position = pcol + 4 * i; bits.ReadUInt16(out column.offColumnStart); bits.ReadUInt16(out column.offColumnEnd); } lines[i] = new PdbSequencePoint(line.offset, lineBegin, column.offColumnStart, lineBegin + delta, column.offColumnEnd); } } break; } } bits.Position = endSym; } } private static void LoadFuncsFromDbiModule(BitAccess bits, DbiModuleInfo info, Dictionary<int, string> names, List<PdbFunction> funcList, bool readStrings, MsfDirectory dir, Dictionary<string, int> nameIndex, PdbStreamHelper reader, Dictionary<string, PdbSource> sources) { PdbFunction[] funcs = null; bits.Position = 0; int sig; bits.ReadInt32(out sig); if (sig != 4) { throw new PdbDebugException("Invalid signature. (sig={0})", sig); } bits.Position = 4; // Console.WriteLine("{0}:", info.moduleName); funcs = PdbFunction.LoadManagedFunctions(/*info.moduleName,*/ bits, (uint)info.cbSyms, readStrings); if (funcs != null) { bits.Position = info.cbSyms + info.cbOldLines; LoadManagedLines(funcs, names, bits, dir, nameIndex, reader, (uint)(info.cbSyms + info.cbOldLines + info.cbLines), sources); for (int i = 0; i < funcs.Length; i++) { funcList.Add(funcs[i]); } } } private static void LoadDbiStream(BitAccess bits, out DbiModuleInfo[] modules, out DbiDbgHdr header, bool readStrings) { DbiHeader dh = new DbiHeader(bits); header = new DbiDbgHdr(); //if (dh.sig != -1 || dh.ver != 19990903) { // throw new PdbException("Unsupported DBI Stream version, sig={0}, ver={1}", // dh.sig, dh.ver); //} // Read gpmod section. List<DbiModuleInfo> modList = new List<DbiModuleInfo>(); int end = bits.Position + dh.gpmodiSize; while (bits.Position < end) { DbiModuleInfo mod = new DbiModuleInfo(bits, readStrings); modList.Add(mod); } if (bits.Position != end) { throw new PdbDebugException("Error reading DBI stream, pos={0} != {1}", bits.Position, end); } if (modList.Count > 0) { modules = modList.ToArray(); } else { modules = null; } // Skip the Section Contribution substream. bits.Position += dh.secconSize; // Skip the Section Map substream. bits.Position += dh.secmapSize; // Skip the File Info substream. bits.Position += dh.filinfSize; // Skip the TSM substream. bits.Position += dh.tsmapSize; // Skip the EC substream. bits.Position += dh.ecinfoSize; // Read the optional header. end = bits.Position + dh.dbghdrSize; if (dh.dbghdrSize > 0) { header = new DbiDbgHdr(bits); } bits.Position = end; } internal static PdbFunction[] LoadFunctions(Stream read, bool readAllStrings, out int ver, out int sig, out int age, out Guid guid, out IEnumerable<PdbSource> sources) { BitAccess bits = new BitAccess(512 * 1024); return LoadFunctions(read, bits, readAllStrings, out ver, out sig, out age, out guid, out sources); } internal static PdbFunction[] LoadFunctions(Stream read, BitAccess bits, bool readAllStrings, out int ver, out int sig, out int age, out Guid guid, out IEnumerable<PdbSource> sources) { sources = null; PdbFileHeader head = new PdbFileHeader(read, bits); PdbStreamHelper reader = new PdbStreamHelper(read, head.PageSize); MsfDirectory dir = new MsfDirectory(reader, head, bits); DbiModuleInfo[] modules = null; DbiDbgHdr header; dir._streams[1].Read(reader, bits); Dictionary<string, int> nameIndex = LoadNameIndex(bits, out ver, out sig, out age, out guid); int nameStream; if (!nameIndex.TryGetValue("/NAMES", out nameStream)) { throw new PdbException("No `name' stream"); } dir._streams[nameStream].Read(reader, bits); Dictionary<int, string> names = LoadNameStream(bits); dir._streams[3].Read(reader, bits); LoadDbiStream(bits, out modules, out header, readAllStrings); List<PdbFunction> funcList = new List<PdbFunction>(); Dictionary<string, PdbSource> sourceDictionary = new Dictionary<string, PdbSource>(); if (modules != null) { for (int m = 0; m < modules.Length; m++) { if (modules[m].stream > 0) { dir._streams[modules[m].stream].Read(reader, bits); LoadFuncsFromDbiModule(bits, modules[m], names, funcList, readAllStrings, dir, nameIndex, reader, sourceDictionary); } } } PdbFunction[] funcs = funcList.ToArray(); sources = sourceDictionary.Values; // After reading the functions, apply the token remapping table if it exists. if (header.snTokenRidMap != 0 && header.snTokenRidMap != 0xffff) { dir._streams[header.snTokenRidMap].Read(reader, bits); uint[] ridMap = new uint[dir._streams[header.snTokenRidMap].Length / 4]; bits.ReadUInt32(ridMap); foreach (PdbFunction func in funcs) { func.Token = 0x06000000 | ridMap[func.Token & 0xffffff]; } } // Array.Sort(funcs, PdbFunction.byAddressAndToken); //Array.Sort(funcs, PdbFunction.byToken); return funcs; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Portions derived from React Native: // Copyright (c) 2015-present, Facebook, Inc. // Licensed under the MIT License. using Newtonsoft.Json.Linq; using ReactNative.Bridge; using ReactNative.Json; using ReactNative.Modules.Core; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; #if WINDOWS_UWP using Windows.Storage; using Windows.Web.Http; using Windows.Web.Http.Filters; using Windows.Web.Http.Headers; #else using PCLStorage; using System.Linq; using System.Net; using System.Net.Http; using HttpMediaTypeHeaderValue = System.Net.Http.Headers.MediaTypeHeaderValue; using HttpMultipartFormDataContent = System.Net.Http.MultipartFormDataContent; using HttpStreamContent = System.Net.Http.StreamContent; using HttpStringContent = System.Net.Http.StringContent; using HttpBaseProtocolFilter = System.Net.Http.WebRequestHandler; #endif namespace ReactNative.Modules.Network { /// <summary> /// Implements the XMLHttpRequest JavaScript interface. /// </summary> public class NetworkingModule : ReactContextNativeModuleBase { private const int MaxChunkSizeBetweenFlushes = 8 * 1024; // 8kb private readonly IHttpClient _client; private readonly TaskCancellationManager<int> _tasks; private bool _shuttingDown; /// <summary> /// Instantiates the <see cref="NetworkingModule"/>. /// </summary> /// <param name="reactContext">The context.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "HttpClient disposed by module.")] internal NetworkingModule(ReactContext reactContext) : this(CreateDefaultHttpClient(), reactContext) { } /// <summary> /// Instantiates the <see cref="NetworkingModule"/>. /// </summary> /// <param name="client">The HTTP client.</param> /// <param name="reactContext">The context.</param> public NetworkingModule(IHttpClient client, ReactContext reactContext) : base(reactContext) { #if !WINDOWS_UWP ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; #endif ServicePointManager.Expect100Continue = false; _client = client; _tasks = new TaskCancellationManager<int>(); } /// <summary> /// The name of the native module. /// </summary> public override string Name { get { return "Networking"; } } /// <inheritedoc /> public override bool CanOverrideExistingModule => true; private RCTDeviceEventEmitter EventEmitter { get { return Context.GetJavaScriptModule<RCTDeviceEventEmitter>(); } } /// <summary> /// Send an HTTP request on the networking module. /// </summary> /// <param name="method">The HTTP method.</param> /// <param name="url">The URL.</param> /// <param name="requestId">The request ID.</param> /// <param name="headers">The headers.</param> /// <param name="data">The request data.</param> /// <param name="responseType">The response type (either "text" or "base64").</param> /// <param name="useIncrementalUpdates"> /// <code>true</code> if incremental updates are allowed. /// </param> /// <param name="timeout">The timeout.</param> [ReactMethod] public void sendRequest( string method, Uri url, int requestId, string[][] headers, JObject data, string responseType, bool useIncrementalUpdates, int timeout) { if (method == null) throw new ArgumentNullException(nameof(method)); if (url == null) throw new ArgumentNullException(nameof(url)); if (responseType == null) throw new ArgumentNullException(nameof(responseType)); if (responseType != "text" && responseType != "base64") throw new ArgumentOutOfRangeException(nameof(responseType)); var request = new HttpRequestMessage(new HttpMethod(method), url); var headerData = default(HttpContentHeaderData); if (headers != null) { headerData = HttpContentHelpers.ExtractHeaders(headers); ApplyHeaders(request, headers); } if (data != null) { var stringBody = data.Value<string>("string"); var base64Body = default(string); var uri = default(string); var formData = default(JArray); if (HasRequestContent(data) && headerData.ContentType == null) { OnRequestError(requestId, "Payload is set but no 'content-type' header specified.", false); return; } if (stringBody != null) { request.Content = HttpContentHelpers.CreateFromBody(headerData, stringBody); } else if ((base64Body = data.Value<string>("base64")) != null) { request.Content = HttpContentHelpers.CreateFromBase64(headerData, base64Body); } else if ((uri = data.Value<string>("uri")) != null) { _tasks.AddAndInvokeAsync(requestId, token => ProcessRequestFromUriAsync( requestId, new Uri(uri), headerData, useIncrementalUpdates, timeout, request, responseType, token)); return; } else if ((formData = (JArray)data.GetValue("formData", StringComparison.Ordinal)) != null) { if (headerData.ContentType == null) { headerData.ContentType = "multipart/form-data"; } var formDataContent = new HttpMultipartFormDataContent(); foreach (var content in formData) { var fieldName = content.Value<string>("fieldName"); var stringContent = content.Value<string>("string"); if (stringContent != null) { formDataContent.Add(new HttpStringContent(stringContent), fieldName); } } request.Content = formDataContent; } } _tasks.AddAndInvokeAsync(requestId, async token => { using (request) { try { await ProcessRequestAsync( requestId, useIncrementalUpdates, timeout, request, responseType, token); } finally { var content = request.Content; if (content != null) { content.Dispose(); } } } }); } /// <summary> /// Abort an HTTP request with the given request ID. /// </summary> /// <param name="requestId">The request ID.</param> [ReactMethod] public void abortRequest(int requestId) { _tasks.Cancel(requestId); } /// <summary> /// Called before a <see cref="IReactInstance"/> is disposed. /// </summary> public override Task OnReactInstanceDisposeAsync() { _shuttingDown = true; _tasks.CancelAllTasks(); _client.Dispose(); //return Task.CompletedTask; return Net46.Net45.Task.CompletedTask; } private async Task ProcessRequestFromUriAsync( int requestId, Uri uri, HttpContentHeaderData headerData, bool useIncrementalUpdates, int timeout, HttpRequestMessage request, string responseType, CancellationToken token) { try { #if WINDOWS_UWP var storageFile = await StorageFile.GetFileFromPathAsync(uri.LocalPath).AsTask().ConfigureAwait(false); var inputStream = await storageFile.OpenReadAsync().AsTask().ConfigureAwait(false); #else var storageFile = await FileSystem.Current.GetFileFromPathAsync(uri.ToString()).ConfigureAwait(false); var input = await storageFile.ReadAllTextAsync().ConfigureAwait(false); var byteArray = Encoding.UTF8.GetBytes(input); var inputStream = new MemoryStream(byteArray); #endif request.Content = new HttpStreamContent(inputStream); request.Content.Headers.ContentType = new HttpMediaTypeHeaderValue(headerData.ContentType); await ProcessRequestAsync( requestId, useIncrementalUpdates, timeout, request, responseType, token).ConfigureAwait(false); } catch(Exception ex) { if (_shuttingDown) { return; } OnRequestError(requestId, ex.Message, false); } } private async Task ProcessRequestAsync( int requestId, bool useIncrementalUpdates, int timeout, HttpRequestMessage request, string responseType, CancellationToken token) { var timeoutSource = timeout > 0 ? new CancellationTokenSource(timeout) : new CancellationTokenSource(); using (timeoutSource) { try { using (token.Register(timeoutSource.Cancel)) using (var response = await _client.SendRequestAsync(request, timeoutSource.Token).ConfigureAwait(false)) { OnResponseReceived(requestId, response); if (useIncrementalUpdates && responseType == "text") { #if WINDOWS_UWP var length = response.Content.Headers.ContentLength; var inputStream = await response.Content.ReadAsInputStreamAsync().AsTask(token).ConfigureAwait(false); var stream = inputStream.AsStreamForRead(); #else var length = (ulong?)response.Content.Headers.ContentLength; var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); #endif using (stream) { await ProcessResponseIncrementalAsync(requestId, stream, length, timeoutSource.Token).ConfigureAwait(false); OnRequestSuccess(requestId); } #if WINDOWS_UWP inputStream.Dispose(); #endif } else { if (response.Content != null) { if (responseType == "text") { #if WINDOWS_UWP string responseBody; var responseInputStream = await response.Content.ReadAsInputStreamAsync().AsTask(token).ConfigureAwait(false); using (var responseStream = responseInputStream.AsStreamForRead()) using (var responseStreamReader = new StreamReader(responseStream)) { responseBody = await responseStreamReader.ReadToEndAsync().ConfigureAwait(false); } #else var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); #endif if (responseBody != null) { OnDataReceived(requestId, responseBody); } } else { Debug.Assert(responseType == "base64"); #if WINDOWS_UWP byte[] responseBytes; var responseInputStream = await response.Content.ReadAsInputStreamAsync().AsTask(token).ConfigureAwait(false); using (var memoryStream = new MemoryStream()) using (var responseStream = responseInputStream.AsStreamForRead()) { await responseStream.CopyToAsync(memoryStream); responseBytes = memoryStream.ToArray(); } #else var responseBytes = await response.Content.ReadAsByteArrayAsync(); #endif OnDataReceived(requestId, Convert.ToBase64String(responseBytes)); } } OnRequestSuccess(requestId); } } } catch (OperationCanceledException ex) when (ex.CancellationToken == timeoutSource.Token) { // Cancellation was due to timeout if (!token.IsCancellationRequested) { OnRequestError(requestId, ex.Message, true); } } catch (Exception ex) { if (_shuttingDown) { return; } OnRequestError(requestId, ex.Message, false); } } } private async Task ProcessResponseIncrementalAsync(int requestId, Stream stream, ulong? length, CancellationToken token) { using (var reader = new StreamReader(stream, Encoding.UTF8, true, MaxChunkSizeBetweenFlushes, true)) { var buffer = new char[MaxChunkSizeBetweenFlushes]; var read = default(int); var progress = 0; var total = length.HasValue ? (long)length : -1; while ((read = await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) { progress += read; OnIncrementalDataReceived(requestId, new string(buffer, 0, read), progress, total); } } } private void OnResponseReceived(int requestId, HttpResponseMessage response) { var headerData = new JObject(); #if WINDOWS_UWP var responseHeaders = response.Headers; #else var responseHeaders = response.Headers.Select(pair => new KeyValuePair<string, string>(pair.Key, string.Join(", ", pair.Value))); #endif TranslateHeaders(headerData, responseHeaders); if (response.Content != null) { #if WINDOWS_UWP var responseContentHeaders = response.Content.Headers; #else var responseContentHeaders = response.Content.Headers.Select(pair => new KeyValuePair<string, string>(pair.Key, string.Join(", ", pair.Value))); #endif TranslateHeaders(headerData, responseContentHeaders); } var args = new JArray { requestId, (int)response.StatusCode, headerData, response.RequestMessage.RequestUri.AbsoluteUri, }; EventEmitter.emit("didReceiveNetworkResponse", args); } private void OnIncrementalDataReceived(int requestId, string data, long progress, long total) { var args = new JArray { requestId, data, progress, total }; EventEmitter.emit("didReceiveNetworkIncrementalData", args); } private void OnDataReceived(int requestId, string responseBody) { EventEmitter.emit("didReceiveNetworkData", new JArray { requestId, responseBody, }); } private void OnRequestError(int requestId, string message, bool timeout) { EventEmitter.emit("didCompleteNetworkResponse", new JArray { requestId, message, timeout }); } private void OnRequestSuccess(int requestId) { EventEmitter.emit("didCompleteNetworkResponse", new JArray { requestId, null, }); } private static bool HasRequestContent(JObject data) { return data.ContainsKey("string") || data.ContainsKey("base64") || data.ContainsKey("uri"); } private static void ApplyHeaders(HttpRequestMessage request, string[][] headers) { foreach (var header in headers) { var key = header[0]; switch (key.ToLowerInvariant()) { #if WINDOWS_UWP case "authorization": var authParts = header[1].Trim().Split(new[] { ' ' }, 2); if (authParts.Length == 2) { request.Headers.Authorization = new HttpCredentialsHeaderValue(authParts[0].Trim(), authParts[1].Trim()); } else { request.Headers.Add(key, header[1]); } break; #endif case "content-encoding": case "content-length": case "content-type": break; case "if-none-match": request.Headers.TryAddWithoutValidation(key, header[1]); break; default: request.Headers.Add(key, header[1]); break; } } } private static void TranslateHeaders(JObject headerData, IEnumerable<KeyValuePair<string, string>> headers) { foreach (var header in headers) { if (headerData.ContainsKey(header.Key)) { var existing = headerData[header.Key].Value<string>(); headerData[header.Key] = existing + ", " + header.Value; } else { headerData.Add(header.Key, header.Value); } } } private static IHttpClient CreateDefaultHttpClient() { #if WINDOWS_UWP return new DefaultHttpClient( new HttpClient( new HttpBaseProtocolFilter { AllowAutoRedirect = true, })); #else var httpClientHandler = new HttpClientHandler { Proxy = WebRequest.GetSystemWebProxy(), AllowAutoRedirect = false }; httpClientHandler.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials; var httpClient = new HttpClient(httpClientHandler); return new DefaultHttpClient(httpClient); #endif } } }
// 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.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; namespace OpenLiveWriter.ApplicationFramework { #region Public Delegates /// <summary> /// Represents the method that will handle the SplitterMoved event. /// </summary> public delegate void LightweightSplitterEventHandler(object sender, LightweightSplitterEventArgs e); #endregion Public Delegates /// <summary> /// Splitter lightweight control. Provides a horizontal or vertical splitter for use in a /// multipane window with resizable panes. /// </summary> public class SplitterLightweightControl : LightweightControl { #region Public Enumeration Declarations /// <summary> /// The splitter orientation: Horizontal or Vertical. /// </summary> public enum SplitterOrientation { Horizontal, Vertical } #endregion Public Enumeration Declarations #region Private Member Variables /// <summary> /// The splitter orientation. /// </summary> private SplitterOrientation orientation = SplitterOrientation.Horizontal; /// <summary> /// The starting position of a move. /// </summary> private int startingPosition; /// <summary> /// A value indicating whether the left mouse button is down. /// </summary> private bool leftMouseButtonDown = false; /// <summary> /// A value indicating whether the SplitterLightweightControl is enabled. /// </summary> private bool enabled = true; /// <summary> /// The layout rectangle for the attached control. /// </summary> private Rectangle attachedControlRectangle = new Rectangle(); /// <summary> /// The attached control. /// </summary> private LightweightControl _attachedControl; #endregion Private Member Variables #region Public Events /// <summary> /// Occurs when the splitter control begins a move operation. /// </summary> public event EventHandler SplitterBeginMove; /// <summary> /// Occurs when the splitter control ends a move operation. /// </summary> public event LightweightSplitterEventHandler SplitterEndMove; /// <summary> /// Occurs when the splitter control is moving. /// </summary> public event LightweightSplitterEventHandler SplitterMoving; #endregion Public Events #region Class Initialization & Termination /// <summary> /// Initializes a new instance of the SplitterLightweightControl class. /// </summary> /// <param name="container"></param> public SplitterLightweightControl(IContainer container) { /// <summary> /// Required for Windows.Forms Class Composition Designer support /// </summary> container.Add(this); InitializeComponent(); } /// <summary> /// Initializes a new instance of the SplitterLightweightControl class. /// </summary> public SplitterLightweightControl() { /// <summary> /// Required for Windows.Forms Class Composition Designer support /// </summary> InitializeComponent(); } #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() { } #endregion #region Public Properties /// <summary> /// Gets or sets the splitter orientation. /// </summary> [ Category("Design"), Localizable(false), DefaultValue(SplitterOrientation.Horizontal), Description("Specifies the the splitter orientation.") ] public SplitterOrientation Orientation { get { return orientation; } set { orientation = value; } } /// <summary> /// Gets or sets the splitter orientation. /// </summary> [ Category("Behavior"), Localizable(false), DefaultValue(true), Description("Specifies whether the splitter is initially enabled.") ] public bool Enabled { get { return enabled; } set { enabled = value; } } /// <summary> /// Gets or set the LightweightControl attached to the center of the splitter bar. /// </summary> public LightweightControl AttachedControl { get { return _attachedControl; } set { if (_attachedControl != value) { if (_attachedControl != null) { LightweightControls.Remove(_attachedControl); _attachedControl.MouseDown -= new MouseEventHandler(_attachedControl_MouseDown); _attachedControl.MouseEnter -= new EventHandler(_attachedControl_MouseEnter); _attachedControl.MouseLeave -= new EventHandler(_attachedControl_MouseLeave); _attachedControl.MouseMove -= new MouseEventHandler(_attachedControl_MouseMove); _attachedControl.MouseUp -= new MouseEventHandler(_attachedControl_MouseUp); } _attachedControl = value; if (_attachedControl != null) { LightweightControls.Add(_attachedControl); _attachedControl.MouseDown += new MouseEventHandler(_attachedControl_MouseDown); _attachedControl.MouseEnter += new EventHandler(_attachedControl_MouseEnter); _attachedControl.MouseLeave += new EventHandler(_attachedControl_MouseLeave); _attachedControl.MouseMove += new MouseEventHandler(_attachedControl_MouseMove); _attachedControl.MouseUp += new MouseEventHandler(_attachedControl_MouseUp); } PerformLayout(); Invalidate(); } } } #endregion Public Properties #region Protected Events /// <summary> /// Raises the SplitterBeginMove event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected virtual void OnSplitterBeginMove(EventArgs e) { if (SplitterBeginMove != null) SplitterBeginMove(this, e); } /// <summary> /// Raises the SplitterEndMove event. /// </summary> /// <param name="e">A LightweightSplitterEventArgs that contains the event data.</param> protected virtual void OnSplitterEndMove(LightweightSplitterEventArgs e) { if (SplitterEndMove != null) SplitterEndMove(this, e); } /// <summary> /// Raises the SplitterMoving event. /// </summary> /// <param name="e">A LightweightSplitterEventArgs that contains the event data.</param> protected virtual void OnSplitterMoving(LightweightSplitterEventArgs e) { if (SplitterMoving != null) SplitterMoving(this, e); } #endregion Protected Events #region Protected Event Overrides /// <summary> /// Handles the layout event. /// </summary> /// <param name="e"></param> protected override void OnLayout(EventArgs e) { base.OnLayout(e); //If a control is attached to the splitter, lay it out. if (AttachedControl != null) { // No layout required if this control is not visible. if (Parent == null || Parent.Parent == null) return; // Layout the expand control. attachedControlRectangle = new Rectangle(Utility.CenterMinZero(AttachedControl.DefaultVirtualSize.Width, VirtualWidth), Utility.CenterMinZero(AttachedControl.DefaultVirtualSize.Height, VirtualHeight), AttachedControl.DefaultVirtualSize.Width, VirtualHeight); AttachedControl.VirtualBounds = attachedControlRectangle; AttachedControl.PerformLayout(); } } /// <summary> /// Raises the MouseDown event. /// </summary> /// <param name="e">A MouseEventArgs that contains the event data</param> protected override void OnMouseDown(MouseEventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnMouseDown(e); // Ignore the event if the splitter is disabled. if (!enabled) return; // If the mouse button is the left button, begin a splitter resize. if (e.Button == MouseButtons.Left) { // Note that the left mouse button is down. leftMouseButtonDown = true; // Note the starting position. startingPosition = (orientation == SplitterOrientation.Vertical) ? e.X : e.Y; // Raise the SplitterBeginMove event. OnSplitterBeginMove(EventArgs.Empty); } } /// <summary> /// Raises the MouseEnter event. /// </summary> /// <param name="e">An EventArgs that contains the event data</param> protected override void OnMouseEnter(EventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnMouseEnter(e); // Ignore the event if the splitter is disabled. if (!enabled) return; // Ensure that the left mouse button isn't down. Debug.Assert(!leftMouseButtonDown, "What?", "How can the left mouse button be down on mouse enter?"); // Turn on the splitter cursor. Parent.Cursor = (orientation == SplitterOrientation.Vertical) ? Cursors.VSplit : Cursors.HSplit; } /// <summary> /// Raises the MouseLeave event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected override void OnMouseLeave(EventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnMouseLeave(e); // Ignore the event if the splitter is disabled. if (!enabled) return; // If the left mouse button was down, end the resize operation. if (leftMouseButtonDown) { // Raise the event. OnSplitterEndMove(new LightweightSplitterEventArgs(0)); // The left mouse button is not down. leftMouseButtonDown = false; } // Turn off the splitter cursor. Parent.Cursor = Cursors.Default; } /// <summary> /// Raises the MouseMove event. /// </summary> /// <param name="e">A MouseEventArgs that contains the event data.</param> protected override void OnMouseMove(MouseEventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnMouseMove(e); // Ignore the event if the splitter is disabled. if (!enabled) return; // If the left mouse button is down, continue the resize operation. if (leftMouseButtonDown) { // If we have one or more registered delegates for the SplitterMoving event, raise // the event. if (SplitterMoving != null) { // Calculate the new position. int newPosition = ((orientation == SplitterOrientation.Vertical) ? e.X : e.Y) - startingPosition; // Raise the SplitterMoving event. OnSplitterMoving(new LightweightSplitterEventArgs(newPosition)); } } } /// <summary> /// Raises the MouseUp event. /// </summary> /// <param name="e">A MouseEventArgs that contains the event data.</param> protected override void OnMouseUp(MouseEventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnMouseUp(e); // Ignore the event if the splitter is disabled. if (!enabled) return; // If the left mouse button is down, end the resize operation. if (e.Button == MouseButtons.Left) { // Ensure that the left mouse button is down. Debug.Assert(leftMouseButtonDown, "What?", "Got a MouseUp that was unexpected."); if (leftMouseButtonDown) { // Obtain the new position. int newPosition = ((orientation == SplitterOrientation.Vertical) ? e.X : e.Y) - startingPosition; // Raise the event. OnSplitterEndMove(new LightweightSplitterEventArgs(newPosition)); // The left mouse button is not down. leftMouseButtonDown = false; } } } #endregion Protected Event Overrides #region Private Event Handlers /// <summary> /// Propogates the mouse event from the attached control. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _attachedControl_MouseDown(object sender, MouseEventArgs e) { OnMouseDown(e); } /// <summary> /// Propogates the mouse event from the attached control. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _attachedControl_MouseEnter(object sender, EventArgs e) { OnMouseEnter(e); } /// <summary> /// Propogates the mouse event from the attached control. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _attachedControl_MouseLeave(object sender, EventArgs e) { OnMouseLeave(e); } /// <summary> /// Propogates the mouse event from the attached control. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _attachedControl_MouseMove(object sender, MouseEventArgs e) { OnMouseMove(e); } /// <summary> /// Propogates the mouse event from the attached control. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _attachedControl_MouseUp(object sender, MouseEventArgs e) { OnMouseUp(e); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.CSharp.Formatting.Indentation; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { public class SmartIndenterEnterOnTokenTests : FormatterTestsBase { [WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBody1() { var code = @"class Class1 { void method() { } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor1() { var code = @"class A { #region T #endregion } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor2() { var code = @"class A { #line 1 #lien 2 } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor3() { var code = @"#region stuff #endregion "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 2, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Comments() { var code = @"using System; class Class { // Comments // Comments "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task UsingDirective() { var code = @"using System; using System.Linq; "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'u', indentationLine: 1, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task AfterTopOfFileComment() { var code = @"// comment class "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 2, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task DottedName() { var code = @"using System. Collection; "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 1, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Namespace() { var code = @"using System; namespace NS { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 3, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task NamespaceDottedName() { var code = @"using System; namespace NS. NS2 "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task NamespaceBody() { var code = @"using System; namespace NS { class "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'c', indentationLine: 4, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task NamespaceCloseBrace() { var code = @"using System; namespace NS { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 4, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Class() { var code = @"using System; namespace NS { class Class { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 5, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ClassBody() { var code = @"using System; namespace NS { class Class { int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 6, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ClassCloseBrace() { var code = @"using System; namespace NS { class Class { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 6, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Method() { var code = @"using System; namespace NS { class Class { void Method() { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 7, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBody() { var code = @"using System; namespace NS { class Class { void Method() { int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 8, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodCloseBrace() { var code = @"using System; namespace NS { class Class { void Method() { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 8, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Statement() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10; int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 9, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodCall() { var code = @"class c { void Method() { M( a: 1, b: 1); } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Switch() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 9, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task SwitchBody() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'c', indentationLine: 10, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task SwitchCase() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 11, expectedIndentation: 20); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task SwitchCaseBlock() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 11, expectedIndentation: 20); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Block() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : { int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 12, expectedIndentation: 24); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MultilineStatement1() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10 + 1 "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 9, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MultilineStatement2() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10 + 20 + 30 "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 10, expectedIndentation: 20); } // Bug number 902477 [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Comments2() { var code = @"class Class { void Method() { if (true) // Test int } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 5, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task AfterCompletedBlock() { var code = @"class Program { static void Main(string[] args) { foreach(var a in x) {} int } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 5, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task AfterTopLevelAttribute() { var code = @"class Program { [Attr] [ } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '[', indentationLine: 3, expectedIndentation: 4); } [WorkItem(537802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537802")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task EmbededStatement() { var code = @"class Program { static void Main(string[] args) { if (true) Console.WriteLine(1); int } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 6, expectedIndentation: 8); } [WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBraces1() { var code = @"class Class1 { void method() { } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 3, expectedIndentation: 4); } [WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBraces2() { var code = @"class Class1 { void method() { } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 4, expectedIndentation: 4); } [WorkItem(537795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537795")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Property1() { var code = @"class C { string Name { get; set; } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 6, expectedIndentation: 4); } [WorkItem(537563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537563")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Class1() { var code = @"class C { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 2, expectedIndentation: 0); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayInitializer1() { var code = @"class C { var a = new [] { 1, 2, 3 } } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayInitializer2() { var code = @"class C { var a = new [] { 1, 2, 3 } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 5, expectedIndentation: 4); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer3() { var code = @"namespace NS { class Class { void Method(int i) { var a = new [] { }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 7, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task QueryExpression2() { var code = @"class C { void Method() { var a = from c in b where } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'w', indentationLine: 5, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task QueryExpression3() { var code = @"class C { void Method() { var a = from c in b where select } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'w', indentationLine: 5, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task QueryExpression4() { var code = @"class C { void Method() { var a = from c in b where c > 10 select } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 's', indentationLine: 5, expectedIndentation: 16); } [WpfFact] [WorkItem(853748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853748")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayInitializer() { var code = @"class C { void Method() { var l = new int[] { } } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(939305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939305")] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayExpression() { var code = @"class C { void M(object[] q) { M( q: new object[] { }); } } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 6, expectedIndentation: 14); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task CollectionExpression() { var code = @"class C { void M(List<int> e) { M( new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 6, expectedIndentation: 12); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ObjectInitializer() { var code = @"class C { void M(What dd) { M( new What { d = 3, dd = "" }); } } class What { public int d; public string dd; }"; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 6, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor() { var code = @" #line 1 """"Bar""""class Foo : [|IComparable|]#line default#line hidden"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 1, expectedIndentation: 0); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_Implicit() { var code = @"class X { int[] a = { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_ImplicitNew() { var code = @"class X { int[] a = new[] { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_Explicit() { var code = @"class X { int[] a = new int[] { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_Collection() { var code = @"using System.Collections.Generic; class X { private List<int> a = new List<int>() { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 4, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_ObjectInitializers() { var code = @"class C { private What sdfsd = new What { d = 3, } } class What { public int d; public string dd; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_1() { var code = @"class Program { static void Main(string[] args) { var s = $@"" {Program.number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_2() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment {Program.number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_3() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number} ""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_4() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number}Comment here ""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task OutsideInterpolationString() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number}Comment here"" ; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_1() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ Program.number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_2() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ Program .number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 6, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_3() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ }""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_4() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_5() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_6() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })) .Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_7() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentLambdaBodyOneIndentationToFirstTokenOfTheStatement() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine(((Func<int, int>)((int s) => { return number; })).Invoke(3)); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(1339, "https://github.com/dotnet/roslyn/issues/1339")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentAutoPropertyInitializerAsPartOfTheDeclaration() { var code = @"class Program { public int d { get; } = 3; static void Main(string[] args) { } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentPatternPropertyFirst() { var code = @" class C { void Main(object o) { var y = o is Point { } } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 7, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentPatternPropertySecond() { var code = @" class C { void Main(object o) { var y = o is Point { X is 13, } } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 8, expectedIndentation: 12); } private async Task AssertIndentUsingSmartTokenFormatterAsync( string code, char ch, int indentationLine, int? expectedIndentation) { // create tree service using (var workspace = await TestWorkspace.CreateCSharpAsync(code)) { var hostdoc = workspace.Documents.First(); var buffer = hostdoc.GetTextBuffer(); var snapshot = buffer.CurrentSnapshot; var line = snapshot.GetLineFromLineNumber(indentationLine); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var root = (await document.GetSyntaxRootAsync()) as CompilationUnitSyntax; Assert.True( CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter( Formatter.GetDefaultFormattingRules(workspace, root.Language), root, line.AsTextLine(), document.Options, CancellationToken.None)); var actualIndentation = await GetSmartTokenFormatterIndentationWorkerAsync(workspace, buffer, indentationLine, ch); Assert.Equal(expectedIndentation.Value, actualIndentation); } } private async Task AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( string code, int indentationLine, int? expectedIndentation) { // create tree service using (var workspace = await TestWorkspace.CreateCSharpAsync(code)) { var hostdoc = workspace.Documents.First(); var buffer = hostdoc.GetTextBuffer(); var snapshot = buffer.CurrentSnapshot; var line = snapshot.GetLineFromLineNumber(indentationLine); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var root = (await document.GetSyntaxRootAsync()) as CompilationUnitSyntax; Assert.False( CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter( Formatter.GetDefaultFormattingRules(workspace, root.Language), root, line.AsTextLine(), document.Options, CancellationToken.None)); TestIndentation(indentationLine, expectedIndentation, workspace); } } } }
//------------------------------------------------------------------------------- // <copyright file="StandardFactory.cs" company="Appccelerate"> // Copyright (c) 2008-2020 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //------------------------------------------------------------------------------- namespace Appccelerate.EventBroker.Factories { using System; using System.Collections.Generic; using System.Reflection; using Appccelerate.EventBroker.Internals; using Appccelerate.EventBroker.Internals.GlobalMatchers; using Appccelerate.EventBroker.Internals.Inspection; using Appccelerate.EventBroker.Internals.Publications; using Appccelerate.EventBroker.Internals.Subscriptions; using Appccelerate.EventBroker.Matchers; using PropertyPublication = Appccelerate.EventBroker.Internals.Publications.PropertyPublication; /// <summary> /// Standard implementation for the <see cref="IFactory"/> interface. /// </summary> public class StandardFactory : IFactory { /// <summary> /// Gets the extension host holding all extensions. /// </summary> protected IExtensionHost ExtensionHost { get; private set; } /// <summary> /// Initializes this factory with the specified <paramref name="extensionHost"/> holding all extensions. /// </summary> /// <param name="extensionHost">The extension host holding all extensions (this is the event broker).</param> public virtual void Initialize(IExtensionHost extensionHost) { this.ExtensionHost = extensionHost; } /// <summary> /// Creates an event topic host. /// </summary> /// <param name="globalMatchersProvider">The global matchers provider.</param> /// <returns>A newly created event topic host.</returns> public virtual IEventTopicHost CreateEventTopicHost(IGlobalMatchersProvider globalMatchersProvider) { return new EventTopicHost(this, this.ExtensionHost, globalMatchersProvider); } /// <summary> /// Creates an event inspector. /// </summary> /// <returns>A newly created event inspector.</returns> public virtual IEventInspector CreateEventInspector() { return new EventInspector(this.ExtensionHost); } /// <summary> /// Creates a new event topic /// </summary> /// <param name="uri">The URI of the event topic.</param> /// <param name="globalMatchersProvider">The global matchers provider.</param> /// <returns>A newly created event topic</returns> public virtual IEventTopic CreateEventTopicInternal(string uri, IGlobalMatchersProvider globalMatchersProvider) { return new EventTopic(uri, this.ExtensionHost, globalMatchersProvider); } /// <summary> /// Creates a new publication /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="publisher">The publisher.</param> /// <param name="eventInfo">The event info.</param> /// <param name="handlerRestriction">The handler restriction.</param> /// <param name="publicationMatchers">The publication matchers.</param> /// <returns>A newly created publication</returns> public virtual IPublication CreatePublication( IEventTopicExecuter eventTopic, object publisher, EventInfo eventInfo, HandlerRestriction handlerRestriction, IList<IPublicationMatcher> publicationMatchers) { return new PropertyPublication(eventTopic, publisher, eventInfo, handlerRestriction, publicationMatchers); } /// <summary> /// Creates a new publication. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="publisher">The publisher.</param> /// <param name="eventHandler">The event handler.</param> /// <param name="handlerRestriction">The handler restriction.</param> /// <param name="publicationMatchers">The matchers.</param> /// <returns>A newly created publication</returns> public virtual IPublication CreatePublication( IEventTopicExecuter eventTopic, object publisher, ref EventHandler eventHandler, HandlerRestriction handlerRestriction, IList<IPublicationMatcher> publicationMatchers) { return new CodePublication<EventArgs>(eventTopic, publisher, ref eventHandler, handlerRestriction, publicationMatchers); } /// <summary> /// Creates a new publication. /// </summary> /// <typeparam name="TEventArgs">The type of the event arguments.</typeparam> /// <param name="eventTopic">The event topic.</param> /// <param name="publisher">The publisher.</param> /// <param name="eventHandler">The event handler.</param> /// <param name="handlerRestriction">The handler restriction.</param> /// <param name="publicationMatchers">The matchers.</param> /// <returns>A newly created publication</returns> public virtual IPublication CreatePublication<TEventArgs>( IEventTopicExecuter eventTopic, object publisher, ref EventHandler<TEventArgs> eventHandler, HandlerRestriction handlerRestriction, IList<IPublicationMatcher> publicationMatchers) where TEventArgs : EventArgs { return new CodePublication<TEventArgs>(eventTopic, publisher, ref eventHandler, handlerRestriction, publicationMatchers); } public virtual ISubscription CreateSubscription( object subscriber, DelegateWrapper delegateWrapper, IHandler handler, IList<ISubscriptionMatcher> subscriptionMatchers) { return new Subscription(subscriber, delegateWrapper, handler, subscriptionMatchers, this.ExtensionHost); } /// <summary> /// Creates a subscription execution handler. This handler defines on which thread the subscription is executed. /// </summary> /// <param name="handlerType">Type of the handler.</param> /// <returns>A new subscription execution handler.</returns> public virtual IHandler CreateHandler(Type handlerType) { Guard.AgainstNullArgument(nameof(handlerType), handlerType); AssertIsHandler(handlerType); return this.ActivateHandler(handlerType); } /// <summary> /// Creates a publication matcher. /// </summary> /// <param name="matcherType">Type of the matcher.</param> /// <returns> /// A newly created publication scope matcher. /// </returns> public virtual IPublicationMatcher CreatePublicationMatcher(Type matcherType) { Guard.AgainstNullArgument(nameof(matcherType), matcherType); AssertIsPublicationMatcher(matcherType); return this.ActivatePublicationMatcher(matcherType); } /// <summary> /// Creates a subscription scope matcher. /// </summary> /// <param name="matcherType">Type of the subscription matcher.</param> /// <returns> /// A newly create subscription scope matcher. /// </returns> public virtual ISubscriptionMatcher CreateSubscriptionMatcher(Type matcherType) { Guard.AgainstNullArgument(nameof(matcherType), matcherType); AssertIsSubscriptionMatcher(matcherType); return this.ActivateSubscriptionMatcher(matcherType); } /// <summary> /// Creates the global matchers host. /// </summary> /// <returns>A newly created global matchers host.</returns> public virtual IGlobalMatchersHost CreateGlobalMatchersHost() { return new GlobalMatchersHost(); } public virtual IEventRegistrar CreateRegistrar(IEventTopicHost eventTopicHost, IEventInspector eventInspector, IExtensionHost extensionHost) { return new Registrar(this, eventTopicHost, eventInspector, extensionHost); } /// <summary> /// Asserts that the given handler type implements <see cref="IHandler"/> and is a class. /// </summary> /// <param name="handlerType">Type of the handler to check.</param> protected static void AssertIsHandler(Type handlerType) { if (!handlerType.IsClass || !typeof(IHandler).IsAssignableFrom(handlerType)) { throw new ArgumentException("handlerType '" + handlerType + "' has to be a class implementing Appccelerate.EventBroker.IHandler."); } } /// <summary> /// Asserts that the given matcher type implements <see cref="ISubscriptionMatcher"/> and is a class. /// </summary> /// <param name="subscriptionMatcherType">Type of the matcher to check.</param> protected static void AssertIsSubscriptionMatcher(Type subscriptionMatcherType) { if (!subscriptionMatcherType.IsClass || !typeof(ISubscriptionMatcher).IsAssignableFrom(subscriptionMatcherType)) { throw new ArgumentException("MatcherType '" + subscriptionMatcherType + "' has to be a class implementing Appccelerate.EventBroker.Matchers.ISubscriptionMatcher."); } } /// <summary> /// Asserts that the given matcher type implements <see cref="IPublicationMatcher"/> and is a class. /// </summary> /// <param name="publicationMatcherType">Type of the matcher to check.</param> protected static void AssertIsPublicationMatcher(Type publicationMatcherType) { if (!publicationMatcherType.IsClass || !typeof(IPublicationMatcher).IsAssignableFrom(publicationMatcherType)) { throw new ArgumentException("MatcherType '" + publicationMatcherType + "' has to be a class implementing Appccelerate.EventBroker.ScopeMatchers.IPublicationMatcher."); } } /// <summary> /// Creates a new instance of a subscription matcher type. /// </summary> /// <remarks>Only called when subscription matcher assertions in /// <see cref="AssertIsSubscriptionMatcher"/> were successful.</remarks> /// <param name="subscriptionMatcherType">The subscription matcher type.</param> /// <returns>A new instance of <paramref name="subscriptionMatcherType"/>.</returns> protected virtual ISubscriptionMatcher ActivateSubscriptionMatcher(Type subscriptionMatcherType) { return (ISubscriptionMatcher)Activator.CreateInstance(subscriptionMatcherType); } /// <summary> /// Creates a new instance of a publication matcher type. /// </summary> /// <remarks>Only called when publication matcher assertions in /// <see cref="AssertIsPublicationMatcher"/> were successful.</remarks> /// <param name="publicationMatcherType">The publication matcher type.</param> /// <returns>A new instance of <paramref name="publicationMatcherType"/>.</returns> protected virtual IPublicationMatcher ActivatePublicationMatcher(Type publicationMatcherType) { return (IPublicationMatcher)Activator.CreateInstance(publicationMatcherType); } /// <summary> /// Creates a new instance of a handler type. /// </summary> /// <remarks>Only called when handler matcher assertions in /// <see cref="AssertIsHandler"/> were successful.</remarks> /// <param name="handlerType">The handler type.</param> /// <returns>A new instance of <paramref name="handlerType"/>.</returns> protected virtual IHandler ActivateHandler(Type handlerType) { return (IHandler)Activator.CreateInstance(handlerType); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using SIL.PlatformUtilities; namespace SIL.Reporting { public interface IErrorReporter { void ReportFatalException(Exception e); ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string alternateButton1Label, ErrorResult resultIfAlternateButtonPressed, string message); void ReportNonFatalException(Exception exception, IRepeatNoticePolicy policy); void ReportNonFatalExceptionWithMessage(Exception error, string message, params object[] args); void ReportNonFatalMessageWithStackTrace(string message, params object[] args); void ReportFatalMessageWithStackTrace(string message, object[] args); } public enum ErrorResult { None, OK, Cancel, Abort, Retry, Ignore, Yes, No } public class ErrorReport { #region Windows8PlusVersionReportingSupport [DllImport("netapi32.dll", CharSet = CharSet.Auto)] static extern int NetWkstaGetInfo(string server, int level, out IntPtr info); [DllImport("netapi32.dll")] static extern int NetApiBufferFree(IntPtr pBuf); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] struct MachineInfo { public int platform_id; [MarshalAs(UnmanagedType.LPWStr)] public string _computerName; [MarshalAs(UnmanagedType.LPWStr)] public string _languageGroup; public int _majorVersion; public int _minorVersion; } /// <summary> /// An application can avoid the need of this method by adding/modifying the application manifest to declare support for a /// particular windows version. This code is still necessary to report usefully about versions of windows released after /// the application has shipped. /// </summary> public static string GetWindowsVersionInfoFromNetworkAPI() { IntPtr pBuffer; // Get the version information from the network api, passing null to get network info from this machine var retval = NetWkstaGetInfo(null, 100, out pBuffer); if(retval != 0) return "Windows Unknown(unidentifiable)"; var info = (MachineInfo)Marshal.PtrToStructure(pBuffer, typeof(MachineInfo)); string windowsVersion = null; if(info._majorVersion == 6) { if(info._minorVersion == 2) windowsVersion = "Windows 8"; else if(info._minorVersion == 3) windowsVersion = "Windows 8.1"; } else if(info._majorVersion == 10 && info._minorVersion == 0) { windowsVersion = "Windows 10"; } else { windowsVersion = string.Format("Windows Unknown({0}.{1})", info._majorVersion, info._minorVersion); } NetApiBufferFree(pBuffer); return windowsVersion; } #endregion private static IErrorReporter _errorReporter; //We removed all references to Winforms from Palaso.dll but our error reporting relied heavily on it. //Not wanting to break existing applications we have now added this class initializer which will //look for a reference to SIL.Windows.Forms in the consuming app and if it exists instantiate the //WinformsErrorReporter from there through Reflection. otherwise we will simply use a console //error reporter static ErrorReport() { _errorReporter = ExceptionHandler.GetObjectFromSilWindowsForms<IErrorReporter>() ?? new ConsoleErrorReporter(); } /// <summary> /// Use this method if you want to override the default IErrorReporter. /// This method should normally be called only once at application startup. /// </summary> public static void SetErrorReporter(IErrorReporter reporter) { _errorReporter = reporter ?? new ConsoleErrorReporter(); } protected static string s_emailAddress = null; protected static string s_emailSubject = "Exception Report"; /// <summary> /// a list of name, string value pairs that will be included in the details of the error report. /// </summary> private static Dictionary<string, string> s_properties = new Dictionary<string, string>(); private static bool s_isOkToInteractWithUser = true; private static bool s_justRecordNonFatalMessagesForTesting=false; private static string s_previousNonFatalMessage; private static Exception s_previousNonFatalException; public static void Init(string emailAddress) { s_emailAddress = emailAddress; ErrorReport.AddStandardProperties(); } private static void UpdateEmailSubject(Exception error) { var subject = new StringBuilder(); subject.AppendFormat("Exception: {0}", error.Message); try { subject.AppendFormat(" in {0}", error.Source); } catch {} s_emailSubject = subject.ToString(); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// <param name="error"></param> /// <returns></returns> /// ------------------------------------------------------------------------------------ public static string GetExceptionText(Exception error) { UpdateEmailSubject(error); return ExceptionHelper.GetExceptionText(error); } public static string GetVersionForErrorReporting() { Assembly assembly = Assembly.GetEntryAssembly(); if (assembly != null) { string version = VersionNumberString; version += " (apparent build date: "; try { string path = assembly.CodeBase.Replace(@"file://", ""); if (Platform.IsWindows) path = path.TrimStart('/'); version += File.GetLastWriteTimeUtc(path).ToString("dd-MMM-yyyy") + ")"; } catch { version += "???"; } #if DEBUG version += " (Debug version)"; #endif return version; } return "unknown"; } public static object GetAssemblyAttribute(Type attributeType) { Assembly assembly = Assembly.GetEntryAssembly(); if (assembly != null) { object[] attributes = assembly.GetCustomAttributes(attributeType, false); if (attributes != null && attributes.Length > 0) { return attributes[0]; } } return null; } public static string VersionNumberString { get { /* object attr = GetAssemblyAttribute(typeof (AssemblyFileVersionAttribute)); if (attr != null) { return ((AssemblyFileVersionAttribute) attr).Version; } return Application.ProductVersion; */ var ver = Assembly.GetEntryAssembly().GetName().Version; return string.Format("Version {0}.{1}.{2}", ver.Major, ver.Minor, ver.Build); } } public static string UserFriendlyVersionString { get { var asm = Assembly.GetEntryAssembly(); var ver = asm.GetName().Version; var file = asm.CodeBase.Replace("file://", string.Empty); if (Platform.IsWindows) file = file.TrimStart('/'); var fi = new FileInfo(file); return string.Format( "Version {0}.{1}.{2} Built on {3}", ver.Major, ver.Minor, ver.Build, fi.CreationTime.ToString("dd-MMM-yyyy") ); } } /// <summary> /// use this in unit tests to cleanly check that a message would have been shown. /// E.g. using (new Palaso.Reporting.ErrorReport.NonFatalErrorReportExpected()) {...} /// </summary> public class NonFatalErrorReportExpected :IDisposable { private readonly bool previousJustRecordNonFatalMessagesForTesting; public NonFatalErrorReportExpected() { previousJustRecordNonFatalMessagesForTesting = s_justRecordNonFatalMessagesForTesting; s_justRecordNonFatalMessagesForTesting = true; s_previousNonFatalMessage = null;//this is a static, so a previous unit test could have filled it with something (yuck) } public void Dispose() { s_justRecordNonFatalMessagesForTesting= previousJustRecordNonFatalMessagesForTesting; if (s_previousNonFatalException == null && s_previousNonFatalMessage == null) throw new Exception("Non Fatal Error Report was expected but wasn't generated."); s_previousNonFatalMessage = null; } /// <summary> /// use this to check the actual contents of the message that was triggered /// </summary> public string Message { get { return s_previousNonFatalMessage; } } } /// <summary> /// use this in unit tests to cleanly check that a message would have been shown. /// E.g. using (new Palaso.Reporting.ErrorReport.NonFatalErrorReportExpected()) {...} /// </summary> public class NoNonFatalErrorReportExpected : IDisposable { private readonly bool previousJustRecordNonFatalMessagesForTesting; public NoNonFatalErrorReportExpected() { previousJustRecordNonFatalMessagesForTesting = s_justRecordNonFatalMessagesForTesting; s_justRecordNonFatalMessagesForTesting = true; s_previousNonFatalMessage = null;//this is a static, so a previous unit test could have filled it with something (yuck) s_previousNonFatalException = null; } public void Dispose() { s_justRecordNonFatalMessagesForTesting = previousJustRecordNonFatalMessagesForTesting; if (s_previousNonFatalException != null || s_previousNonFatalMessage != null) throw new Exception("Non Fatal Error Report was not expected but was generated: "+Message); s_previousNonFatalMessage = null; } /// <summary> /// use this to check the actual contents of the message that was triggered /// </summary> public string Message { get { return s_previousNonFatalMessage; } } } /// <summary> /// set this property if you want the dialog to offer to create an e-mail message. /// </summary> public static string EmailAddress { set { s_emailAddress = value; } get { return s_emailAddress; } } /// <summary> /// set this property if you want something other than the default e-mail subject /// </summary> public static string EmailSubject { set { s_emailSubject = value; } get { return s_emailSubject; } } /// <summary> /// a list of name, string value pairs that will be included in the details of the error report. /// </summary> public static Dictionary<string, string> Properties { get { return s_properties; } set { s_properties = value; } } public static bool IsOkToInteractWithUser { get { return s_isOkToInteractWithUser; } set { s_isOkToInteractWithUser = value; } } /// ------------------------------------------------------------------------------------ /// <summary> /// add a property that he would like included in any bug reports created by this application. /// </summary> /// ------------------------------------------------------------------------------------ public static void AddProperty(string label, string contents) { //avoid an error if the user changes the value of something, //which happens in FieldWorks, for example, when you change the language project. if (s_properties.ContainsKey(label)) { s_properties.Remove(label); } s_properties.Add(label, contents); } public static void AddStandardProperties() { AddProperty("Version", ErrorReport.GetVersionForErrorReporting()); AddProperty("CommandLine", Environment.CommandLine); AddProperty("CurrentDirectory", Environment.CurrentDirectory); AddProperty("MachineName", Environment.MachineName); AddProperty("OSVersion", GetOperatingSystemLabel()); if (Platform.IsUnix) AddProperty("DesktopEnvironment", Platform.DesktopEnvironmentInfoString); AddProperty("DotNetVersion", Environment.Version.ToString()); AddProperty("WorkingSet", Environment.WorkingSet.ToString()); AddProperty("UserDomainName", Environment.UserDomainName); AddProperty("UserName", Environment.UserName); AddProperty("Culture", CultureInfo.CurrentCulture.ToString()); } /// <summary> /// Get the standard properties in a form suitable for other uses /// (such as analytics). /// </summary> public static Dictionary<string, string> GetStandardProperties() { var props = new Dictionary<string,string>(); props.Add("Version", ErrorReport.GetVersionForErrorReporting()); props.Add("CommandLine", Environment.CommandLine); props.Add("CurrentDirectory", Environment.CurrentDirectory); props.Add("MachineName", Environment.MachineName); props.Add("OSVersion", GetOperatingSystemLabel()); if (Platform.IsUnix) props.Add("DesktopEnvironment", Platform.DesktopEnvironmentInfoString); props.Add("DotNetVersion", Environment.Version.ToString()); props.Add("WorkingSet", Environment.WorkingSet.ToString()); props.Add("UserDomainName", Environment.UserDomainName); props.Add("UserName", Environment.UserName); props.Add("Culture", CultureInfo.CurrentCulture.ToString()); return props; } class Version { private readonly PlatformID _platform; private readonly int _major; private readonly int _minor; public string Label { get; private set; } public Version(PlatformID platform, int major, int minor, string label) { _platform = platform; _major = major; _minor = minor; Label = label; } public bool Match(OperatingSystem os) { return os.Version.Minor == _minor && os.Version.Major == _major && os.Platform == _platform; } } public static string GetOperatingSystemLabel() { if (Environment.OSVersion.Platform == PlatformID.Unix) { var startInfo = new ProcessStartInfo("lsb_release", "-si -sr -sc"); startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; var proc = new Process { StartInfo = startInfo }; try { proc.Start(); proc.WaitForExit(500); if(proc.ExitCode == 0) { var si = proc.StandardOutput.ReadLine(); var sr = proc.StandardOutput.ReadLine(); var sc = proc.StandardOutput.ReadLine(); return String.Format("{0} {1} {2}", si, sr, sc); } } catch (Exception) { // lsb_release should work on all supported versions but fall back to the OSVersion.VersionString } } else { // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832%28v=vs.85%29.aspx var list = new List<Version>(); list.Add(new Version(PlatformID.Win32NT, 5, 0, "Windows 2000")); list.Add(new Version(PlatformID.Win32NT, 5, 1, "Windows XP")); list.Add(new Version(PlatformID.Win32NT, 6, 0, "Vista")); list.Add(new Version(PlatformID.Win32NT, 6, 1, "Windows 7")); // After Windows 8 the Environment.OSVersion started misreporting information unless // your app has a manifest which says it supports the OS it is running on. This is not // helpful if someone starts using an app built before the OS is released. Anything that // reports its self as Windows 8 is suspect, and must get the version info another way. list.Add(new Version(PlatformID.Win32NT, 6, 3, "Windows 8.1")); list.Add(new Version(PlatformID.Win32NT, 10, 0, "Windows 10")); foreach (var version in list) { if (version.Match(Environment.OSVersion)) return version.Label + " " + Environment.OSVersion.ServicePack; } // Handle any as yet unrecognized (possibly unmanifested) versions, or anything that reported its self as Windows 8. if(Environment.OSVersion.Platform == PlatformID.Win32NT) { return GetWindowsVersionInfoFromNetworkAPI() + " " + Environment.OSVersion.ServicePack; } } return Environment.OSVersion.VersionString; } public static string GetHiearchicalExceptionInfo(Exception error, ref Exception innerMostException) { UpdateEmailSubject(error); return ExceptionHelper.GetHiearchicalExceptionInfo(error, ref innerMostException); } public static void ReportFatalException(Exception error) { UsageReporter.ReportException(true, null, error, null); _errorReporter.ReportFatalException(error); } /// <summary> /// Put up a message box, unless OkToInteractWithUser is false, in which case throw an Appliciation Exception. /// This will not report the problem to the developer. Use one of the "report" methods for that. /// </summary> public static void NotifyUserOfProblem(string message, params object[] args) { NotifyUserOfProblem(new ShowAlwaysPolicy(), message, args); } public static ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string messageFmt, params object[] args) { return NotifyUserOfProblem(policy, null, default(ErrorResult), messageFmt, args); } public static void NotifyUserOfProblem(Exception error, string messageFmt, params object[] args) { NotifyUserOfProblem(new ShowAlwaysPolicy(), error, messageFmt, args); } public static void NotifyUserOfProblem(IRepeatNoticePolicy policy, Exception error, string messageFmt, params object[] args) { var result = NotifyUserOfProblem(policy, "Details", ErrorResult.Yes, messageFmt, args); if (result == ErrorResult.Yes) { ErrorReport.ReportNonFatalExceptionWithMessage(error, string.Format(messageFmt, args)); } UsageReporter.ReportException(false, null, error, String.Format(messageFmt, args)); } public static ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string alternateButton1Label, ErrorResult resultIfAlternateButtonPressed, string messageFmt, params object[] args) { var message = string.Format(messageFmt, args); if (s_justRecordNonFatalMessagesForTesting) { s_previousNonFatalMessage = message; return ErrorResult.OK; } return _errorReporter.NotifyUserOfProblem(policy, alternateButton1Label, resultIfAlternateButtonPressed, message); } /// <summary> /// Bring up a "yellow box" that let's them send in a report, then return to the program. /// </summary> public static void ReportNonFatalExceptionWithMessage(Exception error, string message, params object[] args) { s_previousNonFatalMessage = message; s_previousNonFatalException = error; _errorReporter.ReportNonFatalExceptionWithMessage(error, message, args); } /// <summary> /// Bring up a "yellow box" that let's them send in a report, then return to the program. /// Use this one only when you don't have an exception (else you're not reporting the exception's message) /// </summary> public static void ReportNonFatalMessageWithStackTrace(string message, params object[] args) { s_previousNonFatalMessage = message; _errorReporter.ReportNonFatalMessageWithStackTrace(message, args); } /// <summary> /// Bring up a "green box" that let's them send in a report, then exit. /// </summary> public static void ReportFatalMessageWithStackTrace(string message, params object[] args) { _errorReporter.ReportFatalMessageWithStackTrace(message, args); } /// <summary> /// Bring up a "yellow box" that lets them send in a report, then return to the program. /// </summary> public static void ReportNonFatalException(Exception exception) { ReportNonFatalException(exception, new ShowAlwaysPolicy()); } /// <summary> /// Allow user to report an exception even though the program doesn't need to exit /// </summary> public static void ReportNonFatalException(Exception exception, IRepeatNoticePolicy policy) { if (s_justRecordNonFatalMessagesForTesting) { ErrorReport.s_previousNonFatalException = exception; return; } _errorReporter.ReportNonFatalException(exception, policy); UsageReporter.ReportException(false, null, exception, null); } /// <summary> /// this is for interacting with test code which doesn't want to allow an actual UI /// </summary> public class ProblemNotificationSentToUserException : ApplicationException { public ProblemNotificationSentToUserException(string message) : base(message) {} } /// <summary> /// this is for interacting with test code which doesn't want to allow an actual UI /// </summary> public class NonFatalExceptionWouldHaveBeenMessageShownToUserException : ApplicationException { public NonFatalExceptionWouldHaveBeenMessageShownToUserException(Exception e) : base(e.Message, e) { } } } public interface IRepeatNoticePolicy { bool ShouldShowErrorReportDialog(Exception exception); bool ShouldShowMessage(string message); string ReoccurenceMessage { get; } } public class ShowAlwaysPolicy :IRepeatNoticePolicy { public bool ShouldShowErrorReportDialog(Exception exception) { return true; } public bool ShouldShowMessage(string message) { return true; } public string ReoccurenceMessage { get { return string.Empty; } } } public class ShowOncePerSessionBasedOnExactMessagePolicy :IRepeatNoticePolicy { private static List<string> _alreadyReportedMessages = new List<string>(); public bool ShouldShowErrorReportDialog(Exception exception) { return ShouldShowMessage(exception.Message); } public bool ShouldShowMessage(string message) { if(_alreadyReportedMessages.Contains(message)) return false; _alreadyReportedMessages.Add(message); return true; } public string ReoccurenceMessage { get { return "This message will not be shown again this session."; } } public static void Reset() { _alreadyReportedMessages.Clear(); } } }
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; /* GoogleAnalyticsMPV3 handles building hits using the Measurement Protocol. Developers should call the methods in GoogleAnalyticsV3, which will call the appropriate methods in this class if the application is built for platforms other than Android and iOS. */ public class GoogleAnalyticsMPV3 { #if UNITY_ANDROID && !UNITY_EDITOR #elif UNITY_IPHONE && !UNITY_EDITOR #else private string trackingCode; private string bundleIdentifier; private string appName; private string appVersion; private GoogleAnalyticsV3.DebugMode logLevel; private bool anonymizeIP; private bool dryRun; private bool optOut; private int sessionTimeout; private string screenRes; private string clientId; private string url; private float timeStarted; private Dictionary<Field, object> trackerValues = new Dictionary<Field, object>(); private bool startSessionOnNextHit = false; private bool endSessionOnNextHit = false; private bool trackingCodeSet = true; public void InitializeTracker() { if(String.IsNullOrEmpty(trackingCode)){ Debug.Log("No tracking code set for 'Other' platforms - hits will not be set"); trackingCodeSet = false; return; } if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.INFO)) { Debug.Log("Platform is not Android or iOS - " + "hits will be sent using measurement protocol."); } screenRes = Screen.width + "x" + Screen.height; clientId = SystemInfo.deviceUniqueIdentifier; string language = Application.systemLanguage.ToString(); optOut = false; #if !UNITY_WP8 CultureInfo[] cultureInfos = CultureInfo.GetCultures(CultureTypes.AllCultures); foreach (CultureInfo info in cultureInfos) { if (info.EnglishName == Application.systemLanguage.ToString()) { language = info.Name; } } #endif try { url = "https://www.google-analytics.com/collect?v=1" + AddRequiredMPParameter(Fields.LANGUAGE, language) + AddRequiredMPParameter(Fields.SCREEN_RESOLUTION, screenRes) + AddRequiredMPParameter(Fields.APP_NAME, appName) + AddRequiredMPParameter(Fields.TRACKING_ID, trackingCode) + AddRequiredMPParameter(Fields.APP_ID, bundleIdentifier) + AddRequiredMPParameter(Fields.CLIENT_ID, clientId) + AddRequiredMPParameter(Fields.APP_VERSION, appVersion); if(anonymizeIP){ url += AddOptionalMPParameter(Fields.ANONYMIZE_IP, 1); } if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) { Debug.Log("Base URL for hits: " + url); } } catch (Exception) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.Log("Error building url."); } } } public void SetTrackerVal(Field field, object value) { trackerValues[field] = value; } private string AddTrackerVals() { if(!trackingCodeSet){ return ""; } string vals = ""; foreach (KeyValuePair<Field, object> pair in trackerValues){ vals += AddOptionalMPParameter(pair.Key, pair.Value); } return vals; } internal void StartSession() { startSessionOnNextHit = true; } internal void StopSession() { endSessionOnNextHit = true; } private void SendGaHitWithMeasurementProtocol(string url) { if (String.IsNullOrEmpty(url)) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.Log("No tracking code set for 'Other' platforms - hit will not be sent."); } return; } if (dryRun || optOut) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.Log("Dry run or opt out enabled - hits will not be sent."); } return; } if (startSessionOnNextHit) { url += AddOptionalMPParameter(Fields.SESSION_CONTROL, "start"); startSessionOnNextHit = false; } else if (endSessionOnNextHit) { url += AddOptionalMPParameter(Fields.SESSION_CONTROL, "end"); endSessionOnNextHit = false; } // Add random z to avoid caching string newUrl = url + "&z=" + UnityEngine.Random.Range(0, 500); if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) { Debug.Log(newUrl); } GoogleAnalyticsV3.getInstance().StartCoroutine(this.HandleWWW(new WWW(newUrl))); } /* Make request using yield and coroutine to prevent lock up waiting on request to return. */ public IEnumerator HandleWWW(WWW request) { while (!request.isDone) { yield return request; if (request.responseHeaders.ContainsKey("STATUS")) { if (request.responseHeaders["STATUS"].Contains("200 OK")) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.INFO)) { Debug.Log("Successfully sent Google Analytics hit."); } } else { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.LogWarning("Google Analytics hit request rejected with " + "status code " + request.responseHeaders["STATUS"]); } } } else { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.LogWarning("Google Analytics hit request failed with error " + request.error); } } } } private string AddRequiredMPParameter(Field parameter, object value) { if(!trackingCodeSet){ return ""; } else if (value == null) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.LogWarning("Value was null for required parameter " + parameter + ". Hit cannot be sent"); } throw new ArgumentNullException(); } else { return parameter + "=" + WWW.EscapeURL(value.ToString()); } } private string AddRequiredMPParameter(Field parameter, string value) { if(!trackingCodeSet){ return ""; } else if (value == null) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.LogWarning("Value was null for required parameter " + parameter + ". Hit cannot be sent"); } throw new ArgumentNullException(); } else { return parameter + "=" + WWW.EscapeURL(value); } } private string AddOptionalMPParameter(Field parameter, object value) { if (value == null || !trackingCodeSet) { return ""; } else { return parameter + "=" + WWW.EscapeURL(value.ToString()); } } private string AddOptionalMPParameter(Field parameter, string value) { if (String.IsNullOrEmpty(value) || !trackingCodeSet) { return ""; } else { return parameter + "=" + WWW.EscapeURL(value); } } private string AddCustomVariables<T>(HitBuilder<T> builder) { if(!trackingCodeSet){ return ""; } String url = ""; foreach(KeyValuePair<int, string> entry in builder.GetCustomDimensions()) { if (entry.Value != null) { url += Fields.CUSTOM_DIMENSION.ToString() + entry.Key + "=" + WWW.EscapeURL(entry.Value.ToString()); } } foreach(KeyValuePair<int, string> entry in builder.GetCustomMetrics()) { if (entry.Value != null) { url += Fields.CUSTOM_METRIC.ToString() + entry.Key + "=" + WWW.EscapeURL(entry.Value.ToString()); } } if(!String.IsNullOrEmpty(url)){ if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) { Debug.Log("Added custom variables to hit."); } } return url; } private string AddCampaignParameters<T>(HitBuilder<T> builder) { if(!trackingCodeSet){ return ""; } String url = ""; url += AddOptionalMPParameter(Fields.CAMPAIGN_NAME, builder.GetCampaignName()); url += AddOptionalMPParameter(Fields.CAMPAIGN_SOURCE, builder.GetCampaignSource()); url += AddOptionalMPParameter(Fields.CAMPAIGN_MEDIUM, builder.GetCampaignMedium()); url += AddOptionalMPParameter(Fields.CAMPAIGN_KEYWORD, builder.GetCampaignKeyword()); url += AddOptionalMPParameter(Fields.CAMPAIGN_CONTENT, builder.GetCampaignContent()); url += AddOptionalMPParameter(Fields.CAMPAIGN_ID, builder.GetCampaignID()); url += AddOptionalMPParameter(Fields.GCLID, builder.GetGclid()); url += AddOptionalMPParameter(Fields.DCLID, builder.GetDclid()); if(!String.IsNullOrEmpty(url)){ if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) { Debug.Log("Added campaign parameters to hit. url:" + url); } } return url; } public void LogScreen(AppViewHitBuilder builder) { trackerValues[Fields.SCREEN_NAME] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "appview") + AddRequiredMPParameter(Fields.SCREEN_NAME, builder.GetScreenName()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void LogEvent(EventHitBuilder builder) { trackerValues[Fields.EVENT_CATEGORY] = null; trackerValues[Fields.EVENT_ACTION] = null; trackerValues[Fields.EVENT_LABEL] = null; trackerValues[Fields.EVENT_VALUE] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "event") + AddOptionalMPParameter(Fields.EVENT_CATEGORY, builder.GetEventCategory()) + AddOptionalMPParameter(Fields.EVENT_ACTION, builder.GetEventAction()) + AddOptionalMPParameter(Fields.EVENT_LABEL, builder.GetEventLabel()) + AddOptionalMPParameter(Fields.EVENT_VALUE, builder.GetEventValue()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void LogTransaction(TransactionHitBuilder builder) { trackerValues[Fields.TRANSACTION_ID] = null; trackerValues[Fields.TRANSACTION_AFFILIATION] = null; trackerValues[Fields.TRANSACTION_REVENUE] = null; trackerValues[Fields.TRANSACTION_SHIPPING] = null; trackerValues[Fields.TRANSACTION_TAX] = null; trackerValues[Fields.CURRENCY_CODE] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "transaction") + AddRequiredMPParameter(Fields.TRANSACTION_ID, builder.GetTransactionID()) + AddOptionalMPParameter(Fields.TRANSACTION_AFFILIATION, builder.GetAffiliation()) + AddOptionalMPParameter(Fields.TRANSACTION_REVENUE, builder.GetRevenue()) + AddOptionalMPParameter(Fields.TRANSACTION_SHIPPING, builder.GetShipping()) + AddOptionalMPParameter(Fields.TRANSACTION_TAX, builder.GetTax()) + AddOptionalMPParameter(Fields.CURRENCY_CODE, builder.GetCurrencyCode()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void LogItem(ItemHitBuilder builder) { trackerValues[Fields.TRANSACTION_ID] = null; trackerValues[Fields.ITEM_NAME] = null; trackerValues[Fields.ITEM_SKU] = null; trackerValues[Fields.ITEM_CATEGORY] = null; trackerValues[Fields.ITEM_PRICE] = null; trackerValues[Fields.ITEM_QUANTITY] = null; trackerValues[Fields.CURRENCY_CODE] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "item") + AddRequiredMPParameter(Fields.TRANSACTION_ID, builder.GetTransactionID()) + AddRequiredMPParameter(Fields.ITEM_NAME, builder.GetName()) + AddOptionalMPParameter(Fields.ITEM_SKU, builder.GetSKU()) + AddOptionalMPParameter(Fields.ITEM_CATEGORY, builder.GetCategory()) + AddOptionalMPParameter(Fields.ITEM_PRICE, builder.GetPrice()) + AddOptionalMPParameter(Fields.ITEM_QUANTITY, builder.GetQuantity()) + AddOptionalMPParameter(Fields.CURRENCY_CODE, builder.GetCurrencyCode()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void LogException(ExceptionHitBuilder builder) { trackerValues[Fields.EX_DESCRIPTION] = null; trackerValues[Fields.EX_FATAL] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "exception") + AddOptionalMPParameter(Fields.EX_DESCRIPTION, builder.GetExceptionDescription()) + AddOptionalMPParameter(Fields.EX_FATAL, builder.IsFatal()) + AddTrackerVals()); } public void LogSocial(SocialHitBuilder builder) { trackerValues[Fields.SOCIAL_NETWORK] = null; trackerValues[Fields.SOCIAL_ACTION] = null; trackerValues[Fields.SOCIAL_TARGET] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "social") + AddRequiredMPParameter(Fields.SOCIAL_NETWORK, builder.GetSocialNetwork()) + AddRequiredMPParameter(Fields.SOCIAL_ACTION, builder.GetSocialAction()) + AddRequiredMPParameter(Fields.SOCIAL_TARGET, builder.GetSocialTarget()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void LogTiming(TimingHitBuilder builder) { trackerValues[Fields.TIMING_CATEGORY] = null; trackerValues[Fields.TIMING_VALUE] = null; trackerValues[Fields.TIMING_LABEL] = null; trackerValues[Fields.TIMING_VAR] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "timing") + AddOptionalMPParameter(Fields.TIMING_CATEGORY, builder.GetTimingCategory()) + AddOptionalMPParameter(Fields.TIMING_VALUE, builder.GetTimingInterval()) + AddOptionalMPParameter(Fields.TIMING_LABEL, builder.GetTimingLabel()) + AddOptionalMPParameter(Fields.TIMING_VAR, builder.GetTimingName()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void ClearUserIDOverride() { SetTrackerVal(Fields.USER_ID, null); } public void SetTrackingCode(string trackingCode) { this.trackingCode = trackingCode; } public void SetBundleIdentifier(string bundleIdentifier) { this.bundleIdentifier = bundleIdentifier; } public void SetAppName(string appName) { this.appName = appName; } public void SetAppVersion(string appVersion) { this.appVersion = appVersion; } public void SetLogLevelValue(GoogleAnalyticsV3.DebugMode logLevel) { this.logLevel = logLevel; } public void SetAnonymizeIP(bool anonymizeIP) { this.anonymizeIP = anonymizeIP; } public void SetDryRun(bool dryRun) { this.dryRun = dryRun; } public void SetOptOut(bool optOut) { this.optOut = optOut; } #endif }
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Threading; using KittyHawk.MqttLib.Plugins.Logging; using Microsoft.SPOT.Net.Security; using KittyHawk.MqttLib.Exceptions; using KittyHawk.MqttLib.Utilities; using KittyHawk.MqttLib.Interfaces; using KittyHawk.MqttLib.Messages; namespace KittyHawk.MqttLib.Net { internal class NetMfSocketAdapter : ISocketAdapter { private Socket _socket; private readonly ManualResetEvent _stopEvent = new ManualResetEvent(false); private readonly object _streamCreationLock = new object(); private readonly object _receiverThreadCreationLock = new object(); private readonly X509Certificate _caCert; private SslProtocols _encryptionLevel; private INetworkStream _stream; private string _remoteHost; private readonly ILogger _logger; private string _clientUid; // Receiver thread private Thread _receiverThread; // Writer thread parameters private Thread _writerThread; private SocketEventArgs _writerEventArgs; private readonly AutoResetEvent _writerThreadReady = new AutoResetEvent(false); private readonly AutoResetEvent _writerThreadWrite = new AutoResetEvent(false); public NetMfSocketAdapter(ILogger logger) : this(logger, null) { } public NetMfSocketAdapter(ILogger logger, X509Certificate caCertificate) { _logger = logger; _caCert = caCertificate; } public bool IsEncrypted(string clientUid) { return _encryptionLevel != SslProtocols.None; } public bool IsConnected(string clientUid) { lock (_receiverThreadCreationLock) { return _receiverThread != null && _receiverThread.IsAlive; } } public void JoinDisconnect(string clientUid) { // Throws InvalidOperationException when called from keep alive timer timeout. Don't know why but probably don't need it. //if (_receiverThread != null && _receiverThread.IsAlive && _receiverThread.ThreadState != ThreadState.Unstarted) //{ // _receiverThread.Join(); //} //if (_writerThread != null && _writerThread.IsAlive && _writerThread.ThreadState != ThreadState.Unstarted) //{ // _writerThread.Join(); //} } public void Disconnect(string clientUid) { _stopEvent.Set(); // Kick the writer thread and make it exit. Must be done after _stopEvent has been set. _writerThreadReady.WaitOne(); _writerThreadWrite.Set(); } public void ConnectAsync(string ipOrHost, int port, SocketEventArgs args) { var t = new Thread(() => { IPEndPoint ep; try { ep = ResolveIpAddress(ipOrHost, port); } catch (Exception ex) { args.SocketException = ex; args.AdditionalErrorInfo = "Unable to resolve ip address or host name."; args.Complete(); return; } _encryptionLevel = GetSslProtocol(args.EncryptionLevel); _clientUid = args.ClientUid; try { CreateSocketAndConnect(ep); StartReceiving(); } catch (Exception ex) { _clientUid = null; args.SocketException = ex; } finally { args.Complete(); } }); // Start the writer thread _writerThread = new Thread(WriteMessageWorker); _writerThread.Start(); // Go connect t.Start(); } /// <summary> /// This method helps overcome what appears to be a problem in .NET MF v4.2 where Socket.Connect() /// may never return. /// </summary> /// <param name="ep"></param> private void CreateSocketAndConnect(IPEndPoint ep) { Exception exception = null; int retries = 1; while (retries > 0) { var t = new Thread(() => { try { CreateSocket(ep.GetAddressFamily()); _logger.LogMessage("Socket", LogLevel.Verbose, "Attempting connection to " + ep.Address); _socket.Connect(ep); _logger.LogMessage("Socket", LogLevel.Information, "Successfully connected to " + ep.Address); } catch (Exception ex) { _logger.LogMessage("Socket", LogLevel.Information, "Connection attempt failed for " + ep.Address + " Exception=" + ex); exception = ex; } }); t.Start(); if (!t.Join(10000)) { // If we timed out, we hit the bug. Try again. retries--; } else { if (exception != null) { throw exception; } break; } } } public void WriteAsync(SocketEventArgs args) { if (_socket == null) { args.SocketException = new InvalidOperationException("No server connection has been established."); FireOnCompletedNewThread(args); return; } int waitResult = WaitHandle.WaitAny(new WaitHandle[] {_stopEvent, _writerThreadReady}, MqttProtocolInformation.Settings.NetworkTimeout*1000, false); if (waitResult == WaitHandle.WaitTimeout || waitResult == 0) { args.SocketException = new Exception("Unable to send message type " + args.MessageToSend.MessageType + ". Client may be disconnecting."); FireOnCompletedNewThread(args); return; } _writerEventArgs = args; _writerThreadWrite.Set(); } private void WriteMessageWorker() { while (true) { _writerThreadReady.Set(); _writerThreadWrite.WaitOne(); // Are we shutting down? if (_stopEvent.WaitOne(0, false)) { return; } try { if (_socket == null) { throw new InvalidOperationException("No server connection has been established."); } string id = "N/A"; if (_writerEventArgs.MessageToSend is IMqttIdMessage) { id = ((IMqttIdMessage)_writerEventArgs.MessageToSend).MessageId.ToString(); } byte[] sendBuffer = _writerEventArgs.MessageToSend.Serialize(); _logger.LogMessage("Socket", LogLevel.Verbose, "Sending message type " + _writerEventArgs.MessageToSend.MessageType + ", QOS=" + _writerEventArgs.MessageToSend.QualityOfService + ", ID=" + id); GetStream().Send(sendBuffer); } catch (ErrorContextException ex) { string msg = "Error sending message " + _writerEventArgs.MessageToSend.MessageType + ". " + ex.Message; if (ex.InnerException != null) { msg += ". Inner exception=" + ex.InnerException; } _logger.LogMessage("Socket", LogLevel.Verbose, msg); _writerEventArgs.AdditionalErrorInfo = ex.Message; _writerEventArgs.SocketException = ex.InnerException ?? ex; } catch (Exception ex) { string msg = "Error sending message " + _writerEventArgs.MessageToSend.MessageType + ". " + ex.Message; if (ex.InnerException != null) { msg += ". Inner exception=" + ex.InnerException; } _logger.LogMessage("Socket", LogLevel.Verbose, msg); _writerEventArgs.SocketException = ex; } finally { // If disconnecting, get off the writer thread so we can close it and join to it properly var args = _writerEventArgs.Clone(); if (_writerEventArgs.MessageToSend.MessageType == MessageType.Disconnect) { FireOnCompletedNewThread(args.Clone()); } else { args.Complete(); } } } } private void StartReceiving() { lock (_receiverThreadCreationLock) { if (_receiverThread != null && _receiverThread.IsAlive) { return; } _receiverThread = new Thread(() => { _stopEvent.Reset(); // Main receiver loop while (true) { byte[] buffer = null; try { if (GetStream().Available > 0) { buffer = Read(); } } catch (Exception ex) { ProcessException(ex); } if (buffer != null && buffer.Length > 0) { ProcessBuffer(buffer); } if (_stopEvent.WaitOne(MqttProtocolInformation.InternalSettings.SocketReceiverThreadLoopDelay, false)) { break; } } }); _receiverThread.Start(); } } private NetworkReceiverEventHandler _messageReceivedHandler; public void OnMessageReceived(NetworkReceiverEventHandler handler) { _messageReceivedHandler = handler; } private void MessageReceived(MqttNetEventArgs args) { _messageReceivedHandler(args); } public void Dispose() { if (_stream != null) { _logger.LogMessage("Socket", LogLevel.Verbose, "Closing existing network stream."); _stream.Close(); // also closes the socket _stream = null; } _socket = null; } private byte[] Read() { var header = new MqttFixedHeader(); var headerByte = new byte[1]; int receivedSize; INetworkStream stream = GetStream(); // Read the fixed header do { receivedSize = stream.Receive(headerByte, 0, 1); } while (receivedSize > 0 && header.AppendByte(headerByte[0])); if (!header.IsComplete) { _logger.LogMessage("Socket", LogLevel.Error, "Header data invalid for incoming message."); throw new IOException("Unable to receive the MQTT fixed header."); } _logger.LogMessage("Socket", LogLevel.Verbose, "Begin reading payload for incoming message type: " + header.MessageType); // Create a buffer and read the remaining message var completeBuffer = header.CreateMessageBuffer(); receivedSize = 0; while (receivedSize < header.RemainingLength) { receivedSize += stream.Receive(completeBuffer, header.HeaderSize + receivedSize, header.RemainingLength - receivedSize); } return completeBuffer; } private void ProcessBuffer(byte[] buffer) { var t = new Thread(() => { var args = new MqttNetEventArgs { ClientUid = _clientUid }; try { // Process incomming messages args.Message = MqttMessageDeserializer.Deserialize(buffer); string id = "N/A"; if (args.Message is IMqttIdMessage) { id = ((IMqttIdMessage)args.Message).MessageId.ToString(); } _logger.LogMessage("Socket", LogLevel.Verbose, "Received message type " + args.Message.MessageType + ", QOS=" + args.Message.QualityOfService + ", ID=" + id); } catch (Exception ex) { args.Exception = ex; } MessageReceived(args); }); t.Start(); } private void ProcessException(Exception ex) { var t = new Thread(() => { var args = new MqttNetEventArgs { ClientUid = _clientUid }; var ece = ex as ErrorContextException; if (ece != null) { _logger.LogMessage("Socket", LogLevel.Verbose, "Processing exception " + ece.Message + ". Inner exception=" + ece.InnerException); args.AdditionalErrorInfo = ece.Message; args.Exception = ece.InnerException; } else { _logger.LogMessage("Socket", LogLevel.Verbose, "Processing exception " + ex); args.Exception = ex; } MessageReceived(args); }); t.Start(); } private void FireOnCompletedNewThread(SocketEventArgs args) { var t = new Thread(args.Complete); t.Start(); } private void CreateSocket(AddressFamily addressFamily) { if (_stream != null) { _logger.LogMessage("Socket", LogLevel.Verbose, "Closing existing network stream."); _stream.Close(); // also closes the socket _stream = null; _socket = null; } _socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); //_socket.ReceiveTimeout = MqttProtocolInformation.Settings.NetworkTimeout * 1000; //_socket.SendTimeout = MqttProtocolInformation.Settings.NetworkTimeout * 1000; } private INetworkStream GetStream() { if (_stream == null) { lock (_streamCreationLock) { if (_stream == null) { if (_encryptionLevel == SslProtocols.None) { _stream = new UnsecureStream(_socket); } else { try { _stream = new SecureStream(_remoteHost, _socket, _caCert, _encryptionLevel); } catch (SocketException ex) { if (ex.ErrorCode == -1) { var detail = new ErrorContextException("The remote certificate is invalid according to the validation procedure.", ex); throw detail; } throw; } } } } } return _stream; } private IPEndPoint ResolveIpAddress(string ipOrHost, int port) { // Save hostname that user gave us for TLS hostname validation _remoteHost = ipOrHost; // IP look-up in user supplied hosts dictionary if (MqttProtocolInformation.Settings.Hosts.Contains(ipOrHost)) { var value = MqttProtocolInformation.Settings.Hosts[ipOrHost] as string; if (value != null) { ipOrHost = value; } } IPHostEntry hostEntry = Dns.GetHostEntry(ipOrHost); return new IPEndPoint(hostEntry.AddressList[0], port); } private SslProtocols GetSslProtocol(SocketEncryption encryption) { _encryptionLevel = SslProtocols.None; switch (encryption) { case SocketEncryption.None: _encryptionLevel = SslProtocols.None; break; case SocketEncryption.Tls10: _encryptionLevel = SslProtocols.TLSv1; break; } return _encryptionLevel; } } /// <summary> /// Extension methods for socket related classes. /// </summary> public static class SocketExtensions { public static AddressFamily GetAddressFamily(this IPEndPoint ep) { string ip = ep.Address.ToString(); var digits = ip.Split(new[] {':'}); // Shortest possible IPv6 address is the loopback address ::1 if (digits.Length > 2) { return AddressFamily.InterNetworkV6; } return AddressFamily.InterNetwork; } } }
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using BitCoinSharp.IO; using log4net; namespace BitCoinSharp.Store { /// <summary> /// Stores the block chain to disk but still holds it in memory. This is intended for desktop apps and tests. /// Constrained environments like mobile phones probably won't want to or be able to store all the block headers in RAM. /// </summary> public class DiskBlockStore : IBlockStore { private static readonly ILog _log = LogManager.GetLogger(typeof (DiskBlockStore)); private FileStream _stream; private readonly IDictionary<Sha256Hash, StoredBlock> _blockMap; private Sha256Hash _chainHead; private readonly NetworkParameters _params; /// <exception cref="BlockStoreException"/> public DiskBlockStore(NetworkParameters @params, FileInfo file) { _params = @params; _blockMap = new Dictionary<Sha256Hash, StoredBlock>(); try { Load(file); if (_stream != null) { _stream.Dispose(); } _stream = file.Open(FileMode.Append, FileAccess.Write); // Do append. } catch (IOException e) { _log.Error("failed to load block store from file", e); CreateNewStore(@params, file); } } /// <exception cref="BlockStoreException"/> private void CreateNewStore(NetworkParameters @params, FileInfo file) { // Create a new block store if the file wasn't found or anything went wrong whilst reading. _blockMap.Clear(); try { if (_stream != null) { _stream.Dispose(); } _stream = file.OpenWrite(); // Do not append, create fresh. _stream.Write(1); // Version. } catch (IOException e1) { // We could not load a block store nor could we create a new one! throw new BlockStoreException(e1); } try { // Set up the genesis block. When we start out fresh, it is by definition the top of the chain. var genesis = @params.GenesisBlock.CloneAsHeader(); var storedGenesis = new StoredBlock(genesis, genesis.GetWork(), 0); _chainHead = storedGenesis.Header.Hash; _stream.Write(_chainHead.Bytes); Put(storedGenesis); } catch (IOException e) { throw new BlockStoreException(e); } } /// <exception cref="IOException"/> /// <exception cref="BlockStoreException"/> private void Load(FileInfo file) { _log.InfoFormat("Reading block store from {0}", file); using (var input = file.OpenRead()) { // Read a version byte. var version = input.Read(); if (version == -1) { // No such file or the file was empty. throw new FileNotFoundException(file.Name + " does not exist or is empty"); } if (version != 1) { throw new BlockStoreException("Bad version number: " + version); } // Chain head pointer is the first thing in the file. var chainHeadHash = new byte[32]; if (input.Read(chainHeadHash) < chainHeadHash.Length) throw new BlockStoreException("Truncated block store: cannot read chain head hash"); _chainHead = new Sha256Hash(chainHeadHash); _log.InfoFormat("Read chain head from disk: {0}", _chainHead); var now = Environment.TickCount; // Rest of file is raw block headers. var headerBytes = new byte[Block.HeaderSize]; try { while (true) { // Read a block from disk. if (input.Read(headerBytes) < 80) { // End of file. break; } // Parse it. var b = new Block(_params, headerBytes); // Look up the previous block it connects to. var prev = Get(b.PrevBlockHash); StoredBlock s; if (prev == null) { // First block in the stored chain has to be treated specially. if (b.Equals(_params.GenesisBlock)) { s = new StoredBlock(_params.GenesisBlock.CloneAsHeader(), _params.GenesisBlock.GetWork(), 0); } else { throw new BlockStoreException("Could not connect " + b.Hash + " to " + b.PrevBlockHash); } } else { // Don't try to verify the genesis block to avoid upsetting the unit tests. b.VerifyHeader(); // Calculate its height and total chain work. s = prev.Build(b); } // Save in memory. _blockMap[b.Hash] = s; } } catch (ProtocolException e) { // Corrupted file. throw new BlockStoreException(e); } catch (VerificationException e) { // Should not be able to happen unless the file contains bad blocks. throw new BlockStoreException(e); } var elapsed = Environment.TickCount - now; _log.InfoFormat("Block chain read complete in {0}ms", elapsed); } } /// <exception cref="BlockStoreException"/> public void Put(StoredBlock block) { lock (this) { try { var hash = block.Header.Hash; Debug.Assert(!_blockMap.ContainsKey(hash), "Attempt to insert duplicate"); // Append to the end of the file. The other fields in StoredBlock will be recalculated when it's reloaded. var bytes = block.Header.BitcoinSerialize(); _stream.Write(bytes); _stream.Flush(); _blockMap[hash] = block; } catch (IOException e) { throw new BlockStoreException(e); } } } /// <exception cref="BlockStoreException"/> public StoredBlock Get(Sha256Hash hash) { lock (this) { StoredBlock block; _blockMap.TryGetValue(hash, out block); return block; } } /// <exception cref="BlockStoreException"/> public StoredBlock GetChainHead() { lock (this) { StoredBlock block; _blockMap.TryGetValue(_chainHead, out block); return block; } } /// <exception cref="BlockStoreException"/> public void SetChainHead(StoredBlock chainHead) { lock (this) { try { _chainHead = chainHead.Header.Hash; // Write out new hash to the first 32 bytes of the file past one (first byte is version number). _stream.Seek(1, SeekOrigin.Begin); var bytes = _chainHead.Bytes; _stream.Write(bytes, 0, bytes.Length); } catch (IOException e) { throw new BlockStoreException(e); } } } #region IDisposable Members public void Dispose() { if (_stream != null) { _stream.Dispose(); _stream = null; } } #endregion } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Text; using System.Drawing; using Axiom.Core; using Axiom.Configuration; using Axiom.Scripting; namespace Axiom.Graphics { ///<summary> /// Class for managing Compositor settings for Ogre. Compositors provide the means /// to flexibly "composite" the final rendering result from multiple scene renders /// and intermediate operations like rendering fullscreen quads. This makes /// it possible to apply postfilter effects, HDRI postprocessing, and shadow /// effects to a Viewport. /// /// When loaded from a script, a Compositor is in an 'unloaded' state and only stores the settings /// required. It does not at that stage load any textures. This is because the material settings may be /// loaded 'en masse' from bulk material script files, but only a subset will actually be required. /// /// Because this is a subclass of ResourceManager, any files loaded will be searched for in any path or /// archive added to the resource paths/archives. See ResourceManager for details. ///</summary> public class CompositorManager : ResourceManager { #region Singleton implementation /// <summary> /// Singleton instance of this class. /// </summary> private static CompositorManager instance; /// <summary> /// Internal constructor. This class cannot be instantiated externally. /// </summary> /// <remarks> /// Protected internal because this singleton will actually hold the instance of a subclass /// created by a render system plugin. /// </remarks> protected internal CompositorManager() { if (instance == null) { instance = this; } rectangle = null; } /// <summary> /// Gets the singleton instance of this class. /// </summary> public static CompositorManager Instance { get { return instance; } } #endregion Singleton implementation #region Fields // Create a logger for use in this class private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(CompositorManager)); ///<summary> /// Mapping from viewport to compositor chain ///</summary> protected Dictionary<Viewport, CompositorChain> chains; ///<summary> /// Serializer ///</summary> //protected CompositorSerializer serializer; ///<summary> ///</summary> protected Rectangle2D rectangle; #endregion Fields #region Methods ///<summary> /// Required by the ResourceManager base class ///</summary> public override Resource Create(string name, bool isManual) { Compositor ret = new Compositor(name); Add(ret); return ret; } ///<summary> /// Intialises the Compositor manager, which also triggers it to /// parse all available .compositor scripts. ///</summary> public void Initialize() { Compositor scene = (Compositor)Create("Ogre/Scene"); CompositionTechnique t = scene.CreateTechnique(); CompositionTargetPass tp = t.OutputTarget; tp.VisibilityMask = 0xFFFFFFFF; CompositionPass pass = tp.CreatePass(); pass.Type = CompositorPassType.Clear; CompositionPass nextPass = tp.CreatePass(); nextPass.Type = CompositorPassType.RenderScene; /// Render everything, including skies pass.FirstRenderQueue = RenderQueueGroupID.SkiesEarly; pass.LastRenderQueue = RenderQueueGroupID.SkiesLate; chains = new Dictionary<Viewport, CompositorChain>(); // parse all compositing scripts ParseAllSources(); } /// <summary> /// Parses all compositing script files in resource folders and archives. /// </summary> private void ParseAllSources() { StringCollection compositingFiles = ResourceManager.GetAllCommonNamesLike("", ".compositor"); foreach(string file in compositingFiles) { Stream data = ResourceManager.FindCommonResourceData(file); try { ParseScript(data, file); } catch (Exception e) { LogManager.Instance.WriteException("Unable to parse compositing script '{0}': {1}", file, e.Message); } } } public void ParseScript(string script) { ParseScript(new StringReader(script), ""); } public void ParseScript(Stream data, string file) { ParseScript(new StreamReader(data, System.Text.Encoding.ASCII), file); } protected static void LogError(CompositorScriptContext context, string error, params object[] substitutions) { StringBuilder errorBuilder = new StringBuilder(); // log compositor name only if filename not specified if(context.filename == null && context.compositor != null) { errorBuilder.Append("Error in compositor "); errorBuilder.Append(context.compositor.Name); errorBuilder.Append(" : "); errorBuilder.AppendFormat("At line # {0}: '{1}'", context.lineNo, context.line); errorBuilder.AppendFormat(error, substitutions); } else { if(context.compositor != null) { errorBuilder.Append("Error in compositor "); errorBuilder.Append(context.compositor.Name); errorBuilder.AppendFormat(" at line # {0}: '{1}'", context.lineNo, context.line); errorBuilder.AppendFormat(" of {0}: ", context.filename); errorBuilder.AppendFormat(error, substitutions); } else { errorBuilder.AppendFormat("Error at line # {0}: '{1}'", context.lineNo, context.line); errorBuilder.AppendFormat(" of {0}: ", context.filename); errorBuilder.AppendFormat(error, substitutions); } } LogManager.Instance.Write(errorBuilder.ToString()); } protected string[] SplitByWhitespace(string line, int count) { return line.Split(new char[] {' ', '\t'}, count); } protected string[] SplitArgs(string args) { return args.Split(new char[] {' ', '\t'}); } protected string RemoveQuotes(string token) { if (token.Length >= 2 && token[0] == '\"') token = token.Substring(1); if (token[token.Length - 1] == '\"') token = token.Substring(0, token.Length - 1); return token; } protected bool OptionCount (CompositorScriptContext context, string introducer, int expectedCount, int count) { if (expectedCount < count) { LogError(context, "The '{0}' phrase requires {1} arguments", introducer, expectedCount); return false; } else return true; } protected bool OnOffArg(CompositorScriptContext context, string introducer, string []args) { if (OptionCount(context, introducer, 1, args.Length)) { string arg = args[0]; if (arg == "on") return true; else if (arg == "off") return false; else { LogError(context, "Illegal '{0}' arg '{1}'; should be 'on' or 'off'", introducer, arg); } } return false; } protected int ParseInt(CompositorScriptContext context, string s) { string n = s.Trim(); try { return int.Parse(n); } catch (Exception e) { LogError(context, "Error converting string '{0}' to integer; error message is '{1}'", n, e.Message); return 0; } } protected uint ParseUint(CompositorScriptContext context, string s) { string n = s.Trim(); try { return uint.Parse(n); } catch (Exception e) { LogError(context, "Error converting string '{0}' to unsigned integer; error message is '{1}'", n, e.Message); return 0; } } protected float ParseFloat(CompositorScriptContext context, string s) { string n = s.Trim(); try { return float.Parse(n); } catch (Exception e) { LogError(context, "Error converting string '{0}' to float; error message is '{1}'", n, e.Message); return 0.0f; } } protected ColorEx ParseClearColor(CompositorScriptContext context, string [] args) { if (args.Length != 4) { LogError(context, "A color value must consist of 4 floating point numbers"); return ColorEx.Black; } else { float r = ParseFloat(context, args[0]); float g = ParseFloat(context, args[0]); float b = ParseFloat(context, args[0]); float a = ParseFloat(context, args[0]); return new ColorEx(a, r, g, b); } } protected void LogIllegal(CompositorScriptContext context, string category, string token) { LogError(context, "Illegal {0} attribute '{1}'", category, token); } /// <summary> /// Starts parsing an individual script file. /// </summary> /// <param name="data">Stream containing the script data.</param> public void ParseScript(TextReader script, string file) { string line = ""; CompositorScriptContext context = new CompositorScriptContext(); context.filename = file; context.lineNo = 0; // parse through the data to the end while((line = ParseHelper.ReadLine(script)) != null) { context.lineNo++; string[] splitCmd; string[] args; string arg; // ignore blank lines and comments if(!(line.Length == 0 || line.StartsWith("//"))) { context.line = line; splitCmd = SplitByWhitespace(line, 2); string token = splitCmd[0]; args = SplitArgs(splitCmd.Length == 2 ? splitCmd[1] : ""); arg = (args.Length > 0 ? args[0] : ""); if(context.section == CompositorScriptSection.None) { if (token != "compositor") { LogError(context, "First token is not 'compositor'!"); break; // Give up } string compositorName = RemoveQuotes(splitCmd[1].Trim()); context.compositor = (Compositor)CompositorManager.Instance.Create(compositorName); context.section = CompositorScriptSection.Compositor; context.seenOpen = false; continue; // next line } else { if (!context.seenOpen) { if (token == "{") context.seenOpen = true; else LogError(context, "Expected open brace '{'; instead got {0}", token); continue; // next line } switch(context.section) { case CompositorScriptSection.Compositor: switch (token) { case "technique": context.section = CompositorScriptSection.Technique; context.technique = context.compositor.CreateTechnique(); context.seenOpen = false; continue; // next line case "}": context.section = CompositorScriptSection.None; context.seenOpen = false; if (context.technique == null) { LogError(context, "No 'technique' section in compositor"); continue; } break; default: LogError(context, "After opening brace '{' of compositor definition, expected 'technique', but got '{0}'", token); continue; // next line } break; case CompositorScriptSection.Technique: switch (token) { case "texture": ParseTextureLine(context, args); break; case "target": context.section = CompositorScriptSection.Target; context.target = context.technique.CreateTargetPass(); context.target.OutputName = arg.Trim(); context.seenOpen = false; break; case "target_output": context.section = CompositorScriptSection.Target; context.target = context.technique.OutputTarget; context.seenOpen = false; break; case "}": context.section = CompositorScriptSection.Compositor; context.seenOpen = true; break; default: LogIllegal(context, "technique", token); break; } break; case CompositorScriptSection.Target: switch (token) { case "input": if (OptionCount(context, token, 1, args.Length)) { arg = args[0]; if (arg == "previous") context.target.InputMode = CompositorInputMode.Previous; else if (arg == "none") context.target.InputMode = CompositorInputMode.None; else LogError(context, "Illegal 'input' arg '{0}'", arg); } break; case "only_initial": context.target.OnlyInitial = OnOffArg(context, token, args); break; case "visibility_mask": if (!OptionCount(context, token, 1, args.Length)) break; context.target.VisibilityMask = ParseUint(context, arg); break; case "lod_bias": if (!OptionCount(context, token, 1, args.Length)) break; context.target.LodBias = ParseInt(context, arg); break; case "material_scheme": if (!OptionCount(context, token, 1, args.Length)) break; context.target.MaterialScheme = arg.Trim(); break; case "pass": context.section = CompositorScriptSection.Pass; context.pass = context.target.CreatePass(); context.seenOpen = false; if (!OptionCount(context, token, 1, args.Length)) break; arg = arg.Trim(); switch(arg) { case "render_quad": context.pass.Type = CompositorPassType.RenderQuad; break; case "clear": context.pass.Type = CompositorPassType.Clear; break; case "stencil": context.pass.Type = CompositorPassType.Stencil; break; case "render_scene": context.pass.Type = CompositorPassType.RenderScene; break; default: LogError(context, "In line '{0}', unrecognized compositor pass type '{1}'", arg); break; } break; case "}": context.section = CompositorScriptSection.Technique; context.seenOpen = true; break; default: LogIllegal(context, "target", token); break; } break; case CompositorScriptSection.Pass: switch (token) { case "first_render_queue": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.FirstRenderQueue = (RenderQueueGroupID)ParseInt(context, args[0]); break; case "last_render_queue": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.LastRenderQueue = (RenderQueueGroupID)ParseInt(context, args[0]); break; case "identifier": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.Identifier = ParseUint(context, args[0]); break; case "material": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.MaterialName = args[0].Trim(); break; case "input": if (!OptionCount(context, token, 2, args.Length)) break; context.pass.SetInput(ParseInt(context, args[0]), args[1].Trim()); break; case "clear": context.section = CompositorScriptSection.Clear; context.seenOpen = false; break; case "stencil": context.section = CompositorScriptSection.Clear; context.seenOpen = false; break; case "}": context.section = CompositorScriptSection.Target; context.seenOpen = true; break; default: LogIllegal(context, "pass", token); break; } break; case CompositorScriptSection.Clear: switch (token) { case "buffers": FrameBuffer fb = (FrameBuffer)0; foreach (string cb in args) { switch (cb) { case "colour": fb |= FrameBuffer.Color; break; case "color": fb |= FrameBuffer.Color; break; case "depth": fb |= FrameBuffer.Depth; break; case "stencil": fb |= FrameBuffer.Stencil; break; default: LogError(context, "When parsing pass clear buffers options, illegal option '{0}'", cb); break; } } break; case "colour": context.pass.ClearColor = ParseClearColor(context, args); break; case "color": context.pass.ClearColor = ParseClearColor(context, args); break; case "depth_value": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.ClearDepth = ParseFloat(context, args[0]); break; case "stencil_value": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.ClearDepth = ParseInt(context, args[0]); break; case "}": context.section = CompositorScriptSection.Pass; context.seenOpen = true; break; default: LogIllegal(context, "clear", token); break; } break; case CompositorScriptSection.Stencil: switch (token) { case "check": context.pass.StencilCheck = OnOffArg(context, token, args); break; case "compare_func": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.StencilFunc = ParseCompareFunc(context, arg); break; case "ref_value": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.StencilRefValue = ParseInt(context, arg); break; case "mask": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.StencilMask = ParseInt(context, arg); break; case "fail_op": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.StencilFailOp = ParseStencilOperation(context, arg); break; case "depth_fail_op": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.StencilDepthFailOp = ParseStencilOperation(context, arg); break; case "pass_op": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.StencilPassOp = ParseStencilOperation(context, arg); break; case "two_sided": if (!OptionCount(context, token, 1, args.Length)) break; context.pass.StencilTwoSidedOperation = OnOffArg(context, token, args); break; case "}": context.section = CompositorScriptSection.Pass; context.seenOpen = true; break; default: LogIllegal(context, "stencil", token); break; } break; default: LogError(context, "Internal compositor parser error: illegal context"); break; } } // if } // if } // while if (context.section != CompositorScriptSection.None) LogError(context, "At end of file, unterminated compositor script!"); } protected void ParseTextureLine(CompositorScriptContext context, string [] args) { if (args.Length == 4) { CompositionTextureDefinition textureDef = context.technique.CreateTextureDefinition(args[0]); textureDef.Width = (args[1] == "target_width" ? 0 : ParseInt(context, args[1])); textureDef.Height = (args[2] == "target_height" ? 0 : ParseInt(context, args[2])); switch (args[3]) { case "PF_A8R8G8B8": textureDef.Format = Axiom.Media.PixelFormat.A8R8G8B8; break; case "PF_R8G8B8A8": textureDef.Format = Axiom.Media.PixelFormat.R8G8B8A8; break; case "PF_R8G8B8": textureDef.Format = Axiom.Media.PixelFormat.R8G8B8; break; case "PF_FLOAT16_RGBA": textureDef.Format = Axiom.Media.PixelFormat.FLOAT16_RGBA; break; case "PF_FLOAT16_RGB": textureDef.Format = Axiom.Media.PixelFormat.FLOAT16_RGB; break; case "PF_FLOAT32_RGBA": textureDef.Format = Axiom.Media.PixelFormat.FLOAT32_RGBA; break; case "PF_FLOAT16_R": textureDef.Format = Axiom.Media.PixelFormat.FLOAT16_R; break; case "PF_FLOAT32_R": textureDef.Format = Axiom.Media.PixelFormat.FLOAT32_R; break; default: LogError(context, "Unsupported texture pixel format '{0}'", args[3]); break; } } } protected CompareFunction ParseCompareFunc(CompositorScriptContext context, string arg) { switch (arg.Trim()) { case "always_fail": return CompareFunction.AlwaysFail; case "always_pass": return CompareFunction.AlwaysPass; case "less_equal": return CompareFunction.LessEqual; case "less'": return CompareFunction.Less; case "equal": return CompareFunction.Equal; case "not_equal": return CompareFunction.NotEqual; case "greater_equal": return CompareFunction.GreaterEqual; case "greater": return CompareFunction.Greater; default: LogError(context, "Illegal stencil compare_func '{0}'", arg); return CompareFunction.AlwaysPass; } } protected StencilOperation ParseStencilOperation(CompositorScriptContext context, string arg) { switch (arg.Trim()) { case "keep": return StencilOperation.Keep; case "zero": return StencilOperation.Zero; case "replace": return StencilOperation.Replace; case "increment_wrap": return StencilOperation.IncrementWrap; case "increment": return StencilOperation.Increment; case "decrement_wrap": return StencilOperation.DecrementWrap; case "decrement": return StencilOperation.Decrement; case "invert": return StencilOperation.Invert; default: LogError(context, "Illegal stencil_operation '{0}'", arg); return StencilOperation.Keep; } } ///<summary> /// Get the compositor chain for a Viewport. If there is none yet, a new /// compositor chain is registered. /// XXX We need a _notifyViewportRemoved to find out when this viewport disappears, /// so we can destroy its chain as well. ///</summary> public CompositorChain GetCompositorChain(Viewport vp) { CompositorChain chain; if (chains.TryGetValue(vp, out chain)) return chain; else { chain = new CompositorChain(vp); chains[vp] = chain; return chain; } } ///<summary> /// Returns whether exists compositor chain for a viewport. ///</summary> public bool HasCompositorChain(Viewport vp) { return chains.ContainsKey(vp); } ///<summary> /// Remove the compositor chain from a viewport if exists. ///</summary> public void RemoveCompositorChain(Viewport vp) { chains.Remove(vp); } ///<summary> /// Overridden from ResourceManager since we have to clean up chains too. ///</summary> public void RemoveAll() { FreeChains(); chains.Clear(); } ///<summary> /// Clear composition chains for all viewports ///</summary> protected void FreeChains() { // Do I need to dispose the CompositorChain objects? chains.Clear(); } ///<summary> /// Get a textured fullscreen 2D rectangle, for internal use. ///</summary> public IRenderable GetTexturedRectangle2D() { if(rectangle == null) /// 2D rectangle, to use for render_quad passes rectangle = new Rectangle2D(true); RenderSystem rs = Root.Instance.RenderSystem; Viewport vp = rs.ActiveViewport; float hOffset = rs.HorizontalTexelOffset / (0.5f * vp.ActualWidth); float vOffset = rs.VerticalTexelOffset / (0.5f * vp.ActualHeight); rectangle.SetCorners(-1f + hOffset, 1f - vOffset, 1f + hOffset, -1f - vOffset); return rectangle; } ///<summary> /// Add a compositor to a viewport. By default, it is added to end of the chain, /// after the other compositors. ///</summary> ///<param name="vp">Viewport to modify</param> ///<param name="compositor">The name of the compositor to apply</param> ///<param name="addPosition">At which position to add, defaults to the end (-1).</param> ///<returns>pointer to instance, or null if it failed.</returns> public CompositorInstance AddCompositor(Viewport vp, string compositor, int addPosition) { Compositor comp = (Compositor)GetByName(compositor); if(comp == null) return null; CompositorChain chain = GetCompositorChain(vp); return chain.AddCompositor(comp, addPosition == -1 ? CompositorChain.LastCompositor : addPosition); } public CompositorInstance AddCompositor(Viewport vp, string compositor) { return AddCompositor(vp, compositor, -1); } ///<summary> /// Remove a compositor from a viewport ///</summary> public void RemoveCompositor(Viewport vp, string compositor) { CompositorChain chain = GetCompositorChain(vp); for (int i=0; i< chain.Instances.Count; i++) { CompositorInstance instance = chain.GetCompositor(i); if (instance.Compositor.Name == compositor) { chain.RemoveCompositor(i); break; } } } /// <summary> /// another overload to remove a compositor instance from its chain /// </summary> /// <param name="remInstance"></param> public void RemoveCompositor(CompositorInstance remInstance) { CompositorChain chain = remInstance.Chain; for (int i = 0; i < chain.Instances.Count; i++) { CompositorInstance instance = chain.GetCompositor(i); if (instance == remInstance) { chain.RemoveCompositor(i); break; } } } ///<summary> /// Set the state of a compositor on a viewport to enabled or disabled. /// Disabling a compositor stops it from rendering but does not free any resources. /// This can be more efficient than using removeCompositor and addCompositor in cases /// the filter is switched on and off a lot. ///</summary> public void SetCompositorEnabled(Viewport vp, string compositor, bool value) { CompositorChain chain = GetCompositorChain(vp); for (int i=0; i< chain.Instances.Count; i++) { CompositorInstance instance = chain.GetCompositor(i); if (instance.Compositor.Name == compositor) { chain.SetCompositorEnabled(i, value); break; } } } #endregion Methods } /// <summary> /// Enum to identify compositor sections. /// </summary> public enum CompositorScriptSection { None, Compositor, Technique, Target, Pass, Clear, Stencil } /// <summary> /// Struct for holding the script context while parsing. /// </summary> public class CompositorScriptContext { public CompositorScriptSection section = CompositorScriptSection.None; public Compositor compositor = null; public CompositionTechnique technique = null; public CompositionPass pass = null; public CompositionTargetPass target = null; public bool seenOpen = false; // Error reporting state public int lineNo; public string line; public string filename; } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using VotingInfo.Database.Contracts; using VotingInfo.Database.Contracts.Data; /////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend.// /////////////////////////////////////////////////////////// // This file contains static implementations of the LocationLogic // Add your own static methods by making a new partial class. // You cannot override static methods, instead override the methods // located in LocationLogicBase by making a partial class of LocationLogic // and overriding the base methods. namespace VotingInfo.Database.Logic.Data { public partial class LocationLogic { //Put your code in a separate file. This is auto generated. /// <summary> /// Run Location_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationName">Value for LocationName</param> public static int? InsertNow(int fldContentInspectionId , string fldLocationName ) { return (new LocationLogic()).Insert(fldContentInspectionId , fldLocationName ); } /// <summary> /// Run Location_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationName">Value for LocationName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> public static int? InsertNow(int fldContentInspectionId , string fldLocationName , SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).Insert(fldContentInspectionId , fldLocationName , connection, transaction); } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(LocationContract row) { return (new LocationLogic()).Insert(row); } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(LocationContract row, SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).Insert(row, connection, transaction); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<LocationContract> rows) { return (new LocationLogic()).InsertAll(rows); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<LocationContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).InsertAll(rows, connection, transaction); } /// <summary> /// Run Location_Update. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationName">Value for LocationName</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldLocationId , int fldContentInspectionId , string fldLocationName ) { return (new LocationLogic()).Update(fldLocationId , fldContentInspectionId , fldLocationName ); } /// <summary> /// Run Location_Update. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationName">Value for LocationName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldLocationId , int fldContentInspectionId , string fldLocationName , SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).Update(fldLocationId , fldContentInspectionId , fldLocationName , connection, transaction); } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(LocationContract row) { return (new LocationLogic()).Update(row); } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(LocationContract row, SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).Update(row, connection, transaction); } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<LocationContract> rows) { return (new LocationLogic()).UpdateAll(rows); } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<LocationContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).UpdateAll(rows, connection, transaction); } /// <summary> /// Run Location_Delete. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldLocationId ) { return (new LocationLogic()).Delete(fldLocationId ); } /// <summary> /// Run Location_Delete. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldLocationId , SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).Delete(fldLocationId , connection, transaction); } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(LocationContract row) { return (new LocationLogic()).Delete(row); } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(LocationContract row, SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).Delete(row, connection, transaction); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<LocationContract> rows) { return (new LocationLogic()).DeleteAll(rows); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<LocationContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).DeleteAll(rows, connection, transaction); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldLocationId ) { return (new LocationLogic()).Exists(fldLocationId ); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldLocationId , SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).Exists(fldLocationId , connection, transaction); } /// <summary> /// Run Location_Search, and return results as a list of LocationRow. /// </summary> /// <param name="fldLocationName">Value for LocationName</param> /// <returns>A collection of LocationRow.</returns> public static List<LocationContract> SearchNow(string fldLocationName ) { var driver = new LocationLogic(); driver.Search(fldLocationName ); return driver.Results; } /// <summary> /// Run Location_Search, and return results as a list of LocationRow. /// </summary> /// <param name="fldLocationName">Value for LocationName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of LocationRow.</returns> public static List<LocationContract> SearchNow(string fldLocationName , SqlConnection connection, SqlTransaction transaction) { var driver = new LocationLogic(); driver.Search(fldLocationName , connection, transaction); return driver.Results; } /// <summary> /// Run Location_SelectAll, and return results as a list of LocationRow. /// </summary> /// <returns>A collection of LocationRow.</returns> public static List<LocationContract> SelectAllNow() { var driver = new LocationLogic(); driver.SelectAll(); return driver.Results; } /// <summary> /// Run Location_SelectAll, and return results as a list of LocationRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of LocationRow.</returns> public static List<LocationContract> SelectAllNow(SqlConnection connection, SqlTransaction transaction) { var driver = new LocationLogic(); driver.SelectAll(connection, transaction); return driver.Results; } /// <summary> /// Run Location_List, and return results as a list. /// </summary> /// <param name="fldLocationName">Value for LocationName</param> /// <returns>A collection of __ListItemRow.</returns> public static List<ListItemContract> ListNow(string fldLocationName ) { return (new LocationLogic()).List(fldLocationName ); } /// <summary> /// Run Location_List, and return results as a list. /// </summary> /// <param name="fldLocationName">Value for LocationName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of __ListItemRow.</returns> public static List<ListItemContract> ListNow(string fldLocationName , SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).List(fldLocationName , connection, transaction); } /// <summary> /// Run Location_SelectBy_LocationId, and return results as a list of LocationRow. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <returns>A collection of LocationRow.</returns> public static List<LocationContract> SelectBy_LocationIdNow(int fldLocationId ) { var driver = new LocationLogic(); driver.SelectBy_LocationId(fldLocationId ); return driver.Results; } /// <summary> /// Run Location_SelectBy_LocationId, and return results as a list of LocationRow. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of LocationRow.</returns> public static List<LocationContract> SelectBy_LocationIdNow(int fldLocationId , SqlConnection connection, SqlTransaction transaction) { var driver = new LocationLogic(); driver.SelectBy_LocationId(fldLocationId , connection, transaction); return driver.Results; } /// <summary> /// Run Location_SelectBy_ContentInspectionId, and return results as a list of LocationRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <returns>A collection of LocationRow.</returns> public static List<LocationContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId ) { var driver = new LocationLogic(); driver.SelectBy_ContentInspectionId(fldContentInspectionId ); return driver.Results; } /// <summary> /// Run Location_SelectBy_ContentInspectionId, and return results as a list of LocationRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of LocationRow.</returns> public static List<LocationContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId , SqlConnection connection, SqlTransaction transaction) { var driver = new LocationLogic(); driver.SelectBy_ContentInspectionId(fldContentInspectionId , connection, transaction); return driver.Results; } /// <summary> /// Read all Location rows from the provided reader into the list structure of LocationRows /// </summary> /// <param name="reader">The result of running a sql command.</param> /// <returns>A populated LocationRows or an empty LocationRows if there are no results.</returns> public static List<LocationContract> ReadAllNow(SqlDataReader reader) { var driver = new LocationLogic(); driver.ReadAll(reader); return driver.Results; } /// <summary>"); /// Advance one, and read values into a Location /// </summary> /// <param name="reader">The result of running a sql command.</param>"); /// <returns>A Location or null if there are no results.</returns> public static LocationContract ReadOneNow(SqlDataReader reader) { var driver = new LocationLogic(); return driver.ReadOne(reader) ? driver.Results[0] : null; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(LocationContract row) { if(row.LocationId == null) { return InsertNow(row); } else { return UpdateNow(row); } } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(LocationContract row, SqlConnection connection, SqlTransaction transaction) { if(row.LocationId == null) { return InsertNow(row, connection, transaction); } else { return UpdateNow(row, connection, transaction); } } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<LocationContract> rows) { return (new LocationLogic()).SaveAll(rows); } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<LocationContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new LocationLogic()).SaveAll(rows, connection, transaction); } } }
#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: Error.cs 923 2011-12-23 22:02:10Z azizatif $")] namespace Elmah { #region Imports using System; using System.Diagnostics; using System.Security; using System.Security.Principal; using System.Web; using System.Xml; using Mannex; using Thread = System.Threading.Thread; using NameValueCollection = System.Collections.Specialized.NameValueCollection; #endregion /// <summary> /// Represents a logical application error (as opposed to the actual /// exception it may be representing). /// </summary> [ Serializable ] public sealed class Error : ICloneable { private readonly Exception _exception; private string _applicationName; private string _hostName; private string _typeName; private string _source; private string _message; private string _detail; private string _user; private DateTime _time; private int _statusCode; private string _webHostHtmlMessage; private NameValueCollection _serverVariables; private NameValueCollection _queryString; private NameValueCollection _form; private NameValueCollection _cookies; /// <summary> /// Initializes a new instance of the <see cref="Error"/> class. /// </summary> public Error() {} /// <summary> /// Initializes a new instance of the <see cref="Error"/> class /// from a given <see cref="Exception"/> instance. /// </summary> public Error(Exception e) : this(e, null) {} /// <summary> /// Initializes a new instance of the <see cref="Error"/> class /// from a given <see cref="Exception"/> instance and /// <see cref="HttpContext"/> instance representing the HTTP /// context during the exception. /// </summary> public Error(Exception e, HttpContextBase context) { if (e == null) throw new ArgumentNullException("e"); _exception = e; Exception baseException = e.GetBaseException(); // // Load the basic information. // _hostName = Environment.TryGetMachineName(context); _typeName = baseException.GetType().FullName; _message = baseException.Message; _source = baseException.Source; _detail = e.ToString(); _user = Thread.CurrentPrincipal.Identity.Name ?? string.Empty; _time = DateTime.Now; // // If this is an HTTP exception, then get the status code // and detailed HTML message provided by the host. // HttpException httpException = e as HttpException; if (httpException != null) { _statusCode = httpException.GetHttpCode(); _webHostHtmlMessage = TryGetHtmlErrorMessage(httpException) ?? string.Empty; } // // If the HTTP context is available, then capture the // collections that represent the state request as well as // the user. // if (context != null) { IPrincipal webUser = context.User; if (webUser != null && (webUser.Identity.Name ?? string.Empty).Length > 0) { _user = webUser.Identity.Name; } var request = context.Request; var qsfc = request.TryGetUnvalidatedCollections((form, qs, cookies) => new { QueryString = qs, Form = form, Cookies = cookies, }); _serverVariables = CopyCollection(request.ServerVariables); if (_serverVariables != null) { // Hack for issue #140: // http://code.google.com/p/elmah/issues/detail?id=140 const string authPasswordKey = "AUTH_PASSWORD"; string authPassword = _serverVariables[authPasswordKey]; if (authPassword != null) // yes, mask empty too! _serverVariables[authPasswordKey] = "*****"; } _queryString = CopyCollection(qsfc.QueryString); _form = CopyCollection(qsfc.Form); _cookies = CopyCollection(qsfc.Cookies); // Adding total bytes of request to output, sometimes this doesn't match // the bytes sent in the header _serverVariables.Add("TOTAL_BYTES", request.TotalBytes.ToString()); // re-read the raw input from the request and put it into the output try { System.IO.Stream inputStream = request.InputStream; inputStream.Position = 0; using (System.IO.StreamReader reader = new System.IO.StreamReader(inputStream)) { _serverVariables.Add("RAW_INPUT_STREAM", reader.ReadToEnd()); } } catch (Exception) { } } var callerInfo = e.TryGetCallerInfo() ?? CallerInfo.Empty; if (!callerInfo.IsEmpty) { _detail = "# caller: " + callerInfo + System.Environment.NewLine + _detail; } } private static string TryGetHtmlErrorMessage(HttpException e) { Debug.Assert(e != null); try { return e.GetHtmlErrorMessage(); } catch (SecurityException se) { // In partial trust environments, HttpException.GetHtmlErrorMessage() // has been known to throw: // System.Security.SecurityException: Request for the // permission of type 'System.Web.AspNetHostingPermission' failed. // // See issue #179 for more background: // http://code.google.com/p/elmah/issues/detail?id=179 Trace.WriteLine(se); return null; } } /// <summary> /// Gets the <see cref="Exception"/> instance used to initialize this /// instance. /// </summary> /// <remarks> /// This is a run-time property only that is not written or read /// during XML serialization via <see cref="ErrorXml.Decode"/> and /// <see cref="ErrorXml.Encode(Error,XmlWriter)"/>. /// </remarks> public Exception Exception { get { return _exception; } } /// <summary> /// Gets or sets the name of application in which this error occurred. /// </summary> public string ApplicationName { get { return _applicationName ?? string.Empty; } set { _applicationName = value; } } /// <summary> /// Gets or sets name of host machine where this error occurred. /// </summary> public string HostName { get { return _hostName ?? string.Empty; } set { _hostName = value; } } /// <summary> /// Gets or sets the type, class or category of the error. /// </summary> public string Type { get { return _typeName ?? string.Empty; } set { _typeName = value; } } /// <summary> /// Gets or sets the source that is the cause of the error. /// </summary> public string Source { get { return _source ?? string.Empty; } set { _source = value; } } /// <summary> /// Gets or sets a brief text describing the error. /// </summary> public string Message { get { return _message ?? string.Empty; } set { _message = value; } } /// <summary> /// Gets or sets a detailed text describing the error, such as a /// stack trace. /// </summary> public string Detail { get { return _detail ?? string.Empty; } set { _detail = value; } } /// <summary> /// Gets or sets the user logged into the application at the time /// of the error. /// </summary> public string User { get { return _user ?? string.Empty; } set { _user = value; } } /// <summary> /// Gets or sets the date and time (in local time) at which the /// error occurred. /// </summary> public DateTime Time { get { return _time; } set { _time = value; } } /// <summary> /// Gets or sets the HTTP status code of the output returned to the /// client for the error. /// </summary> /// <remarks> /// For cases where this value cannot always be reliably determined, /// the value may be reported as zero. /// </remarks> public int StatusCode { get { return _statusCode; } set { _statusCode = value; } } /// <summary> /// Gets or sets the HTML message generated by the web host (ASP.NET) /// for the given error. /// </summary> public string WebHostHtmlMessage { get { return _webHostHtmlMessage ?? string.Empty; } set { _webHostHtmlMessage = value; } } /// <summary> /// Gets a collection representing the Web server variables /// captured as part of diagnostic data for the error. /// </summary> public NameValueCollection ServerVariables { get { return FaultIn(ref _serverVariables); } } /// <summary> /// Gets a collection representing the Web query string variables /// captured as part of diagnostic data for the error. /// </summary> public NameValueCollection QueryString { get { return FaultIn(ref _queryString); } } /// <summary> /// Gets a collection representing the form variables captured as /// part of diagnostic data for the error. /// </summary> public NameValueCollection Form { get { return FaultIn(ref _form); } } /// <summary> /// Gets a collection representing the client cookies /// captured as part of diagnostic data for the error. /// </summary> public NameValueCollection Cookies { get { return FaultIn(ref _cookies); } } /// <summary> /// Returns the value of the <see cref="Message"/> property. /// </summary> public override string ToString() { return this.Message; } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> object ICloneable.Clone() { // // Make a base shallow copy of all the members. // Error copy = (Error) MemberwiseClone(); // // Now make a deep copy of items that are mutable. // copy._serverVariables = CopyCollection(_serverVariables); copy._queryString = CopyCollection(_queryString); copy._form = CopyCollection(_form); copy._cookies = CopyCollection(_cookies); return copy; } private static NameValueCollection CopyCollection(NameValueCollection collection) { if (collection == null || collection.Count == 0) return null; return new NameValueCollection(collection); } private static NameValueCollection CopyCollection(HttpCookieCollection cookies) { if (cookies == null || cookies.Count == 0) return null; NameValueCollection copy = new NameValueCollection(cookies.Count); for (int i = 0; i < cookies.Count; i++) { HttpCookie cookie = cookies[i]; // // NOTE: We drop the Path and Domain properties of the // cookie for sake of simplicity. // copy.Add(cookie.Name, cookie.Value); } return copy; } private static NameValueCollection FaultIn(ref NameValueCollection collection) { if (collection == null) collection = new NameValueCollection(); return collection; } } }
namespace LuaInterface { using System; using System.IO; using System.Collections; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using Lua511; using System.Runtime.InteropServices; /* * Functions used in the metatables of userdata representing * CLR objects * * Author: Fabio Mascarenhas * Version: 1.0 */ class MetaFunctions { /* * __index metafunction for CLR objects. Implemented in Lua. */ internal static string luaIndexFunction = "local function index(obj,name)\n" + " local meta=getmetatable(obj)\n" + " local cached=meta.cache[name]\n" + " if cached~=nil then\n" + " return cached\n" + " else\n" + " local value,isFunc=get_object_member(obj,name)\n" + " if isFunc then\n" + " meta.cache[name]=value\n" + " end\n" + " return value\n" + " end\n" + "end\n" + "return index"; private ObjectTranslator translator; private Hashtable memberCache = new Hashtable(); internal LuaCSFunction gcFunction, indexFunction, newindexFunction, baseIndexFunction, classIndexFunction, classNewindexFunction, execDelegateFunction, callConstructorFunction, toStringFunction; public MetaFunctions(ObjectTranslator translator) { this.translator = translator; gcFunction = new LuaCSFunction(this.collectObject); toStringFunction = new LuaCSFunction(this.toString); indexFunction = new LuaCSFunction(this.getMethod); newindexFunction = new LuaCSFunction(this.setFieldOrProperty); baseIndexFunction = new LuaCSFunction(this.getBaseMethod); callConstructorFunction = new LuaCSFunction(this.callConstructor); classIndexFunction = new LuaCSFunction(this.getClassMethod); classNewindexFunction = new LuaCSFunction(this.setClassFieldOrProperty); execDelegateFunction = new LuaCSFunction(this.runFunctionDelegate); } /* * __call metafunction of CLR delegates, retrieves and calls the delegate. */ private int runFunctionDelegate(IntPtr luaState) { LuaCSFunction func = (LuaCSFunction)translator.getRawNetObject(luaState, 1); LuaDLL.lua_remove(luaState, 1); return func(luaState); } /* * __gc metafunction of CLR objects. */ private int collectObject(IntPtr luaState) { int udata = LuaDLL.luanet_rawnetobj(luaState, 1); if (udata != -1) { translator.collectObject(udata); } else { // Debug.WriteLine("not found: " + udata); } return 0; } /* * __tostring metafunction of CLR objects. */ private int toString(IntPtr luaState) { object obj = translator.getRawNetObject(luaState, 1); if (obj != null) { translator.push(luaState, obj.ToString() + ": " + obj.GetHashCode()); } else LuaDLL.lua_pushnil(luaState); return 1; } /// <summary> /// Debug tool to dump the lua stack /// </summary> /// FIXME, move somewhere else public static void dumpStack(ObjectTranslator translator, IntPtr luaState) { int depth = LuaDLL.lua_gettop(luaState); Debug.WriteLine("lua stack depth: " + depth); for (int i = 1; i <= depth; i++) { LuaTypes type = LuaDLL.lua_type(luaState, i); // we dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, so manually check for key types string typestr = (type == LuaTypes.LUA_TTABLE) ? "table" : LuaDLL.lua_typename(luaState, type); string strrep = LuaDLL.lua_tostring(luaState, i); if (type == LuaTypes.LUA_TUSERDATA) { object obj = translator.getRawNetObject(luaState, i); strrep = obj.ToString(); } Debug.Print("{0}: ({1}) {2}", i, typestr, strrep); } } /* * Called by the __index metafunction of CLR objects in case the * method is not cached or it is a field/property/event. * Receives the object and the member name as arguments and returns * either the value of the member or a delegate to call it. * If the member does not exist returns nil. */ private int getMethod(IntPtr luaState) { object obj = translator.getRawNetObject(luaState, 1); if (obj == null) { translator.throwError(luaState, "trying to index an invalid object reference"); LuaDLL.lua_pushnil(luaState); return 1; } object index = translator.getObject(luaState, 2); Type indexType = index.GetType(); string methodName = index as string; // will be null if not a string arg Type objType = obj.GetType(); // Handle the most common case, looking up the method by name. // CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object, // ie: xmlelement['item'] <- item is a property of xmlelement try { if (methodName != null && isMemberPresent(objType, methodName)) return getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); } catch { } // Try to access by array if the type is right and index is an int (lua numbers always come across as double) if (objType.IsArray && index is double) { int intIndex = (int)((double)index); if (objType.UnderlyingSystemType == typeof(float[])) { float[] arr = ((float[])obj); translator.push(luaState, arr[intIndex]); } else if (objType.UnderlyingSystemType == typeof(double[])) { double[] arr = ((double[])obj); translator.push(luaState, arr[intIndex]); } else if (objType.UnderlyingSystemType == typeof(int[])) { int[] arr = ((int[])obj); translator.push(luaState, arr[intIndex]); } else { object[] arr = (object[])obj; translator.push(luaState, arr[intIndex]); } } else { // Try to use get_Item to index into this .net object //MethodInfo getter = objType.GetMethod("get_Item"); MethodInfo[] methods = objType.GetMethods(); foreach (MethodInfo mInfo in methods) { if (mInfo.Name == "get_Item") { //check if the signature matches the input if (mInfo.GetParameters().Length == 1) { MethodInfo getter = mInfo; ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null; if (actualParms == null || actualParms.Length != 1) { translator.throwError(luaState, "method not found (or no indexer): " + index); LuaDLL.lua_pushnil(luaState); } else { // Get the index in a form acceptable to the getter index = translator.getAsType(luaState, 2, actualParms[0].ParameterType); object[] args = new object[1]; // Just call the indexer - if out of bounds an exception will happen args[0] = index; try { object result = getter.Invoke(obj, args); translator.push(luaState, result); } catch (TargetInvocationException e) { // Provide a more readable description for the common case of key not found if (e.InnerException is KeyNotFoundException) translator.throwError(luaState, "key '" + index + "' not found "); else translator.throwError(luaState, "exception indexing '" + index + "' " + e.Message); LuaDLL.lua_pushnil(luaState); } } } } } } LuaDLL.lua_pushboolean(luaState, false); return 2; } /* * __index metafunction of base classes (the base field of Lua tables). * Adds a prefix to the method name to call the base version of the method. */ private int getBaseMethod(IntPtr luaState) { object obj = translator.getRawNetObject(luaState, 1); if (obj == null) { translator.throwError(luaState, "trying to index an invalid object reference"); LuaDLL.lua_pushnil(luaState); LuaDLL.lua_pushboolean(luaState, false); return 2; } string methodName = LuaDLL.lua_tostring(luaState, 2); if (methodName == null) { LuaDLL.lua_pushnil(luaState); LuaDLL.lua_pushboolean(luaState, false); return 2; } getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); LuaDLL.lua_settop(luaState, -2); if (LuaDLL.lua_type(luaState, -1) == LuaTypes.LUA_TNIL) { LuaDLL.lua_settop(luaState, -2); return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); } LuaDLL.lua_pushboolean(luaState, false); return 2; } /// <summary> /// Does this method exist as either an instance or static? /// </summary> /// <param name="objType"></param> /// <param name="methodName"></param> /// <returns></returns> bool isMemberPresent(IReflect objType, string methodName) { object cachedMember = checkMemberCache(memberCache, objType, methodName); if (cachedMember != null) return true; //CP: Removed NonPublic binding search MemberInfo[] members = objType.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase/* | BindingFlags.NonPublic*/); return (members.Length > 0); } /* * Pushes the value of a member or a delegate to call it, depending on the type of * the member. Works with static or instance members. * Uses reflection to find members, and stores the reflected MemberInfo object in * a cache (indexed by the type of the object and the name of the member). */ private int getMember(IntPtr luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType) { bool implicitStatic = false; MemberInfo member = null; object cachedMember = checkMemberCache(memberCache, objType, methodName); //object cachedMember=null; if (cachedMember is LuaCSFunction) { translator.pushFunction(luaState, (LuaCSFunction)cachedMember); translator.push(luaState, true); return 2; } else if (cachedMember != null) { member = (MemberInfo)cachedMember; } else { //CP: Removed NonPublic binding search MemberInfo[] members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); if (members.Length > 0) member = members[0]; else { // If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static // lookups for fields/properties/events -kevinh //CP: Removed NonPublic binding search and made case insensitive members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); if (members.Length > 0) { member = members[0]; implicitStatic = true; } } } if (member != null) { if (member.MemberType == MemberTypes.Field) { FieldInfo field = (FieldInfo)member; if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); try { translator.push(luaState, field.GetValue(obj)); } catch { LuaDLL.lua_pushnil(luaState); } } else if (member.MemberType == MemberTypes.Property) { PropertyInfo property = (PropertyInfo)member; if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); try { object val = property.GetValue(obj, null); translator.push(luaState, val); } catch (ArgumentException) { // If we can't find the getter in our class, recurse up to the base class and see // if they can help. if (objType is Type && !(((Type)objType) == typeof(object))) return getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType); else LuaDLL.lua_pushnil(luaState); } catch (TargetInvocationException e) // Convert this exception into a Lua error { ThrowError(luaState, e); LuaDLL.lua_pushnil(luaState); } } else if (member.MemberType == MemberTypes.Event) { EventInfo eventInfo = (EventInfo)member; if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo)); } else if (!implicitStatic) { if (member.MemberType == MemberTypes.NestedType) { // kevinh - added support for finding nested types // cache us if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); // Find the name of our class string name = member.Name; Type dectype = member.DeclaringType; // Build a new long name and try to find the type by name string longname = dectype.FullName + "+" + name; Type nestedType = translator.FindType(longname); translator.pushType(luaState, nestedType); } else { // Member type must be 'method' LuaCSFunction wrapper = new LuaCSFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call); if (cachedMember == null) setMemberCache(memberCache, objType, methodName, wrapper); translator.pushFunction(luaState, wrapper); translator.push(luaState, true); return 2; } } else { // If we reach this point we found a static method, but can't use it in this context because the user passed in an instance translator.throwError(luaState, "can't pass instance to static method " + methodName); LuaDLL.lua_pushnil(luaState); } } else { // kevinh - we want to throw an exception because meerly returning 'nil' in this case // is not sufficient. valid data members may return nil and therefore there must be some // way to know the member just doesn't exist. translator.throwError(luaState, "unknown member name " + methodName); LuaDLL.lua_pushnil(luaState); } // push false because we are NOT returning a function (see luaIndexFunction) translator.push(luaState, false); return 2; } /* * Checks if a MemberInfo object is cached, returning it or null. */ private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName) { Hashtable members = (Hashtable)memberCache[objType]; if (members != null) return members[memberName]; else return null; } /* * Stores a MemberInfo object in the member cache. */ private void setMemberCache(Hashtable memberCache, IReflect objType, string memberName, object member) { Hashtable members = (Hashtable)memberCache[objType]; if (members == null) { members = new Hashtable(); memberCache[objType] = members; } members[memberName] = member; } /* * __newindex metafunction of CLR objects. Receives the object, * the member name and the value to be stored as arguments. Throws * and error if the assignment is invalid. */ private int setFieldOrProperty(IntPtr luaState) { object target = translator.getRawNetObject(luaState, 1); if (target == null) { translator.throwError(luaState, "trying to index and invalid object reference"); return 0; } Type type = target.GetType(); // First try to look up the parameter as a property name string detailMessage; bool didMember = trySetMember(luaState, type, target, BindingFlags.Instance | BindingFlags.IgnoreCase, out detailMessage); if (didMember) return 0; // Must have found the property name // We didn't find a property name, now see if we can use a [] style this accessor to set array contents try { if (type.IsArray && LuaDLL.lua_isnumber(luaState, 2)) { int index = (int)LuaDLL.lua_tonumber(luaState, 2); Array arr = (Array)target; object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType()); arr.SetValue(val, index); } else { // Try to see if we have a this[] accessor MethodInfo setter = type.GetMethod("set_Item"); if (setter != null) { ParameterInfo[] args = setter.GetParameters(); Type valueType = args[1].ParameterType; // The new val ue the user specified object val = translator.getAsType(luaState, 3, valueType); Type indexType = args[0].ParameterType; object index = translator.getAsType(luaState, 2, indexType); object[] methodArgs = new object[2]; // Just call the indexer - if out of bounds an exception will happen methodArgs[0] = index; methodArgs[1] = val; setter.Invoke(target, methodArgs); } else { translator.throwError(luaState, detailMessage); // Pass the original message from trySetMember because it is probably best } } } catch (SEHException) { // If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it throw; } catch (Exception e) { ThrowError(luaState, e); } return 0; } /// <summary> /// Tries to set a named property or field /// </summary> /// <param name="luaState"></param> /// <param name="targetType"></param> /// <param name="target"></param> /// <param name="bindingType"></param> /// <returns>false if unable to find the named member, true for success</returns> private bool trySetMember(IntPtr luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage) { detailMessage = null; // No error yet // If not already a string just return - we don't want to call tostring - which has the side effect of // changing the lua typecode to string // Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to // be true for isstring. if (LuaDLL.lua_type(luaState, 2) != LuaTypes.LUA_TSTRING) { detailMessage = "property names must be strings"; return false; } // We only look up property names by string string fieldName = LuaDLL.lua_tostring(luaState, 2); if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_')) { detailMessage = "invalid property name"; return false; } // Find our member via reflection or the cache MemberInfo member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName); if (member == null) { //CP: Removed NonPublic binding search and made case insensitive MemberInfo[] members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); if (members.Length > 0) { member = members[0]; setMemberCache(memberCache, targetType, fieldName, member); } else { detailMessage = "field or property '" + fieldName + "' does not exist"; return false; } } if (member.MemberType == MemberTypes.Field) { FieldInfo field = (FieldInfo)member; object val = translator.getAsType(luaState, 3, field.FieldType); try { field.SetValue(target, val); } catch (Exception e) { ThrowError(luaState, e); } // We did a call return true; } else if (member.MemberType == MemberTypes.Property) { PropertyInfo property = (PropertyInfo)member; object val = translator.getAsType(luaState, 3, property.PropertyType); try { property.SetValue(target, val, null); } catch (Exception e) { ThrowError(luaState, e); } // We did a call return true; } detailMessage = "'" + fieldName + "' is not a .net field or property"; return false; } /* * Writes to fields or properties, either static or instance. Throws an error * if the operation is invalid. */ private int setMember(IntPtr luaState, IReflect targetType, object target, BindingFlags bindingType) { string detail; bool success = trySetMember(luaState, targetType, target, bindingType, out detail); if (!success) translator.throwError(luaState, detail); return 0; } /// <summary> /// Convert a C# exception into a Lua error /// </summary> /// <param name="e"></param> /// We try to look into the exception to give the most meaningful description void ThrowError(IntPtr luaState, Exception e) { // If we got inside a reflection show what really happened TargetInvocationException te = e as TargetInvocationException; if (te != null) e = te.InnerException; translator.throwError(luaState, e); } /* * __index metafunction of type references, works on static members. */ private int getClassMethod(IntPtr luaState) { IReflect klass; object obj = translator.getRawNetObject(luaState, 1); if (obj == null || !(obj is IReflect)) { translator.throwError(luaState, "trying to index an invalid type reference"); LuaDLL.lua_pushnil(luaState); return 1; } else klass = (IReflect)obj; if (LuaDLL.lua_isnumber(luaState, 2)) { int size = (int)LuaDLL.lua_tonumber(luaState, 2); translator.push(luaState, Array.CreateInstance(klass.UnderlyingSystemType, size)); return 1; } else { string methodName = LuaDLL.lua_tostring(luaState, 2); if (methodName == null) { LuaDLL.lua_pushnil(luaState); return 1; } //CP: Ignore case else return getMember(luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase); } } /* * __newindex function of type references, works on static members. */ private int setClassFieldOrProperty(IntPtr luaState) { IReflect target; object obj = translator.getRawNetObject(luaState, 1); if (obj == null || !(obj is IReflect)) { translator.throwError(luaState, "trying to index an invalid type reference"); return 0; } else target = (IReflect)obj; return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase); } /* * __call metafunction of type references. Searches for and calls * a constructor for the type. Returns nil if the constructor is not * found or if the arguments are invalid. Throws an error if the constructor * generates an exception. */ private int callConstructor(IntPtr luaState) { MethodCache validConstructor = new MethodCache(); IReflect klass; object obj = translator.getRawNetObject(luaState, 1); if (obj == null || !(obj is IReflect)) { translator.throwError(luaState, "trying to call constructor on an invalid type reference"); LuaDLL.lua_pushnil(luaState); return 1; } else klass = (IReflect)obj; LuaDLL.lua_remove(luaState, 1); ConstructorInfo[] constructors = klass.UnderlyingSystemType.GetConstructors(); foreach (ConstructorInfo constructor in constructors) { bool isConstructor = matchParameters(luaState, constructor, ref validConstructor); if (isConstructor) { try { translator.push(luaState, constructor.Invoke(validConstructor.args)); } catch (TargetInvocationException e) { ThrowError(luaState, e); LuaDLL.lua_pushnil(luaState); } catch { LuaDLL.lua_pushnil(luaState); } return 1; } } string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name; translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match", klass.UnderlyingSystemType, constructorName)); LuaDLL.lua_pushnil(luaState); return 1; } private static bool IsInteger(double x) { return Math.Ceiling(x) == x; } internal Array TableToArray (Func<int, object> luaParamValueExtractor, Type paramArrayType, int startIndex, int count) { Array paramArray; if (count == 0) return Array.CreateInstance (paramArrayType, 0); var luaParamValue = luaParamValueExtractor (startIndex); #if false // LuaTable unpacking is disabled. // In Lua, print({1, 2, 3}) should pass an array, not multiple arguments. // You can write print(unpack({1, 2, 3})) if necessary. if (luaParamValue is LuaTable) { LuaTable table = (LuaTable)luaParamValue; IDictionaryEnumerator tableEnumerator = table.GetEnumerator (); tableEnumerator.Reset (); paramArray = Array.CreateInstance (paramArrayType, table.Values.Count); int paramArrayIndex = 0; while (tableEnumerator.MoveNext ()) { object value = tableEnumerator.Value; if (paramArrayType == typeof (object)) { if (value != null && value.GetType () == typeof (double) && IsInteger ((double)value)) value = Convert.ToInt32 ((double)value); } paramArray.SetValue (Convert.ChangeType (value, paramArrayType), paramArrayIndex); paramArrayIndex++; } } else #endif { paramArray = Array.CreateInstance (paramArrayType, count); paramArray.SetValue (luaParamValue, 0); for (int i = 1; i < count; i++) { startIndex++; var value = luaParamValueExtractor (startIndex); paramArray.SetValue (value, i); } } return paramArray; } /* * Matches a method against its arguments in the Lua stack. Returns * if the match was succesful. It it was also returns the information * necessary to invoke the method. */ internal bool matchParameters(IntPtr luaState, MethodBase method, ref MethodCache methodCache) { ExtractValue extractValue; bool isMethod = true; var paramInfo = method.GetParameters (); int currentLuaParam = 1; int nLuaParams = LuaDLL.lua_gettop(luaState); var paramList = new List<object> (); var outList = new List<int> (); var argTypes = new List<MethodArgs> (); foreach (var currentNetParam in paramInfo) { if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params { paramList.Add (null); outList.Add (paramList.LastIndexOf (null)); } else if (currentLuaParam <= nLuaParams && _IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) { // Type checking var value = extractValue (luaState, currentLuaParam); paramList.Add (value); int index = paramList.LastIndexOf (value); var methodArg = new MethodArgs (); methodArg.index = index; methodArg.extractValue = extractValue; argTypes.Add (methodArg); if (currentNetParam.ParameterType.IsByRef) outList.Add (index); currentLuaParam++; } // Type does not match, ignore if the parameter is optional else if (_IsParamsArray (luaState, currentLuaParam, currentNetParam, out extractValue)) { var paramArrayType = currentNetParam.ParameterType.GetElementType (); Func<int, object> extractDelegate = (currentParam) => { currentLuaParam ++; return extractValue (luaState, currentParam); }; int count = (nLuaParams - currentLuaParam) + 1; Array paramArray = TableToArray (extractDelegate, paramArrayType, currentLuaParam, count); paramList.Add (paramArray); int index = paramList.LastIndexOf (paramArray); var methodArg = new MethodArgs (); methodArg.index = index; methodArg.extractValue = extractValue; methodArg.isParamsArray = true; methodArg.paramsArrayType = paramArrayType; argTypes.Add (methodArg); } else if (currentLuaParam > nLuaParams) { // Adds optional parameters if (currentNetParam.IsOptional) paramList.Add (currentNetParam.DefaultValue); else { isMethod = false; break; } } else if (currentNetParam.IsOptional) paramList.Add (currentNetParam.DefaultValue); else { // No match isMethod = false; break; } } if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match isMethod = false; if (isMethod) { methodCache.args = paramList.ToArray (); methodCache.cachedMethod = method; methodCache.outList = outList.ToArray (); methodCache.argTypes = argTypes.ToArray (); } return isMethod; } /// <summary> /// CP: Fix for operator overloading failure /// Returns true if the type is set and assigns the extract value /// </summary> /// <param name="luaState"></param> /// <param name="currentLuaParam"></param> /// <param name="currentNetParam"></param> /// <param name="extractValue"></param> /// <returns></returns> private bool _IsTypeCorrect(IntPtr luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue) { try { return (extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, currentNetParam.ParameterType)) != null; } catch { extractValue = null; Debug.WriteLine("Type wasn't correct"); return false; } } private bool _IsParamsArray(IntPtr luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue) { extractValue = null; if (currentNetParam.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0) { LuaTypes luaType; try { luaType = LuaDLL.lua_type(luaState, currentLuaParam); } catch (Exception ex) { Debug.WriteLine("Could not retrieve lua type while attempting to determine params Array Status."); Debug.WriteLine(ex.Message); extractValue = null; return false; } if (luaType == LuaTypes.LUA_TTABLE) { try { extractValue = translator.typeChecker.getExtractor(typeof(LuaTable)); } catch (Exception ex) { Debug.WriteLine("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status."); } if (extractValue != null) { return true; } } else { Type paramElementType = currentNetParam.ParameterType.GetElementType(); try { extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, paramElementType); } catch (Exception ex) { Debug.WriteLine(string.Format("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName)); } if (extractValue != null) { return true; } } } Debug.WriteLine("Type wasn't Params object."); return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Net.Sockets; using System.Text; namespace System.Net { /// <summary> /// <para> /// Implements basic sending and receiving of network commands. /// Handles generic parsing of server responses and provides /// a pipeline sequencing mechanism for sending the commands to the server. /// </para> /// </summary> internal class CommandStream : NetworkStreamWrapper { private static readonly AsyncCallback s_writeCallbackDelegate = new AsyncCallback(WriteCallback); private static readonly AsyncCallback s_readCallbackDelegate = new AsyncCallback(ReadCallback); private bool _recoverableFailure; // // Active variables used for the command state machine // protected WebRequest _request; protected bool _isAsync; private bool _aborted; protected PipelineEntry[] _commands; protected int _index; private bool _doRead; private bool _doSend; private ResponseDescription _currentResponseDescription; protected string _abortReason; internal CommandStream(TcpClient client) : base(client) { _decoder = _encoding.GetDecoder(); } internal virtual void Abort(Exception e) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "closing control Stream"); lock (this) { if (_aborted) return; _aborted = true; } try { base.Close(0); } finally { if (e != null) { InvokeRequestCallback(e); } else { InvokeRequestCallback(null); } } } protected override void Dispose(bool disposing) { if (NetEventSource.IsEnabled) NetEventSource.Info(this); InvokeRequestCallback(null); // Do not call base.Dispose(bool), which would close the web request. // This stream effectively should be a wrapper around a web // request that does not own the web request. } protected void InvokeRequestCallback(object obj) { WebRequest webRequest = _request; if (webRequest != null) { FtpWebRequest ftpWebRequest = (FtpWebRequest)webRequest; ftpWebRequest.RequestCallback(obj); } } internal bool RecoverableFailure { get { return _recoverableFailure; } } protected void MarkAsRecoverableFailure() { if (_index <= 1) { _recoverableFailure = true; } } internal Stream SubmitRequest(WebRequest request, bool isAsync, bool readInitalResponseOnConnect) { ClearState(); PipelineEntry[] commands = BuildCommandsList(request); InitCommandPipeline(request, commands, isAsync); if (readInitalResponseOnConnect) { _doSend = false; _index = -1; } return ContinueCommandPipeline(); } protected virtual void ClearState() { InitCommandPipeline(null, null, false); } protected virtual PipelineEntry[] BuildCommandsList(WebRequest request) { return null; } protected Exception GenerateException(string message, WebExceptionStatus status, Exception innerException) { return new WebException( message, innerException, status, null /* no response */ ); } protected Exception GenerateException(FtpStatusCode code, string statusDescription, Exception innerException) { return new WebException(SR.Format(SR.net_ftp_servererror, NetRes.GetWebStatusCodeString(code, statusDescription)), innerException, WebExceptionStatus.ProtocolError, null); } protected void InitCommandPipeline(WebRequest request, PipelineEntry[] commands, bool isAsync) { _commands = commands; _index = 0; _request = request; _aborted = false; _doRead = true; _doSend = true; _currentResponseDescription = null; _isAsync = isAsync; _recoverableFailure = false; _abortReason = string.Empty; } internal void CheckContinuePipeline() { if (_isAsync) return; try { ContinueCommandPipeline(); } catch (Exception e) { Abort(e); } } /// Pipelined command resolution. /// How this works: /// A list of commands that need to be sent to the FTP server are spliced together into an array, /// each command such STOR, PORT, etc, is sent to the server, then the response is parsed into a string, /// with the response, the delegate is called, which returns an instruction (either continue, stop, or read additional /// responses from server). protected Stream ContinueCommandPipeline() { // In async case, The BeginWrite can actually result in a // series of synchronous completions that eventually close // the connection. So we need to save the members that // we need to access, since they may not be valid after // BeginWrite returns bool isAsync = _isAsync; while (_index < _commands.Length) { if (_doSend) { if (_index < 0) throw new InternalException(); byte[] sendBuffer = Encoding.GetBytes(_commands[_index].Command); if (NetEventSource.Log.IsEnabled()) { string sendCommand = _commands[_index].Command.Substring(0, _commands[_index].Command.Length - 2); if (_commands[_index].HasFlag(PipelineEntryFlags.DontLogParameter)) { int index = sendCommand.IndexOf(' '); if (index != -1) sendCommand = string.Concat(sendCommand.AsSpan(0, index), " ********"); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Sending command {sendCommand}"); } try { if (isAsync) { BeginWrite(sendBuffer, 0, sendBuffer.Length, s_writeCallbackDelegate, this); } else { Write(sendBuffer, 0, sendBuffer.Length); } } catch (IOException) { MarkAsRecoverableFailure(); throw; } catch { throw; } if (isAsync) { return null; } } Stream stream = null; bool isReturn = PostSendCommandProcessing(ref stream); if (isReturn) { return stream; } } lock (this) { Close(); } return null; } private bool PostSendCommandProcessing(ref Stream stream) { if (_doRead) { // In async case, the next call can actually result in a // series of synchronous completions that eventually close // the connection. So we need to save the members that // we need to access, since they may not be valid after the // next call returns bool isAsync = _isAsync; int index = _index; PipelineEntry[] commands = _commands; try { ResponseDescription response = ReceiveCommandResponse(); if (isAsync) { return true; } _currentResponseDescription = response; } catch { // If we get an exception on the QUIT command (which is // always the last command), ignore the final exception // and continue with the pipeline regardlss of sync/async if (index < 0 || index >= commands.Length || commands[index].Command != "QUIT\r\n") throw; } } return PostReadCommandProcessing(ref stream); } private bool PostReadCommandProcessing(ref Stream stream) { if (_index >= _commands.Length) return false; // Set up front to prevent a race condition on result == PipelineInstruction.Pause _doSend = false; _doRead = false; PipelineInstruction result; PipelineEntry entry; if (_index == -1) entry = null; else entry = _commands[_index]; // Final QUIT command may get exceptions since the connection // may be already closed by the server. So there is no response // to process, just advance the pipeline to continue. if (_currentResponseDescription == null && entry.Command == "QUIT\r\n") result = PipelineInstruction.Advance; else result = PipelineCallback(entry, _currentResponseDescription, false, ref stream); if (result == PipelineInstruction.Abort) { Exception exception; if (_abortReason != string.Empty) exception = new WebException(_abortReason); else exception = GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null); Abort(exception); throw exception; } else if (result == PipelineInstruction.Advance) { _currentResponseDescription = null; _doSend = true; _doRead = true; _index++; } else if (result == PipelineInstruction.Pause) { // PipelineCallback did an async operation and will have to re-enter again. // Hold on for now. return true; } else if (result == PipelineInstruction.GiveStream) { // We will have another response coming, don't send _currentResponseDescription = null; _doRead = true; if (_isAsync) { // If they block in the requestcallback we should still continue the pipeline ContinueCommandPipeline(); InvokeRequestCallback(stream); } return true; } else if (result == PipelineInstruction.Reread) { // Another response is expected after this one _currentResponseDescription = null; _doRead = true; } return false; } internal enum PipelineInstruction { Abort, // aborts the pipeline Advance, // advances to the next pipelined command Pause, // Let async callback to continue the pipeline Reread, // rereads from the command socket GiveStream, // returns with open data stream, let stream close to continue } [Flags] internal enum PipelineEntryFlags { UserCommand = 0x1, GiveDataStream = 0x2, CreateDataConnection = 0x4, DontLogParameter = 0x8 } internal class PipelineEntry { internal PipelineEntry(string command) { Command = command; } internal PipelineEntry(string command, PipelineEntryFlags flags) { Command = command; Flags = flags; } internal bool HasFlag(PipelineEntryFlags flags) { return (Flags & flags) != 0; } internal string Command; internal PipelineEntryFlags Flags; } protected virtual PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream) { return PipelineInstruction.Abort; } // // I/O callback methods // private static void ReadCallback(IAsyncResult asyncResult) { ReceiveState state = (ReceiveState)asyncResult.AsyncState; try { Stream stream = (Stream)state.Connection; int bytesRead = 0; try { bytesRead = stream.EndRead(asyncResult); if (bytesRead == 0) state.Connection.CloseSocket(); } catch (IOException) { state.Connection.MarkAsRecoverableFailure(); throw; } catch { throw; } state.Connection.ReceiveCommandResponseCallback(state, bytesRead); } catch (Exception e) { state.Connection.Abort(e); } } private static void WriteCallback(IAsyncResult asyncResult) { CommandStream connection = (CommandStream)asyncResult.AsyncState; try { try { connection.EndWrite(asyncResult); } catch (IOException) { connection.MarkAsRecoverableFailure(); throw; } catch { throw; } Stream stream = null; if (connection.PostSendCommandProcessing(ref stream)) return; connection.ContinueCommandPipeline(); } catch (Exception e) { connection.Abort(e); } } // // Read parsing methods and privates // private string _buffer = string.Empty; private Encoding _encoding = Encoding.UTF8; private Decoder _decoder; protected Encoding Encoding { get { return _encoding; } set { _encoding = value; _decoder = _encoding.GetDecoder(); } } /// <summary> /// This function is implemented in a derived class to determine whether a response is valid, and when it is complete. /// </summary> protected virtual bool CheckValid(ResponseDescription response, ref int validThrough, ref int completeLength) { return false; } /// <summary> /// Kicks off an asynchronous or sync request to receive a response from the server. /// Uses the Encoding <code>encoding</code> to transform the bytes received into a string to be /// returned in the GeneralResponseDescription's StatusDescription field. /// </summary> private ResponseDescription ReceiveCommandResponse() { // These are the things that will be needed to maintain state. ReceiveState state = new ReceiveState(this); try { // If a string of nonzero length was decoded from the buffered bytes after the last complete response, then we // will use this string as our first string to append to the response StatusBuffer, and we will // forego a Connection.Receive here. if (_buffer.Length > 0) { ReceiveCommandResponseCallback(state, -1); } else { int bytesRead; try { if (_isAsync) { BeginRead(state.Buffer, 0, state.Buffer.Length, s_readCallbackDelegate, state); return null; } else { bytesRead = Read(state.Buffer, 0, state.Buffer.Length); if (bytesRead == 0) CloseSocket(); ReceiveCommandResponseCallback(state, bytesRead); } } catch (IOException) { MarkAsRecoverableFailure(); throw; } catch { throw; } } } catch (Exception e) { if (e is WebException) throw; throw GenerateException(SR.net_ftp_receivefailure, WebExceptionStatus.ReceiveFailure, e); } return state.Resp; } /// <summary> /// ReceiveCommandResponseCallback is the main "while loop" of the ReceiveCommandResponse function family. /// In general, what is does is perform an EndReceive() to complete the previous retrieval of bytes from the /// server (unless it is using a buffered response) It then processes what is received by using the /// implementing class's CheckValid() function, as described above. If the response is complete, it returns the single complete /// response in the GeneralResponseDescription created in BeginReceiveComamndResponse, and buffers the rest as described above. /// /// If the response is not complete, it issues another Connection.BeginReceive, with callback ReceiveCommandResponse2, /// so the action will continue at the next invocation of ReceiveCommandResponse2. /// </summary> private void ReceiveCommandResponseCallback(ReceiveState state, int bytesRead) { // completeLength will be set to a nonnegative number by CheckValid if the response is complete: // it will set completeLength to the length of a complete response. int completeLength = -1; while (true) { int validThrough = state.ValidThrough; // passed to checkvalid // If we have a Buffered response (ie data was received with the last response that was past the end of that response) // deal with it as if we had just received it now instead of actually doing another receive if (_buffer.Length > 0) { // Append the string we got from the buffer, and flush it out. state.Resp.StatusBuffer.Append(_buffer); _buffer = string.Empty; // invoke checkvalid. if (!CheckValid(state.Resp, ref validThrough, ref completeLength)) { throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null); } } else // we did a Connection.BeginReceive. Note that in this case, all bytes received are in the receive buffer (because bytes from // the buffer were transferred there if necessary { // this indicates the connection was closed. if (bytesRead <= 0) { throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null); } // decode the bytes in the receive buffer into a string, append it to the statusbuffer, and invoke checkvalid. // Decoder automatically takes care of caching partial codepoints at the end of a buffer. char[] chars = new char[_decoder.GetCharCount(state.Buffer, 0, bytesRead)]; int numChars = _decoder.GetChars(state.Buffer, 0, bytesRead, chars, 0, false); string szResponse = new string(chars, 0, numChars); state.Resp.StatusBuffer.Append(szResponse); if (!CheckValid(state.Resp, ref validThrough, ref completeLength)) { throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null); } // If the response is complete, then determine how many characters are left over...these bytes need to be set into Buffer. if (completeLength >= 0) { int unusedChars = state.Resp.StatusBuffer.Length - completeLength; if (unusedChars > 0) { _buffer = szResponse.Substring(szResponse.Length - unusedChars, unusedChars); } } } // Now, in general, if the response is not complete, update the "valid through" length for the efficiency of checkValid, // and perform the next receive. // Note that there may NOT be bytes in the beginning of the receive buffer (even if there were partial characters left over after the // last encoding), because they get tracked in the Decoder. if (completeLength < 0) { state.ValidThrough = validThrough; try { if (_isAsync) { BeginRead(state.Buffer, 0, state.Buffer.Length, s_readCallbackDelegate, state); return; } else { bytesRead = Read(state.Buffer, 0, state.Buffer.Length); if (bytesRead == 0) CloseSocket(); continue; } } catch (IOException) { MarkAsRecoverableFailure(); throw; } catch { throw; } } // The response is completed break; } // Otherwise, we have a complete response. string responseString = state.Resp.StatusBuffer.ToString(); state.Resp.StatusDescription = responseString.Substring(0, completeLength); // Set the StatusDescription to the complete part of the response. Note that the Buffer has already been taken care of above. if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Received response: {responseString.Substring(0, completeLength - 2)}"); if (_isAsync) { // Tell who is listening what was received. if (state.Resp != null) { _currentResponseDescription = state.Resp; } Stream stream = null; if (PostReadCommandProcessing(ref stream)) return; ContinueCommandPipeline(); } } } // class CommandStream /// <summary> /// Contains the parsed status line from the server /// </summary> internal class ResponseDescription { internal const int NoStatus = -1; internal bool Multiline = false; internal int Status = NoStatus; internal string StatusDescription; internal StringBuilder StatusBuffer = new StringBuilder(); internal string StatusCodeString; internal bool PositiveIntermediate { get { return (Status >= 100 && Status <= 199); } } internal bool PositiveCompletion { get { return (Status >= 200 && Status <= 299); } } internal bool TransientFailure { get { return (Status >= 400 && Status <= 499); } } internal bool PermanentFailure { get { return (Status >= 500 && Status <= 599); } } internal bool InvalidStatusCode { get { return (Status < 100 || Status > 599); } } } /// <summary> /// State information that is used during ReceiveCommandResponse()'s async operations /// </summary> internal class ReceiveState { private const int bufferSize = 1024; internal ResponseDescription Resp; internal int ValidThrough; internal byte[] Buffer; internal CommandStream Connection; internal ReceiveState(CommandStream connection) { Connection = connection; Resp = new ResponseDescription(); Buffer = new byte[bufferSize]; //1024 ValidThrough = 0; } } } // namespace System.Net
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the RisTipoTelefono class. /// </summary> [Serializable] public partial class RisTipoTelefonoCollection : ActiveList<RisTipoTelefono, RisTipoTelefonoCollection> { public RisTipoTelefonoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RisTipoTelefonoCollection</returns> public RisTipoTelefonoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { RisTipoTelefono o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the RIS_TipoTelefono table. /// </summary> [Serializable] public partial class RisTipoTelefono : ActiveRecord<RisTipoTelefono>, IActiveRecord { #region .ctors and Default Settings public RisTipoTelefono() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public RisTipoTelefono(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public RisTipoTelefono(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public RisTipoTelefono(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("RIS_TipoTelefono", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdTipoTelefono = new TableSchema.TableColumn(schema); colvarIdTipoTelefono.ColumnName = "idTipoTelefono"; colvarIdTipoTelefono.DataType = DbType.Int32; colvarIdTipoTelefono.MaxLength = 0; colvarIdTipoTelefono.AutoIncrement = true; colvarIdTipoTelefono.IsNullable = false; colvarIdTipoTelefono.IsPrimaryKey = true; colvarIdTipoTelefono.IsForeignKey = false; colvarIdTipoTelefono.IsReadOnly = false; colvarIdTipoTelefono.DefaultSetting = @""; colvarIdTipoTelefono.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdTipoTelefono); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.AnsiString; colvarDescripcion.MaxLength = 100; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = false; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("RIS_TipoTelefono",schema); } } #endregion #region Props [XmlAttribute("IdTipoTelefono")] [Bindable(true)] public int IdTipoTelefono { get { return GetColumnValue<int>(Columns.IdTipoTelefono); } set { SetColumnValue(Columns.IdTipoTelefono, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varDescripcion) { RisTipoTelefono item = new RisTipoTelefono(); item.Descripcion = varDescripcion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdTipoTelefono,string varDescripcion) { RisTipoTelefono item = new RisTipoTelefono(); item.IdTipoTelefono = varIdTipoTelefono; item.Descripcion = varDescripcion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdTipoTelefonoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdTipoTelefono = @"idTipoTelefono"; public static string Descripcion = @"descripcion"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
/* * 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 Mono.Addins; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim; using OpenSim.ApplicationPlugins.RegionModulesController; using OpenSim.Framework; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid; using OpenSim.Region.Framework.Interfaces; using OpenSim.Tests.Common; namespace OpenSim.Region.Framework.Scenes.Tests { public class SharedRegionModuleTests : OpenSimTestCase { // [Test] public void TestLifecycle() { TestHelpers.InMethod(); TestHelpers.EnableLogging(); UUID estateOwnerId = TestHelpers.ParseTail(0x1); UUID regionId = TestHelpers.ParseTail(0x10); IConfigSource configSource = new IniConfigSource(); configSource.AddConfig("Startup"); configSource.AddConfig("Modules"); // // We use this to skip estate questions // Turns out not to be needed is estate owner id is pre-set in region information. // IConfig estateConfig = configSource.AddConfig(OpenSimBase.ESTATE_SECTION_NAME); // estateConfig.Set("DefaultEstateOwnerName", "Zaphod Beeblebrox"); // estateConfig.Set("DefaultEstateOwnerUUID", estateOwnerId); // estateConfig.Set("DefaultEstateOwnerEMail", "zaphod@galaxy.com"); // estateConfig.Set("DefaultEstateOwnerPassword", "two heads"); // For grid servic configSource.AddConfig("GridService"); configSource.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector"); configSource.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData"); configSource.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService"); configSource.Configs["GridService"].Set("ConnectionString", "!static"); LocalGridServicesConnector gridService = new LocalGridServicesConnector(); // OpenSim sim = new OpenSim(configSource); sim.SuppressExit = true; sim.EnableInitialPluginLoad = false; sim.LoadEstateDataService = false; sim.NetServersInfo.HttpListenerPort = 0; IRegistryCore reg = sim.ApplicationRegistry; RegionInfo ri = new RegionInfo(); ri.RegionID = regionId; ri.EstateSettings.EstateOwner = estateOwnerId; ri.InternalEndPoint = new IPEndPoint(0, 0); MockRegionModulesControllerPlugin rmcp = new MockRegionModulesControllerPlugin(); sim.m_plugins = new List<IApplicationPlugin>() { rmcp }; reg.RegisterInterface<IRegionModulesController>(rmcp); // XXX: Have to initialize directly for now rmcp.Initialise(sim); rmcp.AddNode(gridService); TestSharedRegion tsr = new TestSharedRegion(); rmcp.AddNode(tsr); // FIXME: Want to use the real one eventually but this is currently directly tied into Mono.Addins // which has been written in such a way that makes it impossible to use for regression tests. // RegionModulesControllerPlugin rmcp = new RegionModulesControllerPlugin(); // rmcp.LoadModulesFromAddins = false; //// reg.RegisterInterface<IRegionModulesController>(rmcp); // rmcp.Initialise(sim); // rmcp.PostInitialise(); // TypeExtensionNode node = new TypeExtensionNode(); // node. // rmcp.AddNode(node, configSource.Configs["Modules"], new Dictionary<RuntimeAddin, IList<int>>()); sim.Startup(); IScene scene; sim.CreateRegion(ri, out scene); sim.Shutdown(); List<string> co = tsr.CallOrder; int expectedEventCount = 6; Assert.AreEqual( expectedEventCount, co.Count, "Expected {0} events but only got {1} ({2})", expectedEventCount, co.Count, string.Join(",", co)); Assert.AreEqual("Initialise", co[0]); Assert.AreEqual("PostInitialise", co[1]); Assert.AreEqual("AddRegion", co[2]); Assert.AreEqual("RegionLoaded", co[3]); Assert.AreEqual("RemoveRegion", co[4]); Assert.AreEqual("Close", co[5]); } } class TestSharedRegion : ISharedRegionModule { // FIXME: Should really use MethodInfo public List<string> CallOrder = new List<string>(); public string Name { get { return "TestSharedRegion"; } } public Type ReplaceableInterface { get { return null; } } public void PostInitialise() { CallOrder.Add("PostInitialise"); } public void Initialise(IConfigSource source) { CallOrder.Add("Initialise"); } public void Close() { CallOrder.Add("Close"); } public void AddRegion(Scene scene) { CallOrder.Add("AddRegion"); } public void RemoveRegion(Scene scene) { CallOrder.Add("RemoveRegion"); } public void RegionLoaded(Scene scene) { CallOrder.Add("RegionLoaded"); } } class MockRegionModulesControllerPlugin : IRegionModulesController, IApplicationPlugin { // List of shared module instances, for adding to Scenes private List<ISharedRegionModule> m_sharedInstances = new List<ISharedRegionModule>(); // Config access private OpenSimBase m_openSim; public string Version { get { return "0"; } } public string Name { get { return "MockRegionModulesControllerPlugin"; } } public void Initialise() {} public void Initialise(OpenSimBase sim) { m_openSim = sim; } /// <summary> /// Called when the application loading is completed /// </summary> public void PostInitialise() { foreach (ISharedRegionModule module in m_sharedInstances) module.PostInitialise(); } public void AddRegionToModules(Scene scene) { List<ISharedRegionModule> sharedlist = new List<ISharedRegionModule>(); foreach (ISharedRegionModule module in m_sharedInstances) { module.AddRegion(scene); scene.AddRegionModule(module.Name, module); sharedlist.Add(module); } foreach (ISharedRegionModule module in sharedlist) { module.RegionLoaded(scene); } } public void RemoveRegionFromModules(Scene scene) { foreach (IRegionModuleBase module in scene.RegionModules.Values) { // m_log.DebugFormat("[REGIONMODULE]: Removing scene {0} from module {1}", // scene.RegionInfo.RegionName, module.Name); module.RemoveRegion(scene); } scene.RegionModules.Clear(); } public void AddNode(ISharedRegionModule module) { m_sharedInstances.Add(module); module.Initialise(m_openSim.ConfigSource.Source); } public void Dispose() { // We expect that all regions have been removed already while (m_sharedInstances.Count > 0) { m_sharedInstances[0].Close(); m_sharedInstances.RemoveAt(0); } } } }
using System; using System.Globalization; using Avalonia.Animation.Animators; using Avalonia.Utilities; namespace Avalonia { /// <summary> /// Defines a point. /// </summary> public readonly struct Point : IEquatable<Point> { static Point() { Animation.Animation.RegisterAnimator<PointAnimator>(prop => typeof(Point).IsAssignableFrom(prop.PropertyType)); } /// <summary> /// The X position. /// </summary> private readonly double _x; /// <summary> /// The Y position. /// </summary> private readonly double _y; /// <summary> /// Initializes a new instance of the <see cref="Point"/> structure. /// </summary> /// <param name="x">The X position.</param> /// <param name="y">The Y position.</param> public Point(double x, double y) { _x = x; _y = y; } /// <summary> /// Gets the X position. /// </summary> public double X => _x; /// <summary> /// Gets the Y position. /// </summary> public double Y => _y; /// <summary> /// Converts the <see cref="Point"/> to a <see cref="Vector"/>. /// </summary> /// <param name="p">The point.</param> public static implicit operator Vector(Point p) { return new Vector(p._x, p._y); } /// <summary> /// Negates a point. /// </summary> /// <param name="a">The point.</param> /// <returns>The negated point.</returns> public static Point operator -(Point a) { return new Point(-a._x, -a._y); } /// <summary> /// Checks for equality between two <see cref="Point"/>s. /// </summary> /// <param name="left">The first point.</param> /// <param name="right">The second point.</param> /// <returns>True if the points are equal; otherwise false.</returns> public static bool operator ==(Point left, Point right) { return left.Equals(right); } /// <summary> /// Checks for inequality between two <see cref="Point"/>s. /// </summary> /// <param name="left">The first point.</param> /// <param name="right">The second point.</param> /// <returns>True if the points are unequal; otherwise false.</returns> public static bool operator !=(Point left, Point right) { return !(left == right); } /// <summary> /// Adds two points. /// </summary> /// <param name="a">The first point.</param> /// <param name="b">The second point.</param> /// <returns>A point that is the result of the addition.</returns> public static Point operator +(Point a, Point b) { return new Point(a._x + b._x, a._y + b._y); } /// <summary> /// Adds a vector to a point. /// </summary> /// <param name="a">The point.</param> /// <param name="b">The vector.</param> /// <returns>A point that is the result of the addition.</returns> public static Point operator +(Point a, Vector b) { return new Point(a._x + b.X, a._y + b.Y); } /// <summary> /// Subtracts two points. /// </summary> /// <param name="a">The first point.</param> /// <param name="b">The second point.</param> /// <returns>A point that is the result of the subtraction.</returns> public static Point operator -(Point a, Point b) { return new Point(a._x - b._x, a._y - b._y); } /// <summary> /// Subtracts a vector from a point. /// </summary> /// <param name="a">The point.</param> /// <param name="b">The vector.</param> /// <returns>A point that is the result of the subtraction.</returns> public static Point operator -(Point a, Vector b) { return new Point(a._x - b.X, a._y - b.Y); } /// <summary> /// Multiplies a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to multiply</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates multiplied</returns> public static Point operator *(Point p, double k) => new Point(p.X * k, p.Y * k); /// <summary> /// Multiplies a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to multiply</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates multiplied</returns> public static Point operator *(double k, Point p) => new Point(p.X * k, p.Y * k); /// <summary> /// Divides a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to divide by</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates divided</returns> public static Point operator /(Point p, double k) => new Point(p.X / k, p.Y / k); /// <summary> /// Applies a matrix to a point. /// </summary> /// <param name="point">The point.</param> /// <param name="matrix">The matrix.</param> /// <returns>The resulting point.</returns> public static Point operator *(Point point, Matrix matrix) { return new Point( (point.X * matrix.M11) + (point.Y * matrix.M21) + matrix.M31, (point.X * matrix.M12) + (point.Y * matrix.M22) + matrix.M32); } /// <summary> /// Parses a <see cref="Point"/> string. /// </summary> /// <param name="s">The string.</param> /// <returns>The <see cref="Point"/>.</returns> public static Point Parse(string s) { using (var tokenizer = new StringTokenizer(s, CultureInfo.InvariantCulture, exceptionMessage: "Invalid Point.")) { return new Point( tokenizer.ReadDouble(), tokenizer.ReadDouble() ); } } /// <summary> /// Returns a boolean indicating whether the point is equal to the other given point. /// </summary> /// <param name="other">The other point to test equality against.</param> /// <returns>True if this point is equal to other; False otherwise.</returns> public bool Equals(Point other) { // ReSharper disable CompareOfFloatsByEqualityOperator return _x == other._x && _y == other._y; // ReSharper enable CompareOfFloatsByEqualityOperator } /// <summary> /// Checks for equality between a point and an object. /// </summary> /// <param name="obj">The object.</param> /// <returns> /// True if <paramref name="obj"/> is a point that equals the current point. /// </returns> public override bool Equals(object obj) => obj is Point other && Equals(other); /// <summary> /// Returns a hash code for a <see cref="Point"/>. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { unchecked { int hash = 17; hash = (hash * 23) + _x.GetHashCode(); hash = (hash * 23) + _y.GetHashCode(); return hash; } } /// <summary> /// Returns the string representation of the point. /// </summary> /// <returns>The string representation of the point.</returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0}, {1}", _x, _y); } /// <summary> /// Transforms the point by a matrix. /// </summary> /// <param name="transform">The transform.</param> /// <returns>The transformed point.</returns> public Point Transform(Matrix transform) { var x = X; var y = Y; var xadd = y * transform.M21 + transform.M31; var yadd = x * transform.M12 + transform.M32; x *= transform.M11; x += xadd; y *= transform.M22; y += yadd; return new Point(x, y); } /// <summary> /// Returns a new point with the specified X coordinate. /// </summary> /// <param name="x">The X coordinate.</param> /// <returns>The new point.</returns> public Point WithX(double x) { return new Point(x, _y); } /// <summary> /// Returns a new point with the specified Y coordinate. /// </summary> /// <param name="y">The Y coordinate.</param> /// <returns>The new point.</returns> public Point WithY(double y) { return new Point(_x, y); } /// <summary> /// Deconstructs the point into its X and Y coordinates. /// </summary> /// <param name="x">The X coordinate.</param> /// <param name="y">The Y coordinate.</param> public void Deconstruct(out double x, out double y) { x = this._x; y = this._y; } /// <summary> /// Gets a value indicating whether the X and Y coordinates are zero. /// </summary> public bool IsDefault { get { return (_x == 0) && (_y == 0); } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Forms.Design; using Microsoft.PythonTools.Commands; using Microsoft.PythonTools.Common; using Microsoft.PythonTools.Common.Infrastructure; using Microsoft.PythonTools.Debugger; using Microsoft.PythonTools.Debugger.DebugEngine; using Microsoft.PythonTools.Debugger.Remote; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Infrastructure.Commands; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.InterpreterList; using Microsoft.PythonTools.Logging; using Microsoft.PythonTools.Options; using Microsoft.PythonTools.Project; using Microsoft.PythonTools.Repl; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.InteractiveWindow.Shell; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.Navigation; using Microsoft.VisualStudioTools.Project; using Task = System.Threading.Tasks.Task; namespace Microsoft.PythonTools { /// <summary> /// This is the class that implements the package exposed by this assembly. /// /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. /// </summary> [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is a package. // This attribute is used to register the information needed to show the this package in the Help/About dialog of Visual Studio. [InstalledProductRegistration("#110", "#112", AssemblyVersionInfo.Version, IconResourceID = 400)] // This attribute is needed to let the shell know that this package exposes some menus. [ProvideMenuResource("Menus.ctmenu", 1)] [ProvideKeyBindingTable(PythonConstants.TextMateEditorGuid, 3004, AllowNavKeyBinding = true)] [Description("Python Tools Package")] [ProvideAutomationObject("VsPython")] [ProvideLanguageEditorOptionPage(typeof(PythonAdvancedEditorOptionsPage), PythonConstants.LanguageName, "", "Advanced", "#113")] [ProvideLanguageEditorOptionPage(typeof(PythonFormattingOptionsPage), PythonConstants.LanguageName, "", "Formatting", "#126")] [ProvideOptionPage(typeof(PythonInteractiveOptionsPage), "Python Tools", "Interactive Windows", 115, 117, true)] [ProvideOptionPage(typeof(PythonGeneralOptionsPage), "Python Tools", "General", 115, 120, true)] [ProvideOptionPage(typeof(PythonAnalysisOptionsPage), "Python Tools", "Analysis", 115, 129, true)] [ProvideOptionPage(typeof(PythonDebuggingOptionsPage), "Python Tools", "Debugging", 115, 125, true)] [ProvideOptionPage(typeof(PythonCondaOptionsPage), "Python Tools", "Conda", 115, 132, true)] [Guid(CommonGuidList.guidPythonToolsPkgString)] // our packages GUID [ProvideLanguageService(typeof(PythonLanguageInfo), PythonConstants.LanguageName, 106, RequestStockColors = true, ShowSmartIndent = true, ShowCompletion = true, DefaultToInsertSpaces = true, HideAdvancedMembersByDefault = true, EnableAdvancedMembersOption = true, ShowDropDownOptions = true)] [ProvideLanguageExtension(typeof(PythonLanguageInfo), PythonConstants.FileExtension)] [ProvideLanguageExtension(typeof(PythonLanguageInfo), PythonConstants.WindowsFileExtension)] [ProvideLanguageExtension(typeof(PythonLanguageInfo), PythonConstants.StubFileExtension)] [ProvideDebugEngine(AD7Engine.DebugEngineName, typeof(AD7ProgramProvider), typeof(AD7Engine), AD7Engine.DebugEngineId, hitCountBp: true)] [ProvideDebugAdapter("VSCode Python Debugger", DebugAdapterLauncher.VSCodeDebugEngineId, DebugAdapterLauncher.DebugAdapterLauncherCLSID, CustomDebugAdapterProtocolExtension.CustomProtocolExtensionCLSID, "Python", "{DA3C7D59-F9E4-4697-BEE7-3A0703AF6BFF}", typeof(DebugAdapterLauncher), typeof(CustomDebugAdapterProtocolExtension))] [ProvideDebugLanguage("Python", "{DA3C7D59-F9E4-4697-BEE7-3A0703AF6BFF}", PythonExpressionEvaluatorGuid, AD7Engine.DebugEngineId)] [ProvideDebugPortSupplier("Python remote (ptvsd)", typeof(PythonRemoteDebugPortSupplier), PythonRemoteDebugPortSupplier.PortSupplierId, typeof(PythonRemoteDebugPortPicker))] [ProvideDebugPortPicker(typeof(PythonRemoteDebugPortPicker))] #region Exception List [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ArithmeticError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "AssertionError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "AttributeError", BreakByDefault = false)] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "BaseException")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "BufferError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "BytesWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "DeprecationWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "EOFError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "EnvironmentError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "Exception")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "FloatingPointError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "FutureWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "GeneratorExit", BreakByDefault = false)] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "IOError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ImportError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ImportWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "IndentationError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "IndexError", BreakByDefault = false)] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "KeyError", BreakByDefault = false)] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "KeyboardInterrupt")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "LookupError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "MemoryError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "NameError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "NotImplementedError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "BlockingIOError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ChildProcessError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "BrokenPipeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "ConnectionAbortedError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "ConnectionRefusedError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "ConnectionResetError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "FileExistsError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "FileNotFoundError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "InterruptedError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "IsADirectoryError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "NotADirectoryError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "PermissionError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ProcessLookupError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "TimeoutError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OverflowError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "PendingDeprecationWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ReferenceError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "RuntimeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "RuntimeWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "StandardError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "StopIteration", BreakByDefault = false)] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SyntaxError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SyntaxWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SystemError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SystemExit")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "TabError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "TypeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnboundLocalError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeDecodeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeEncodeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeTranslateError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UserWarning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ValueError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "Warning")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "WindowsError")] [ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ZeroDivisionError")] #endregion [ProvideComponentPickerPropertyPage(typeof(PythonToolsPackage), typeof(WebPiComponentPickerControl), "WebPi", DefaultPageNameValue = "#4000")] [ProvideToolWindow(typeof(InterpreterListToolWindow), Style = VsDockStyle.Linked, Window = ToolWindowGuids80.SolutionExplorer)] // TODO: Pylance //[ProvideDiffSupportedContentType(PythonConstants.SourceFileExtensions, "")] //[ProvidePeekSupportedContentType(PythonConstants.SourceFileExtensions, "")] [ProvideCodeExpansions(CommonGuidList.guidPythonLanguageService, false, 106, "Python", @"Snippets\%LCID%\SnippetsIndex.xml", @"Snippets\%LCID%\Python\")] [ProvideCodeExpansionPath("Python", "Test", @"Snippets\%LCID%\Test\")] [ProvideInteractiveWindow(CommonGuidList.guidPythonInteractiveWindow, Style = VsDockStyle.Linked, Orientation = ToolWindowOrientation.none, Window = ToolWindowGuids80.Outputwindow)] [ProvideBraceCompletion(PythonCoreConstants.ContentType)] [ProvideNewFileTemplates(CommonGuidList.guidMiscFilesProjectGuidString, CommonGuidList.guidPythonToolsPkgString, "Python", @"Templates\NewItem\")] internal sealed class PythonToolsPackage : CommonPackage, IVsComponentSelectorProvider, IPythonToolsToolWindowService { private PythonAutomation _autoObject; private PackageContainer _packageContainer; private readonly DisposableBag _disposables; internal const string PythonExpressionEvaluatorGuid = "{D67D5DB8-3D44-4105-B4B8-47AB1BA66180}"; /// <summary> /// Default constructor of the package. /// Inside this method you can place any initialization code that does not require /// any Visual Studio service because at this point the package object is created but /// not sited yet inside Visual Studio environment. The place to do all the other /// initialization is the Initialize method. /// </summary> public PythonToolsPackage() { _disposables = new DisposableBag(GetType().Name, "Package is disposed"); Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString())); #if DEBUG TaskScheduler.UnobservedTaskException += (sender, e) => { if (!e.Observed) { var str = e.Exception.ToString(); if (str.Contains("Python")) { CommonUtils.ActivityLogError("UnobservedTaskException", $"An exception in a task was not observed: {e.Exception}"); Debug.Fail("An exception in a task was not observed. See ActivityLog.xml for more details.", e.Exception.ToString()); } e.SetObserved(); } }; #endif } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _disposables.TryDispose(); } } public override Microsoft.VisualStudio.Shell.Interop.IVsAsyncToolWindowFactory GetAsyncToolWindowFactory(Guid toolWindowType) => toolWindowType == typeof(InterpreterListToolWindow).GUID ? this : base.GetAsyncToolWindowFactory(toolWindowType); protected override Task<object> InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) => toolWindowType == typeof(InterpreterListToolWindow) ? Task.FromResult<object>(this) : base.InitializeToolWindowAsync(toolWindowType, id, cancellationToken); protected override int CreateToolWindow(ref Guid toolWindowType, int id) { // We can't move initialization of PythonInteractiveWindow into AsyncToolWindowFactory // because Package.ShowToolWindow doesn't call IVsAsyncToolWindowFactory.CreateToolWindow // which makes it impossible to fully override tool window creation if (toolWindowType == CommonGuidList.guidPythonInteractiveWindowGuid) { var pyService = this.GetPythonToolsService(); var category = SelectableReplEvaluator.GetSettingsCategory(id.ToString()); string replId; try { replId = pyService.LoadString("Id", category); } catch (Exception ex) when (!ex.IsCriticalException()) { Debug.Fail("Could not load settings for interactive window.", ex.ToString()); replId = null; } if (string.IsNullOrEmpty(replId)) { pyService.DeleteCategory(category); return VSConstants.S_OK; } pyService.ComponentModel.GetService<InteractiveWindowProvider>().Create(replId, id); return VSConstants.S_OK; } return base.CreateToolWindow(ref toolWindowType, id); } protected override int QueryClose(out bool canClose) { var res = base.QueryClose(out canClose); if (canClose) { var pyService = this.GetPythonToolsService(); pyService.EnvironmentSwitcherManager.IsClosing = true; } return res; } internal static void NavigateTo(IServiceProvider serviceProvider, string filename, Guid docViewGuidType, int line, int col) { if (File.Exists(filename)) { VsUtilities.NavigateTo(serviceProvider, filename, docViewGuidType, line, col); } } internal static void NavigateTo(System.IServiceProvider serviceProvider, string filename, Guid docViewGuidType, int pos) { VsUtilities.OpenDocument(serviceProvider, filename, out var viewAdapter, out var pWindowFrame); ErrorHandler.ThrowOnFailure(pWindowFrame.Show()); // Set the cursor at the beginning of the declaration. ErrorHandler.ThrowOnFailure(viewAdapter.GetLineAndColumn(pos, out var line, out var col)); ErrorHandler.ThrowOnFailure(viewAdapter.SetCaretPos(line, col)); // Make sure that the text is visible. viewAdapter.CenterLines(line, 1); } internal static ITextBuffer GetBufferForDocument(IServiceProvider serviceProvider, string filename) { VsUtilities.OpenDocument(serviceProvider, filename, out var viewAdapter, out _); ErrorHandler.ThrowOnFailure(viewAdapter.GetBuffer(out var lines)); var adapter = serviceProvider.GetComponentModel().GetService<IVsEditorAdaptersFactoryService>(); return adapter.GetDocumentBuffer(lines); } internal static IProjectLauncher GetLauncher(IServiceProvider serviceProvider, IPythonProject project) { var launchProvider = serviceProvider.GetUIThread().Invoke(() => project.GetProperty(PythonConstants.LaunchProvider)); IPythonLauncherProvider defaultLaunchProvider = null; foreach (var launcher in serviceProvider.GetComponentModel().GetExtensions<IPythonLauncherProvider>()) { if (launcher.Name == launchProvider) { return serviceProvider.GetUIThread().Invoke(() => launcher.CreateLauncher(project)); } if (launcher.Name == DefaultLauncherProvider.DefaultLauncherName) { defaultLaunchProvider = launcher; } } // no launcher configured, use the default one. Debug.Assert(defaultLaunchProvider != null); return serviceProvider.GetUIThread().Invoke(() => defaultLaunchProvider?.CreateLauncher(project)); } internal static bool LaunchFile(IServiceProvider provider, string filename, bool debug, bool saveDirtyFiles) { bool isLaunchFileOpen = true; var project = (IPythonProject)provider.GetProjectFromOpenFile(filename); if (project == null) { project = provider.GetProjectContainingFile(filename); if (project == null) { project = new DefaultPythonProject(provider, filename); } else { isLaunchFileOpen = false; } } try { var starter = GetLauncher(provider, project); if (starter == null) { Debug.Fail("Failed to get project launcher"); return false; } if (saveDirtyFiles) { if (!SaveDirtyFiles(provider, isLaunchFileOpen, ref filename)) { return false; } } starter.LaunchFile(filename, debug); } catch (MissingInterpreterException ex) { var interpreterRegistry = provider.GetComponentModel().GetService<IInterpreterRegistryService>(); if (project.GetInterpreterFactory() == interpreterRegistry.NoInterpretersValue) { OpenNoInterpretersHelpPage(provider, ex.HelpPage); } else { var td = new TaskDialog(provider) { Title = Strings.ProductTitle, MainInstruction = Strings.FailedToLaunchDebugger, Content = ex.Message }; td.Buttons.Add(TaskDialogButton.Close); td.ShowModal(); } return false; } catch (NoInterpretersException ex) { OpenNoInterpretersHelpPage(provider, ex.HelpPage); return false; } catch (NoStartupFileException ex) { MessageBox.Show(ex.Message, Strings.ProductTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } catch (IOException ex) { MessageBox.Show(ex.Message, Strings.ProductTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } private static bool SaveDirtyFiles(IServiceProvider provider, bool isLaunchFileOpen, ref string fileName) { if (provider.GetService(typeof(SVsRunningDocumentTable)) is IVsRunningDocumentTable rdt && provider.GetService(typeof(SVsRunningDocumentTable)) is IVsRunningDocumentTable4 rdt4) { // The save operation may move the file, so adjust filename // to the new location if necessary. var launchFileCookie = isLaunchFileOpen ? rdt4.GetDocumentCookie(fileName) : VSConstants.VSCOOKIE_NIL; // Consider using (uint)(__VSRDTSAVEOPTIONS.RDTSAVEOPT_SaveIfDirty | __VSRDTSAVEOPTIONS.RDTSAVEOPT_PromptSave) // when VS settings include prompt for save on build var saveOpt = (uint)__VSRDTSAVEOPTIONS.RDTSAVEOPT_SaveIfDirty; var hr = rdt.SaveDocuments(saveOpt, null, VSConstants.VSITEMID_NIL, VSConstants.VSCOOKIE_NIL); if (hr == VSConstants.E_ABORT) { return false; } if (launchFileCookie != VSConstants.VSCOOKIE_NIL) { var launchFileMoniker = rdt4.GetDocumentMoniker(launchFileCookie); if (!string.IsNullOrEmpty(launchFileMoniker)) { fileName = launchFileMoniker; } } } return true; } async Task<ToolWindowPane> IPythonToolsToolWindowService.GetWindowPaneAsync(Type windowType, bool create) { await JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken); return await FindWindowPaneAsync(windowType, 0, create, DisposalToken) as ToolWindowPane; } async Task IPythonToolsToolWindowService.ShowWindowPaneAsync(Type windowType, bool focus) { await JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken); var toolWindow = await ShowToolWindowAsync(windowType, 0, true, DisposalToken); if (focus && toolWindow.Content is System.Windows.UIElement content) { content.Focus(); } } internal static void OpenNoInterpretersHelpPage(IServiceProvider serviceProvider, string page = null) => OpenVsWebBrowser(serviceProvider, page ?? PythonToolsInstallPath.GetFile("NoInterpreters.html")); public static string InterpreterHelpUrl => $"https://go.microsoft.com/fwlink/?LinkId=299429&clcid=0x{CultureInfo.CurrentCulture.LCID:X}"; protected override object GetAutomationObject(string name) => name == "VsPython" ? _autoObject ?? (_autoObject = new PythonAutomation(this)) : base.GetAutomationObject(name); public override bool IsRecognizedFile(string filename) => ModulePath.IsPythonSourceFile(filename); public override Type GetLibraryManagerType() => null; internal override LibraryManager CreateLibraryManager() => null; ///////////////////////////////////////////////////////////////////////////// // Overriden Package Implementation protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { Trace.WriteLine("Entering InitializeAsync() of: {0}".FormatUI(this)); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); await base.InitializeAsync(cancellationToken, progress); var shell = GetService(typeof(SVsShell)) as IVsShell; AddService<IClipboardService>(new ClipboardService(), true); AddService<IPythonToolsToolWindowService>(this, true); AddService<PythonLanguageInfo>((container, serviceType) => new PythonLanguageInfo(this), promote: true); AddService<CustomDebuggerEventHandler>((container, serviceType) => new CustomDebuggerEventHandler(this), promote: true); AddService<IPythonToolsOptionsService>(PythonToolsOptionsService.CreateService, promote: true); AddService<IPythonToolsLogger>(PythonToolsLogger.CreateService, promote: true); AddService<PythonToolsService>(PythonToolsService.CreateService, promote: true); AddService<IPythonDebugOptionsService>((container, serviceType) => new PythonDebugOptionsService(this), promote: true); var solutionEventListener = new SolutionEventsListener(this); solutionEventListener.StartListeningForChanges(); AddService<SolutionEventsListener>(solutionEventListener, true); // Enable the mixed-mode debugger UI context UIContext.FromUIContextGuid(DkmEngineId.NativeEng).IsActive = true; // Add our command handlers for menu (commands must exist in the .vsct file) RegisterCommands(CommonGuidList.guidPythonToolsCmdSet, new OpenReplCommand(this, (int)PkgCmdIDList.cmdidReplWindow), new OpenReplCommand(this, PythonConstants.OpenInteractiveForEnvironment), new OpenDebugReplCommand(this), new ExecuteInReplCommand(this), new SendToReplCommand(this), new FillParagraphCommand(this), new DiagnosticsCommand(this), new OpenInterpreterListCommand(this), new ImportWizardCommand(this), new ImportCoverageCommand(this), new ShowPythonViewCommand(this), new ShowCppViewCommand(this), new ShowNativePythonFrames(this), new UsePythonStepping(this), new ViewAllEnvironmentsCommand(this), new OpenWebUrlCommand(this, "https://go.microsoft.com/fwlink/?linkid=832525", PkgCmdIDList.cmdidWebPythonAtMicrosoft), new OpenWebUrlCommand(this, Strings.IssueTrackerUrl, PkgCmdIDList.cmdidWebPTVSSupport), new OpenWebUrlCommand(this, "https://go.microsoft.com/fwlink/?linkid=832517", PkgCmdIDList.cmdidWebDGProducts)); RegisterCommands( CommandAsyncToOleMenuCommandShimFactory.CreateCommand(CommonGuidList.guidPythonToolsCmdSet, (int)PkgCmdIDList.cmdidAddEnvironment, new AddEnvironmentCommand(this)), CommandAsyncToOleMenuCommandShimFactory.CreateCommand(CommonGuidList.guidPythonToolsCmdSet, (int)PkgCmdIDList.cmdidAddVirtualEnv, new AddEnvironmentCommand(this, Environments.AddEnvironmentDialog.PageKind.VirtualEnvironment)), CommandAsyncToOleMenuCommandShimFactory.CreateCommand(CommonGuidList.guidPythonToolsCmdSet, (int)PkgCmdIDList.cmdidAddExistingEnv, new AddEnvironmentCommand(this, Environments.AddEnvironmentDialog.PageKind.ExistingEnvironment)), CommandAsyncToOleMenuCommandShimFactory.CreateCommand(CommonGuidList.guidPythonToolsCmdSet, (int)PkgCmdIDList.cmdidAddCondaEnv, new AddEnvironmentCommand(this, Environments.AddEnvironmentDialog.PageKind.CondaEnvironment)), CommandAsyncToOleMenuCommandShimFactory.CreateCommand(CommonGuidList.guidPythonToolsCmdSet, PythonConstants.InstallPythonPackage, new ManagePackagesCommand(this)), new CurrentEnvironmentCommand(this), new CurrentEnvironmentListCommand(this) ); // Enable the Python debugger UI context UIContext.FromUIContextGuid(AD7Engine.DebugEngineGuid).IsActive = true; // The variable is inherited by child processes backing Test Explorer, and is used in PTVS // test discoverer and test executor to connect back to VS. Environment.SetEnvironmentVariable("_PTVS_PID", Process.GetCurrentProcess().Id.ToString()); Trace.WriteLine("Leaving Initialize() of: {0}".FormatUI(this)); } public EnvDTE.DTE DT => (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE)); #region IVsComponentSelectorProvider Members public int GetComponentSelectorPage(ref Guid rguidPage, VSPROPSHEETPAGE[] ppage) { if (rguidPage == typeof(WebPiComponentPickerControl).GUID) { var page = new VSPROPSHEETPAGE(); page.dwSize = (uint)Marshal.SizeOf(typeof(VSPROPSHEETPAGE)); var pickerPage = new WebPiComponentPickerControl(); if (_packageContainer == null) { _packageContainer = new PackageContainer(this); } _packageContainer.Add(pickerPage); //IWin32Window window = pickerPage; page.hwndDlg = pickerPage.Handle; ppage[0] = page; return VSConstants.S_OK; } return VSConstants.E_FAIL; } /// <devdoc> /// This class derives from container to provide a service provider /// connection to the package. /// </devdoc> private sealed class PackageContainer : Container { private readonly IServiceProvider _provider; private IUIService _uis; private AmbientProperties _ambientProperties; /// <devdoc> /// Creates a new container using the given service provider. /// </devdoc> internal PackageContainer(System.IServiceProvider provider) { _provider = provider; } /// <devdoc> /// Override to GetService so we can route requests /// to the package's service provider. /// </devdoc> protected override object GetService(Type serviceType) { if (serviceType == null) { throw new ArgumentNullException("serviceType"); } if (_provider != null) { if (serviceType.IsEquivalentTo(typeof(AmbientProperties))) { if (_uis == null) { _uis = (IUIService)_provider.GetService(typeof(IUIService)); } if (_ambientProperties == null) { _ambientProperties = new AmbientProperties(); } if (_uis != null) { // update the _ambientProperties in case the styles have changed // since last time. _ambientProperties.Font = (Font)_uis.Styles["DialogFont"]; } return _ambientProperties; } object service = _provider.GetService(serviceType); if (service != null) { return service; } } return base.GetService(serviceType); } } #endregion } }
using System; using Xunit; public class ForthTests { [Fact] public void Parsing_and_numbers_numbers_just_get_pushed_onto_the_stack() { Assert.Equal("1 2 3 4 5", Forth.Evaluate(new[] { "1 2 3 4 5" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Addition_can_add_two_numbers() { Assert.Equal("3", Forth.Evaluate(new[] { "1 2 +" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Addition_errors_if_there_is_nothing_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "+" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Addition_errors_if_there_is_only_one_value_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "1 +" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Subtraction_can_subtract_two_numbers() { Assert.Equal("-1", Forth.Evaluate(new[] { "3 4 -" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Subtraction_errors_if_there_is_nothing_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "-" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Subtraction_errors_if_there_is_only_one_value_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "1 -" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Multiplication_can_multiply_two_numbers() { Assert.Equal("8", Forth.Evaluate(new[] { "2 4 *" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Multiplication_errors_if_there_is_nothing_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "*" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Multiplication_errors_if_there_is_only_one_value_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "1 *" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Division_can_divide_two_numbers() { Assert.Equal("4", Forth.Evaluate(new[] { "12 3 /" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Division_performs_integer_division() { Assert.Equal("2", Forth.Evaluate(new[] { "8 3 /" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Division_errors_if_dividing_by_zero() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "4 0 /" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Division_errors_if_there_is_nothing_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "/" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Division_errors_if_there_is_only_one_value_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "1 /" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Combined_arithmetic_addition_and_subtraction() { Assert.Equal("-1", Forth.Evaluate(new[] { "1 2 + 4 -" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Combined_arithmetic_multiplication_and_division() { Assert.Equal("2", Forth.Evaluate(new[] { "2 4 * 3 /" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Dup_copies_a_value_on_the_stack() { Assert.Equal("1 1", Forth.Evaluate(new[] { "1 dup" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Dup_copies_the_top_value_on_the_stack() { Assert.Equal("1 2 2", Forth.Evaluate(new[] { "1 2 dup" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Dup_errors_if_there_is_nothing_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "dup" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Drop_removes_the_top_value_on_the_stack_if_it_is_the_only_one() { Assert.Equal("", Forth.Evaluate(new[] { "1 drop" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Drop_removes_the_top_value_on_the_stack_if_it_is_not_the_only_one() { Assert.Equal("1", Forth.Evaluate(new[] { "1 2 drop" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Drop_errors_if_there_is_nothing_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "drop" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Swap_swaps_the_top_two_values_on_the_stack_if_they_are_the_only_ones() { Assert.Equal("2 1", Forth.Evaluate(new[] { "1 2 swap" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Swap_swaps_the_top_two_values_on_the_stack_if_they_are_not_the_only_ones() { Assert.Equal("1 3 2", Forth.Evaluate(new[] { "1 2 3 swap" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Swap_errors_if_there_is_nothing_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "swap" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Swap_errors_if_there_is_only_one_value_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "1 swap" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Over_copies_the_second_element_if_there_are_only_two() { Assert.Equal("1 2 1", Forth.Evaluate(new[] { "1 2 over" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Over_copies_the_second_element_if_there_are_more_than_two() { Assert.Equal("1 2 3 2", Forth.Evaluate(new[] { "1 2 3 over" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Over_errors_if_there_is_nothing_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "over" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Over_errors_if_there_is_only_one_value_on_the_stack() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "1 over" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void User_defined_words_can_consist_of_built_in_words() { Assert.Equal("1 1 1", Forth.Evaluate(new[] { ": dup-twice dup dup ;", "1 dup-twice" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void User_defined_words_execute_in_the_right_order() { Assert.Equal("1 2 3", Forth.Evaluate(new[] { ": countup 1 2 3 ;", "countup" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void User_defined_words_can_override_other_user_defined_words() { Assert.Equal("1 1 1", Forth.Evaluate(new[] { ": foo dup ;", ": foo dup dup ;", "1 foo" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void User_defined_words_can_override_built_in_words() { Assert.Equal("1 1", Forth.Evaluate(new[] { ": swap dup ;", "1 swap" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void User_defined_words_can_override_built_in_operators() { Assert.Equal("12", Forth.Evaluate(new[] { ": + * ;", "3 4 +" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void User_defined_words_can_use_different_words_with_the_same_name() { Assert.Equal("5 6", Forth.Evaluate(new[] { ": foo 5 ;", ": bar foo ;", ": foo 6 ;", "bar foo" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void User_defined_words_can_define_word_that_uses_word_with_the_same_name() { Assert.Equal("11", Forth.Evaluate(new[] { ": foo 10 ;", ": foo foo 1 + ;", "foo" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void User_defined_words_cannot_redefine_non_negative_numbers() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { ": 1 2 ;" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void User_defined_words_errors_if_executing_a_non_existent_word() { Assert.Throws<InvalidOperationException>(() => Forth.Evaluate(new[] { "foo" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Case_insensitivity_dup_is_case_insensitive() { Assert.Equal("1 1 1 1", Forth.Evaluate(new[] { "1 DUP Dup dup" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Case_insensitivity_drop_is_case_insensitive() { Assert.Equal("1", Forth.Evaluate(new[] { "1 2 3 4 DROP Drop drop" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Case_insensitivity_swap_is_case_insensitive() { Assert.Equal("2 3 4 1", Forth.Evaluate(new[] { "1 2 SWAP 3 Swap 4 swap" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Case_insensitivity_over_is_case_insensitive() { Assert.Equal("1 2 1 2 1", Forth.Evaluate(new[] { "1 2 OVER Over over" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Case_insensitivity_user_defined_words_are_case_insensitive() { Assert.Equal("1 1 1 1", Forth.Evaluate(new[] { ": foo dup ;", "1 FOO Foo foo" })); } [Fact(Skip = "Remove this Skip property to run this test")] public void Case_insensitivity_definitions_are_case_insensitive() { Assert.Equal("1 1 1 1", Forth.Evaluate(new[] { ": SWAP DUP Dup dup ;", "1 swap" })); } }
#region MIT license // // MIT license // // Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne // // 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.Data.Common; using System.Linq; using System.Collections.Generic; using System.Text; using System.Data.Linq.Mapping; using System.Reflection; using System.Data; #if MONO_STRICT using System.Data.Linq; #else using DbLinq.Data.Linq; #endif using DbLinq.Data.Linq.SqlClient; using DbLinq.Util; using DbLinq.Vendor; namespace DbLinq.Firebird { [Vendor(typeof(FirebirdProvider))] #if !MONO_STRICT public #endif class FirebirdVendor : Vendor.Implementation.Vendor { public override string VendorName { get { return "FirebirdSql"; } } protected readonly FirebirdSqlProvider sqlProvider = new FirebirdSqlProvider(); public override ISqlProvider SqlProvider { get { return sqlProvider; } } /// <summary> /// call mysql stored proc or stored function, /// optionally return DataSet, and collect return params. /// </summary> public override IExecuteResult ExecuteMethodCall(DataContext context, MethodInfo method , params object[] inputValues) { if (method == null) throw new ArgumentNullException("L56 Null 'method' parameter"); //check to make sure there is exactly one [FunctionEx]? that's below. //FunctionAttribute functionAttrib = GetFunctionAttribute(method); var functionAttrib = context.Mapping.GetFunction(method); ParameterInfo[] paramInfos = method.GetParameters(); //int numRequiredParams = paramInfos.Count(p => p.IsIn || p.IsRetval); //if (numRequiredParams != inputValues.Length) // throw new ArgumentException("L161 Argument count mismatch"); string sp_name = functionAttrib.MappedName; // picrap: is there any way to abstract some part of this? using (IDbCommand command = context.Connection.CreateCommand()) { command.CommandText = sp_name; //FbSqlCommand command = new FbSqlCommand("select * from hello0()"); int currInputIndex = 0; List<string> paramNames = new List<string>(); for (int i = 0; i < paramInfos.Length; i++) { ParameterInfo paramInfo = paramInfos[i]; //TODO: check to make sure there is exactly one [Parameter]? ParameterAttribute paramAttrib = paramInfo.GetCustomAttributes(false).OfType<ParameterAttribute>().Single(); string paramName = "@" + paramAttrib.Name; //eg. '@param1' paramNames.Add(paramName); System.Data.ParameterDirection direction = GetDirection(paramInfo, paramAttrib); //FbDbType dbType = FbSqlTypeConversions.ParseType(paramAttrib.DbType); IDbDataParameter cmdParam = command.CreateParameter(); cmdParam.ParameterName = paramName; //cmdParam.Direction = System.Data.ParameterDirection.Input; if (direction == System.Data.ParameterDirection.Input || direction == System.Data.ParameterDirection.InputOutput) { object inputValue = inputValues[currInputIndex++]; cmdParam.Value = inputValue; } else { cmdParam.Value = null; } cmdParam.Direction = direction; command.Parameters.Add(cmdParam); } if (!functionAttrib.IsComposable) // IsCompsable is false when we have a procedure { //procedures: under the hood, this seems to prepend 'CALL ' command.CommandType = System.Data.CommandType.StoredProcedure; } else { //functions: 'SELECT * FROM myFunction()' or 'SELECT * FROM hello(?s)' command.CommandText = "SELECT * FROM " + command.CommandText + "(" + string.Join(",", paramNames.ToArray()) + ")"; } if (method.ReturnType == typeof(DataSet)) { //unknown shape of resultset: System.Data.DataSet dataSet = new DataSet(); //IDataAdapter adapter = new FbDataAdapter((FbCommand)command); IDbDataAdapter adapter = CreateDataAdapter(context); adapter.SelectCommand = command; adapter.Fill(dataSet); List<object> outParamValues = CopyOutParams(paramInfos, command.Parameters); return new ProcedureResult(dataSet, outParamValues.ToArray()); } else { object obj = command.ExecuteScalar(); List<object> outParamValues = CopyOutParams(paramInfos, command.Parameters); return new ProcedureResult(obj, outParamValues.ToArray()); } } } static System.Data.ParameterDirection GetDirection(ParameterInfo paramInfo, ParameterAttribute paramAttrib) { //strange hack to determine what's a ref, out parameter: //http://lists.ximian.com/pipermain/mono-list/2003-March/012751.html bool hasAmpersand = paramInfo.ParameterType.FullName.Contains('&'); if (paramInfo.IsOut) return System.Data.ParameterDirection.Output; if (hasAmpersand) return System.Data.ParameterDirection.InputOutput; return System.Data.ParameterDirection.Input; } /// <summary> /// Collect all Out or InOut param values, casting them to the correct .net type. /// </summary> private List<object> CopyOutParams(ParameterInfo[] paramInfos, IDataParameterCollection paramSet) { List<object> outParamValues = new List<object>(); //Type type_t = typeof(T); int i = -1; foreach (IDbDataParameter param in paramSet) { i++; if (param.Direction == System.Data.ParameterDirection.Input) { outParamValues.Add("unused"); continue; } object val = param.Value; Type desired_type = paramInfos[i].ParameterType; if (desired_type.Name.EndsWith("&")) { //for ref and out parameters, we need to tweak ref types, e.g. // "System.Int32&, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" string fullName1 = desired_type.AssemblyQualifiedName; string fullName2 = fullName1.Replace("&", ""); desired_type = Type.GetType(fullName2); } try { //fi.SetValue(t, val); //fails with 'System.Decimal cannot be converted to Int32' //DbLinq.util.FieldUtils.SetObjectIdField(t, fi, val); //object val2 = FieldUtils.CastValue(val, desired_type); object val2 = TypeConvert.To(val, desired_type); outParamValues.Add(val2); } catch (Exception) { //fails with 'System.Decimal cannot be converted to Int32' //Logger.Write(Level.Error, "CopyOutParams ERROR L245: failed on CastValue(): " + ex.Message); } } return outParamValues; } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Xaml.Xaml File: OrderWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Xaml { using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using Ecng.Common; using Ecng.ComponentModel; using Ecng.Xaml; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// The window for the order creating. /// </summary> public partial class OrderWindow { private enum OrderWindowTif { [EnumDisplayNameLoc(LocalizedStrings.GTCKey)] Gtc, [EnumDisplayNameLoc(LocalizedStrings.FOKKey)] MatchOrCancel, [EnumDisplayNameLoc(LocalizedStrings.IOCKey)] CancelBalance, [EnumDisplayNameLoc(LocalizedStrings.SessionKey)] Today, [EnumDisplayNameLoc(LocalizedStrings.GTDKey)] Gtd, } private class SecurityData : NotifiableObject { private decimal? _maxPrice; private decimal? _minPrice; private decimal? _lastTradePrice; private decimal? _bestAskPrice; private decimal? _bestBidPrice; public decimal? BestBidPrice { get { return _bestBidPrice; } set { _bestBidPrice = value; NotifyChanged(nameof(BestBidPrice)); } } public decimal? BestAskPrice { get { return _bestAskPrice; } set { _bestAskPrice = value; NotifyChanged(nameof(BestAskPrice)); } } public decimal? LastTradePrice { get { return _lastTradePrice; } set { _lastTradePrice = value; NotifyChanged(nameof(LastTradePrice)); } } public decimal? MinPrice { get { return _minPrice; } set { _minPrice = value; NotifyChanged(nameof(MinPrice)); } } public decimal? MaxPrice { get { return _maxPrice; } set { _maxPrice = value; NotifyChanged(nameof(MaxPrice)); } } } /// <summary> /// Initializes a new instance of the <see cref="OrderWindow"/>. /// </summary> public OrderWindow() { InitializeComponent(); TimeInForceCtrl.SetDataSource<OrderWindowTif>(); Order = new Order { Type = OrderTypes.Limit }; DataContext = Data = new SecurityData(); } private SecurityData Data { get; } /// <summary> /// Available portfolios. /// </summary> public ThreadSafeObservableCollection<Portfolio> Portfolios { get { return PortfolioCtrl.Portfolios; } set { PortfolioCtrl.Portfolios = value; } } private IMarketDataProvider _marketDataProvider; /// <summary> /// The market data provider. /// </summary> public IMarketDataProvider MarketDataProvider { get { return _marketDataProvider; } set { if (value == _marketDataProvider) return; if (_marketDataProvider != null) _marketDataProvider.ValuesChanged -= MarketDataProviderOnValuesChanged; _marketDataProvider = value; if (_marketDataProvider == null) return; if (Security != null) FillDataDefaults(); _marketDataProvider.ValuesChanged += MarketDataProviderOnValuesChanged; } } /// <summary> /// The provider of information about instruments. /// </summary> public ISecurityProvider SecurityProvider { get { return SecurityCtrl.SecurityProvider; } set { SecurityCtrl.SecurityProvider = value; } } private Order _order; /// <summary> /// Order. /// </summary> public Order Order { get { _order.Type = IsMarketCtrl.IsChecked == true ? OrderTypes.Market : OrderTypes.Limit; _order.Security = Security; _order.Portfolio = Portfolio; _order.ClientCode = ClientCodeCtrl.Text; _order.Price = PriceCtrl.Value ?? 0; _order.Volume = VolumeCtrl.Value ?? 0; _order.VisibleVolume = VisibleVolumeCtrl.Value; _order.Direction = IsBuyCtrl.IsChecked == true ? Sides.Buy : Sides.Sell; _order.Comment = CommentCtrl.Text; switch ((OrderWindowTif?)TimeInForceCtrl.SelectedValue) { case OrderWindowTif.MatchOrCancel: _order.TimeInForce = TimeInForce.MatchOrCancel; break; case OrderWindowTif.CancelBalance: _order.TimeInForce = TimeInForce.CancelBalance; break; case OrderWindowTif.Gtc: _order.TimeInForce = TimeInForce.PutInQueue; break; case OrderWindowTif.Today: _order.TimeInForce = TimeInForce.PutInQueue; _order.ExpiryDate = DateTime.Today.ApplyTimeZone(Security.Board.TimeZone); break; case OrderWindowTif.Gtd: _order.TimeInForce = TimeInForce.PutInQueue; _order.ExpiryDate = (ExpiryDate.Value ?? DateTime.Today).ApplyTimeZone(Security.Board.TimeZone); break; case null: break; default: throw new ArgumentOutOfRangeException(); } return _order; } set { if (value == null) throw new ArgumentNullException(nameof(value)); _order = value; switch (value.Type) { case OrderTypes.Limit: case null: IsMarketCtrl.IsChecked = false; break; case OrderTypes.Market: IsMarketCtrl.IsChecked = true; break; case OrderTypes.Conditional: case OrderTypes.Repo: case OrderTypes.ExtRepo: case OrderTypes.Rps: case OrderTypes.Execute: throw new NotSupportedException(LocalizedStrings.Str2872Params.Put(value.Type)); default: throw new ArgumentOutOfRangeException(); } Security = value.Security; Portfolio = value.Portfolio; ClientCodeCtrl.Text = value.ClientCode; PriceCtrl.Value = value.Price == 0 ? PriceCtrl.Increment : value.Price; VolumeCtrl.Value = value.Volume == 0 ? VolumeCtrl.Increment : value.Volume; VisibleVolumeCtrl.Value = value.VisibleVolume; IsBuyCtrl.IsChecked = value.Direction == Sides.Buy; IsSellCtrl.IsChecked = value.Direction == Sides.Sell; CommentCtrl.Text = value.Comment; switch (value.TimeInForce) { case null: case TimeInForce.PutInQueue: { if (value.ExpiryDate == null || value.ExpiryDate == DateTimeOffset.MaxValue) TimeInForceCtrl.SelectedValue = OrderWindowTif.Gtc; else if (value.ExpiryDate == DateTimeOffset.Now.Date.ApplyTimeZone(Security.Board.TimeZone)) TimeInForceCtrl.SelectedValue = OrderWindowTif.Today; else { TimeInForceCtrl.SelectedValue = OrderWindowTif.Gtd; ExpiryDate.Value = value.ExpiryDate.Value.Date; //throw new ArgumentOutOfRangeException("value", value.ExpiryDate, LocalizedStrings.Str1541); } break; } case TimeInForce.MatchOrCancel: TimeInForceCtrl.SelectedValue = OrderWindowTif.MatchOrCancel; break; case TimeInForce.CancelBalance: TimeInForceCtrl.SelectedValue = OrderWindowTif.CancelBalance; break; default: throw new ArgumentOutOfRangeException(); } if (Security != null && !Security.Board.IsSupportMarketOrders) IsMarketCtrl.IsEnabled = false; if (_order.State != OrderStates.None) { IsMarketCtrl.IsEnabled = PortfolioCtrl.IsEnabled = SecurityCtrl.IsEnabled = false; } } } private Security Security { get { return SecurityCtrl.SelectedSecurity; } set { SecurityCtrl.SelectedSecurity = value; } } private Portfolio Portfolio { get { return PortfolioCtrl.SelectedPortfolio; } set { PortfolioCtrl.SelectedPortfolio = value; } } private void PortfolioCtrl_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { TryEnableSend(); } private void SecurityCtrl_OnSecuritySelected() { TryEnableSend(); var isNull = Security == null; PriceCtrl.Increment = isNull ? 0.01m : Security.PriceStep ?? 1m; VolumeCtrl.Increment = isNull ? 1m : Security.VolumeStep ?? 1m; MinPrice.IsEnabled = MaxPrice.IsEnabled = BestBidPrice.IsEnabled = BestAskPrice.IsEnabled = LastTradePrice.IsEnabled = !isNull; Data.BestBidPrice = Data.BestAskPrice = Data.LastTradePrice = Data.MinPrice = Data.MaxPrice = null; if (isNull || MarketDataProvider == null) return; FillDataDefaults(); } private void FillDataDefaults() { Data.BestBidPrice = GetSecurityValue(Level1Fields.BestBidPrice); Data.BestAskPrice = GetSecurityValue(Level1Fields.BestAskPrice); Data.LastTradePrice = GetSecurityValue(Level1Fields.LastTradePrice); Data.MinPrice = GetSecurityValue(Level1Fields.MinPrice); Data.MaxPrice = GetSecurityValue(Level1Fields.MaxPrice); } private decimal? GetSecurityValue(Level1Fields field) { return (decimal?)MarketDataProvider.GetSecurityValue(Security, field); } private void IsMarketCtrl_OnClick(object sender, RoutedEventArgs e) { TryEnableSend(); } private void VolumeCtrl_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { UpdateAmount(); TryEnableSend(); } private void PriceCtrl_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { UpdateAmount(); TryEnableSend(); } private void TryEnableSend() { Send.IsEnabled = Security != null && Portfolio != null && VolumeCtrl.Value > 0 && (IsMarketCtrl.IsChecked == true || PriceCtrl.Value > 0) && (ExpiryDate.IsEnabled != true || ExpiryDate.Value != null); } private void MarketDataProviderOnValuesChanged(Security security, IEnumerable<KeyValuePair<Level1Fields, object>> changes, DateTimeOffset serverTime, DateTimeOffset localTime) { if (Security != security) return; foreach (var change in changes) { switch (change.Key) { case Level1Fields.BestAskPrice: Data.BestAskPrice = (decimal)change.Value; break; case Level1Fields.BestBidPrice: Data.BestBidPrice = (decimal)change.Value; break; case Level1Fields.LastTradePrice: Data.LastTradePrice = (decimal)change.Value; break; case Level1Fields.MinPrice: Data.MinPrice = (decimal)change.Value; break; case Level1Fields.MaxPrice: Data.MaxPrice = (decimal)change.Value; break; } } } private void MaxPrice_OnClick(object sender, RoutedEventArgs e) { if (Data.MaxPrice == null) return; PriceCtrl.Value = Data.MaxPrice; IsMarketCtrl.IsChecked = false; } private void MinPrice_OnClick(object sender, RoutedEventArgs e) { if (Data.MinPrice == null) return; PriceCtrl.Value = Data.MinPrice; IsMarketCtrl.IsChecked = false; } private void LastTradePrice_OnClick(object sender, RoutedEventArgs e) { var trade = Data.LastTradePrice; if (trade == null) return; PriceCtrl.Value = trade; IsMarketCtrl.IsChecked = false; } private void BestBidPrice_OnClick(object sender, RoutedEventArgs e) { var bid = Data.BestBidPrice; if (bid == null) return; PriceCtrl.Value = bid; IsMarketCtrl.IsChecked = false; } private void BestAskPrice_OnClick(object sender, RoutedEventArgs e) { var ask = Data.BestAskPrice; if (ask == null) return; PriceCtrl.Value = ask; IsMarketCtrl.IsChecked = false; } private void Vol1_OnClick(object sender, RoutedEventArgs e) { VolumeCtrl.Value = 1; } private void Vol10_OnClick(object sender, RoutedEventArgs e) { VolumeCtrl.Value = 10; } private void Vol20_OnClick(object sender, RoutedEventArgs e) { VolumeCtrl.Value = 20; } private void Vol50_OnClick(object sender, RoutedEventArgs e) { VolumeCtrl.Value = 50; } private void Vol100_OnClick(object sender, RoutedEventArgs e) { VolumeCtrl.Value = 100; } private void Vol200_OnClick(object sender, RoutedEventArgs e) { VolumeCtrl.Value = 200; } private bool _fromAmount; private void ToVolume_OnClick(object sender, RoutedEventArgs e) { var amount = AmountCtrl.Value; if (amount == null) return; var price = GetPrice(); var volume = VolumeCtrl.Value; _fromAmount = true; try { if (price == 0) { if (volume == 0 || volume == null) return; var step = PriceCtrl.Increment ?? 0.01m; PriceCtrl.Value = MathHelper.Round(amount.Value / volume.Value, step, step.GetCachedDecimals()); } else { var step = VolumeCtrl.Increment ?? 1m; VolumeCtrl.Value = MathHelper.Round(amount.Value / price, step, step.GetCachedDecimals()); } } finally { _fromAmount = false; } } private decimal GetPrice() { return PriceCtrl.Value ?? (Data.LastTradePrice ?? 0); } private void UpdateAmount() { if (_fromAmount) return; AmountCtrl.Value = GetPrice() * VolumeCtrl.Value; } private void AmountCtrl_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { ToVolume.IsEnabled = AmountCtrl.Value != null; } private void TimeInForceCtrl_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { var member = e.AddedItems.Cast<EnumComboBoxHelper.EnumerationMember>().FirstOrDefault(); ExpiryDate.IsEnabled = member != null && (OrderWindowTif?)member.Value == OrderWindowTif.Gtd; TryEnableSend(); } private void ExpiryDate_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { TryEnableSend(); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Utilities; using System; using System.IO; using UnityEditor; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// Tools for simulating and recording input as well as playing back input animation in the Unity editor. /// </summary> public class InputSimulationWindow : EditorWindow { private InputAnimation Animation { get { return PlaybackService?.Animation; } set { if (PlaybackService != null) PlaybackService.Animation = value; } } private string loadedFilePath = ""; private IInputSimulationService simulationService = null; private IInputSimulationService SimulationService { get { if (simulationService == null) { simulationService = CoreServices.GetInputSystemDataProvider<IInputSimulationService>(); } return simulationService; } } private IMixedRealityInputRecordingService recordingService = null; private IMixedRealityInputRecordingService RecordingService { get { if (recordingService == null) { recordingService = CoreServices.GetInputSystemDataProvider<IMixedRealityInputRecordingService>(); } return recordingService; } } private IMixedRealityInputPlaybackService playbackService = null; private IMixedRealityInputPlaybackService PlaybackService { get { if (playbackService == null) { playbackService = CoreServices.GetInputSystemDataProvider<IMixedRealityInputPlaybackService>(); } return playbackService; } } public enum ToolMode { /// <summary> /// Record input animation and store in the asset. /// </summary> Record, /// <summary> /// Play back input animation as simulated input. /// </summary> Playback, } public ToolMode Mode { get; private set; } = ToolMode.Record; /// Icon textures private Texture2D iconPlay = null; private Texture2D iconPause = null; private Texture2D iconRecord = null; private Texture2D iconRecordActive = null; private Texture2D iconStepFwd = null; private Texture2D iconJumpBack = null; private Texture2D iconJumpFwd = null; [MenuItem("Mixed Reality/Toolkit/Utilities/Input Simulation")] private static void ShowWindow() { InputSimulationWindow window = GetWindow<InputSimulationWindow>(); window.titleContent = new GUIContent("Input Simulation"); window.Show(); } private void OnGUI() { LoadIcons(); if (!Application.isPlaying) { EditorGUILayout.HelpBox("Input simulation is only available in play mode", MessageType.Info); return; } DrawSimulationGUI(); EditorGUILayout.Separator(); string[] modeStrings = Enum.GetNames(typeof(ToolMode)); Mode = (ToolMode)GUILayout.SelectionGrid((int)Mode, modeStrings, modeStrings.Length); switch (Mode) { case ToolMode.Record: DrawRecordingGUI(); break; case ToolMode.Playback: DrawPlaybackGUI(); break; } // XXX Reloading the scene is currently not supported, // due to the life cycle of the MRTK "instance" object (see #4530). // Enable the button below once scene reloading is supported! #if false using (new GUIEnabledWrapper(Application.isPlaying)) { bool reloadScene = GUILayout.Button("Reload Scene"); if (reloadScene) { Scene activeScene = SceneManager.GetActiveScene(); if (activeScene.IsValid()) { SceneManager.LoadScene(activeScene.name); return; } } } #endif } private void DrawSimulationGUI() { if (SimulationService == null) { EditorGUILayout.HelpBox("No input simulation service found", MessageType.Info); return; } DrawHeadGUI(); DrawHandsGUI(); } private void DrawHeadGUI() { if (!CameraCache.Main) { return; } using (new GUILayout.VerticalScope(EditorStyles.helpBox)) { GUILayout.Label($"Head:"); Transform headTransform = CameraCache.Main.transform; Vector3 newPosition = EditorGUILayout.Vector3Field("Position", headTransform.position); Vector3 newRotation = DrawRotationGUI("Rotation", headTransform.rotation.eulerAngles); bool resetHand = GUILayout.Button("Reset"); if (newPosition != headTransform.position) { headTransform.position = newPosition; } if (newRotation != headTransform.rotation.eulerAngles) { headTransform.rotation = Quaternion.Euler(newRotation); } if (resetHand) { headTransform.position = Vector3.zero; headTransform.rotation = Quaternion.identity; } } } private void DrawHandsGUI() { ControllerSimulationMode newHandSimMode = (ControllerSimulationMode)EditorGUILayout.EnumPopup("Hand Simulation Mode", SimulationService.ControllerSimulationMode); if (newHandSimMode != SimulationService.ControllerSimulationMode) { SimulationService.ControllerSimulationMode = newHandSimMode; } using (new GUILayout.HorizontalScope()) { DrawHandGUI( "Left", SimulationService.IsAlwaysVisibleControllerLeft, v => SimulationService.IsAlwaysVisibleControllerLeft = v, SimulationService.ControllerPositionLeft, v => SimulationService.ControllerPositionLeft = v, SimulationService.ControllerRotationLeft, v => SimulationService.ControllerRotationLeft = v, SimulationService.ResetControllerLeft); DrawHandGUI( "Right", SimulationService.IsAlwaysVisibleControllerRight, v => SimulationService.IsAlwaysVisibleControllerRight = v, SimulationService.ControllerPositionRight, v => SimulationService.ControllerPositionRight = v, SimulationService.ControllerRotationRight, v => SimulationService.ControllerRotationRight = v, SimulationService.ResetControllerRight); } } private void DrawHandGUI(string name, bool isAlwaysVisible, Action<bool> setAlwaysVisible, Vector3 position, Action<Vector3> setPosition, Vector3 rotation, Action<Vector3> setRotation, Action reset) { using (new GUILayout.VerticalScope(EditorStyles.helpBox)) { GUILayout.Label($"{name} Hand:"); bool newIsAlwaysVisible = EditorGUILayout.Toggle("Always Visible", isAlwaysVisible); Vector3 newPosition = EditorGUILayout.Vector3Field("Position", position); Vector3 newRotation = DrawRotationGUI("Rotation", rotation); bool resetHand = GUILayout.Button("Reset"); if (newIsAlwaysVisible != isAlwaysVisible) { setAlwaysVisible(newIsAlwaysVisible); } if (newPosition != position) { setPosition(newPosition); } if (newRotation != rotation) { setRotation(newRotation); } if (resetHand) { reset(); } } } private void DrawRecordingGUI() { if (RecordingService == null) { EditorGUILayout.HelpBox("No input recording service found", MessageType.Info); return; } using (new GUILayout.HorizontalScope()) { bool newUseTimeLimit = GUILayout.Toggle(RecordingService.UseBufferTimeLimit, "Use buffer time limit"); if (newUseTimeLimit != RecordingService.UseBufferTimeLimit) { RecordingService.UseBufferTimeLimit = newUseTimeLimit; } using (new EditorGUI.DisabledGroupScope(!RecordingService.UseBufferTimeLimit)) { float newTimeLimit = EditorGUILayout.FloatField(RecordingService.RecordingBufferTimeLimit); if (newTimeLimit != RecordingService.RecordingBufferTimeLimit) { RecordingService.RecordingBufferTimeLimit = newTimeLimit; } } } bool wasRecording = RecordingService.IsRecording; var recordButtonContent = wasRecording ? new GUIContent(iconRecordActive, "Stop recording input animation") : new GUIContent(iconRecord, "Record new input animation"); bool record = GUILayout.Toggle(wasRecording, recordButtonContent, "Button"); if (record != wasRecording) { if (record) { RecordingService.StartRecording(); } else { RecordingService.StopRecording(); SaveAnimation(true); } } DrawAnimationInfo(); } private void DrawPlaybackGUI() { DrawAnimationInfo(); using (new GUILayout.HorizontalScope()) { if (GUILayout.Button("Load ...")) { string filepath = EditorUtility.OpenFilePanel( "Select input animation file", "", InputAnimationSerializationUtils.Extension); LoadAnimation(filepath); } } using (new EditorGUI.DisabledGroupScope(PlaybackService == null)) { bool wasPlaying = PlaybackService.IsPlaying; bool play, stepFwd, jumpBack, jumpFwd; using (new GUILayout.HorizontalScope()) { jumpBack = GUILayout.Button(new GUIContent(iconJumpBack, "Jump to the start of the input animation"), "Button"); var playButtonContent = wasPlaying ? new GUIContent(iconPause, "Stop playing input animation") : new GUIContent(iconPlay, "Play back input animation"); play = GUILayout.Toggle(wasPlaying, playButtonContent, "Button"); stepFwd = GUILayout.Button(new GUIContent(iconStepFwd, "Step forward one frame"), "Button"); jumpFwd = GUILayout.Button(new GUIContent(iconJumpFwd, "Jump to the end of the input animation"), "Button"); } float time = PlaybackService.LocalTime; float duration = (Animation != null ? Animation.Duration : 0.0f); float newTimeField = EditorGUILayout.FloatField("Current time", time); float newTimeSlider = GUILayout.HorizontalSlider(time, 0.0f, duration); if (play != wasPlaying) { if (play) { PlaybackService.Play(); } else { PlaybackService.Pause(); } } if (jumpBack) { PlaybackService.LocalTime = 0.0f; } if (jumpFwd) { PlaybackService.LocalTime = duration; } if (stepFwd) { PlaybackService.LocalTime += Time.deltaTime; } if (newTimeField != time) { PlaybackService.LocalTime = newTimeField; } if (newTimeSlider != time) { PlaybackService.LocalTime = newTimeSlider; } // Repaint while playing to update the timeline if (PlaybackService.IsPlaying) { Repaint(); } } } private void DrawAnimationInfo() { using (new GUILayout.VerticalScope(EditorStyles.helpBox)) { GUILayout.Label("Animation Info:", EditorStyles.boldLabel); if (Animation != null) { GUILayout.Label($"File Path: {loadedFilePath}"); GUILayout.Label($"Duration: {Animation.Duration} seconds"); } else { GUILayout.Label("No animation loaded"); } } } private Vector3 DrawRotationGUI(string label, Vector3 rotation) { Vector3 newRotation = EditorGUILayout.Vector3Field(label, rotation); return newRotation; } private void SaveAnimation(bool loadAfterExport) { string outputPath; if (loadedFilePath.Length > 0) { string loadedDirectory = Path.GetDirectoryName(loadedFilePath); outputPath = EditorUtility.SaveFilePanel( "Select output path", loadedDirectory, InputAnimationSerializationUtils.GetOutputFilename(), InputAnimationSerializationUtils.Extension); } else { outputPath = EditorUtility.SaveFilePanelInProject( "Select output path", InputAnimationSerializationUtils.GetOutputFilename(), InputAnimationSerializationUtils.Extension, "Enter filename for exporting input animation"); } if (outputPath.Length > 0) { string filename = Path.GetFileName(outputPath); string directory = Path.GetDirectoryName(outputPath); string result = RecordingService.SaveInputAnimation(filename, directory); RecordingService.DiscardRecordedInput(); if (loadAfterExport) { LoadAnimation(result); } } } private void LoadAnimation(string filepath) { if (PlaybackService.LoadInputAnimation(filepath)) { loadedFilePath = filepath; } else { loadedFilePath = ""; } } private void LoadIcons() { // MRTK_TimelinePlay.png LoadTexture(ref iconPlay, "474f3f21b48daea4f8617806305769ff"); // MRTK_TimelinePause.png LoadTexture(ref iconPause, "1bfd4df7e86b18640b9fa1af5713bfb9"); // MRTK_TimelineRecord.png LoadTexture(ref iconRecord, "c079cf55f13c1dc4db7d09053a51a40d"); // MRTK_TimelineRecordActive.png LoadTexture(ref iconRecordActive, "6752387ee2181ee4fbef5cc74691b6ac"); // MRTK_TimelineStepFwd.png LoadTexture(ref iconStepFwd, "230b98155638e544892c123d8d674737"); // MRTK_TimelineJumpFwd.png LoadTexture(ref iconJumpFwd, "3afb597cbd6ec44439ea7b8ce92d957a"); // MRTK_TimelineJumpBack.png LoadTexture(ref iconJumpBack, "a5d8e80a54741dc459e4f116e1d477f2"); } private static void LoadTexture(ref Texture2D tex, string fileGuid) { if (tex == null) { tex = AssetDatabase.LoadAssetAtPath<Texture2D>(AssetDatabase.GUIDToAssetPath(fileGuid)); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Jbi.Angular.Api.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
#if UNITY_EDITOR using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; [System.Serializable] public class Uni2DEditorAssetTable : ScriptableObject { // 1 Key => 0..n value(s) [System.Serializable] private class GenericValueEntry<T> { public string key = null; public T genericValue = default( T ); public GenericValueEntry( string a_rKey, T a_rValue ) { key = a_rKey; genericValue = a_rValue; } } [System.Serializable] private class SimpleValueEntry : GenericValueEntry<string> { public SimpleValueEntry( string a_rKey, string a_rValue ) :base( a_rKey, a_rValue ) { } } [System.Serializable] private class MultiValueEntry : GenericValueEntry<List<string>> { public MultiValueEntry( string a_rKey, List<string> a_rValue ) :base( a_rKey, a_rValue ) { } } private const string mc_oDefaultAssetLocation = "Assets/Uni2D_AssetTable.asset"; // Singleton ref. private static Uni2DEditorAssetTable ms_rInstance = null; [SerializeField] [HideInInspector] private List<SimpleValueEntry> m_oAtlasPathGUIDEntries = new List<SimpleValueEntry>( ); [SerializeField] [HideInInspector] private List<SimpleValueEntry> m_oClipPathGUIDEntries = new List<SimpleValueEntry>( ); [SerializeField] [HideInInspector] private List<SimpleValueEntry> m_oTextureImportGUIDEntries = new List<SimpleValueEntry>( ); // Texture GUIDs (multi atlas values dict key list) [SerializeField] [HideInInspector] private List<MultiValueEntry> m_oTextureGUIDAtlasEntries = new List<MultiValueEntry>( ); // Texture GUIDs (multi clip values dict key list) [SerializeField] [HideInInspector] private List<MultiValueEntry> m_oTextureGUIDClipEntries = new List<MultiValueEntry>( ); [SerializeField] [HideInInspector] private List<MultiValueEntry> m_oTextureGUIDSpritePrefabEntries = new List<MultiValueEntry>( ); [SerializeField] [HideInInspector] private List<MultiValueEntry> m_oAtlasGUIDSpritePrefabEntries = new List<MultiValueEntry>( ); // Multi-value dictionary ( 1 tex. GUID => 0..n atlas GUIDs) private MultiValueDictionary<string, string> m_oTextureGUIDAtlasGUIDsMultiDict = null; // Multi-value dictionary ( 1 tex. GUID => 0..n clip GUIDs) private MultiValueDictionary<string, string> m_oTextureGUIDClipGUIDsMultiDict = null; // Multi-value dictionary ( 1 tex. GUID => 0..n sprite prefab GUIDs) private MultiValueDictionary<string, string> m_oTextureGUIDSpritePrefabGUIDsMultiDict = null; // Multi-value dictionary ( 1 atlas GUID => 0..n sprite prefab GUIDs) private MultiValueDictionary<string, string> m_oAtlasGUIDSpritePrefabGUIDsMultiDict = null; // Single-value dictionary private Dictionary<string, string> m_oAtlasPathGUIDDict = null; // Single-value dictionary private Dictionary<string, string> m_oClipPathGUIDDict = null; // Texture Import GUID private Dictionary<string, string> m_oTextureImportGUIDDict = null; // Singleton accessors public static Uni2DEditorAssetTable Instance { get { if( ms_rInstance == null ) { // Try to load from database ms_rInstance = (Uni2DEditorAssetTable) AssetDatabase.LoadAssetAtPath( mc_oDefaultAssetLocation, typeof( Uni2DEditorAssetTable ) ); if( ms_rInstance == null ) { Uni2DEditorAssetTable[ ] rInstances = (Uni2DEditorAssetTable[ ]) Resources.FindObjectsOfTypeAll( typeof( Uni2DEditorAssetTable ) ); ms_rInstance = rInstances != null && rInstances.Length > 0 ? rInstances[ 0 ] : null; // Create the instance if( ms_rInstance == null ) { ms_rInstance = ScriptableObject.CreateInstance<Uni2DEditorAssetTable>( ); ms_rInstance.name = "Uni2D_AssetTable"; // Import it to database AssetDatabase.CreateAsset( ms_rInstance, mc_oDefaultAssetLocation ); AssetDatabase.ImportAsset( mc_oDefaultAssetLocation ); ms_rInstance = (Uni2DEditorAssetTable) AssetDatabase.LoadAssetAtPath( mc_oDefaultAssetLocation, typeof( Uni2DEditorAssetTable ) ); } else if( EditorUtility.IsPersistent( ms_rInstance ) == false ) { // Import it to database AssetDatabase.CreateAsset( ms_rInstance, mc_oDefaultAssetLocation ); AssetDatabase.ImportAsset( mc_oDefaultAssetLocation ); ms_rInstance = (Uni2DEditorAssetTable) AssetDatabase.LoadAssetAtPath( mc_oDefaultAssetLocation, typeof( Uni2DEditorAssetTable ) ); } } } return ms_rInstance; } set { ms_rInstance = value; } } public static bool AssetTableCreated { get { if( ms_rInstance == null ) { Uni2DEditorAssetTable rAssetTable = (Uni2DEditorAssetTable) AssetDatabase.LoadAssetAtPath( mc_oDefaultAssetLocation, typeof( Uni2DEditorAssetTable ) ); if( rAssetTable == null ) { Uni2DEditorAssetTable[ ] rInstances = (Uni2DEditorAssetTable[ ]) Resources.FindObjectsOfTypeAll( typeof( Uni2DEditorAssetTable ) ); return rInstances != null && rInstances.Length > 0; } return true; } return false; } } void OnEnable( ) { //Debug.Log( this.name + ": Deserializing..." ); // Create the multi value dictionary m_oTextureGUIDAtlasGUIDsMultiDict = this.BuildMultiDictFromEntries( m_oTextureGUIDAtlasEntries ); m_oTextureGUIDClipGUIDsMultiDict = this.BuildMultiDictFromEntries( m_oTextureGUIDClipEntries ); m_oTextureGUIDSpritePrefabGUIDsMultiDict = this.BuildMultiDictFromEntries( m_oTextureGUIDSpritePrefabEntries ); m_oAtlasGUIDSpritePrefabGUIDsMultiDict = this.BuildMultiDictFromEntries( m_oAtlasGUIDSpritePrefabEntries ); m_oAtlasPathGUIDDict = this.BuildDictFromEntries( m_oAtlasPathGUIDEntries ); m_oClipPathGUIDDict = this.BuildDictFromEntries( m_oClipPathGUIDEntries ); m_oTextureImportGUIDDict = BuildDictFromEntries( m_oTextureImportGUIDEntries ); } void OnDisable( ) { this.Save( ); } public void Save( ) { //Debug.Log( this.name + ": Serializing..." ); // Save multi value dictionaries into a serializable form this.BuildEntriesFromMultiDict( m_oTextureGUIDAtlasGUIDsMultiDict, out m_oTextureGUIDAtlasEntries ); this.BuildEntriesFromMultiDict( m_oTextureGUIDClipGUIDsMultiDict, out m_oTextureGUIDClipEntries ); this.BuildEntriesFromMultiDict( m_oTextureGUIDSpritePrefabGUIDsMultiDict, out m_oTextureGUIDSpritePrefabEntries ); this.BuildEntriesFromMultiDict( m_oAtlasGUIDSpritePrefabGUIDsMultiDict, out m_oAtlasGUIDSpritePrefabEntries ); this.BuildEntriesFromDict( m_oAtlasPathGUIDDict, out m_oAtlasPathGUIDEntries ); this.BuildEntriesFromDict( m_oClipPathGUIDDict, out m_oClipPathGUIDEntries ); this.BuildEntriesFromDict( m_oTextureImportGUIDDict, out m_oTextureImportGUIDEntries ); EditorUtility.SetDirty( this ); AssetDatabase.ImportAsset( AssetDatabase.GetAssetPath( this.GetInstanceID( ) ) ); } public void Rebuild( ) { //Debug.Log( "Rebuilding Uni2D Asset Table..." ); m_oAtlasGUIDSpritePrefabGUIDsMultiDict.Clear( ); m_oTextureGUIDAtlasGUIDsMultiDict.Clear( ); m_oTextureGUIDClipGUIDsMultiDict.Clear( ); m_oTextureGUIDSpritePrefabGUIDsMultiDict.Clear( ); m_oAtlasPathGUIDDict.Clear( ); m_oClipPathGUIDDict.Clear( ); m_oTextureImportGUIDDict.Clear(); // Iterate project's assets string[ ] rAssetPaths = AssetDatabase.GetAllAssetPaths( ); int iAssetCount = rAssetPaths.Length; float fInvAssetCount = 1.0f / (float) iAssetCount; int iProcessedAssets = 0; try { foreach( string rPath in rAssetPaths ) { EditorUtility.DisplayProgressBar( "Uni2D - Asset Table Rebuilding Progress", iProcessedAssets + " out of " + iAssetCount + " asset(s) processed...", fInvAssetCount * iProcessedAssets ); Object rAssetObject = null; // Might be an atlas or a clip if( rPath.EndsWith( ".prefab" ) ) { rAssetObject = AssetDatabase.LoadAssetAtPath( rPath, typeof( Uni2DTextureAtlas ) ); if( rAssetObject != null ) // It's an atlas { Uni2DTextureAtlas rAtlasAsset = (Uni2DTextureAtlas) rAssetObject; string rAtlasGUID = AssetDatabase.AssetPathToGUID( rPath ); foreach( string rTextureGUID in rAtlasAsset.GetTextureGUIDs( ) ) { this.AddAtlasUsingTexture( rAtlasGUID, rTextureGUID ); } m_oAtlasPathGUIDDict.Add( rPath, rAtlasGUID ); rAtlasAsset = null; EditorUtility.UnloadUnusedAssets( ); } rAssetObject = AssetDatabase.LoadAssetAtPath( rPath, typeof( Uni2DAnimationClip ) ); if( rAssetObject != null ) // It's an animation clip { Uni2DAnimationClip rAnimationClipAsset = (Uni2DAnimationClip) rAssetObject; string rAnimationClipGUID = AssetDatabase.AssetPathToGUID( rPath ); foreach( string rTextureGUID in rAnimationClipAsset.GetAllFramesTextureGUIDs( ) ) { this.AddClipUsingTexture( rAnimationClipGUID, rTextureGUID ); } m_oClipPathGUIDDict.Add( rPath, rAnimationClipGUID ); rAnimationClipAsset = null; EditorUtility.UnloadUnusedAssets( ); } rAssetObject = AssetDatabase.LoadAssetAtPath( rPath, typeof( GameObject ) ); if( rAssetObject != null ) // It's a sprite prefab { GameObject rPrefabAsset = (GameObject) rAssetObject; string rPrefabGUID = AssetDatabase.AssetPathToGUID( rPath ); Uni2DSprite[ ] rSpritePrefabComponents = rPrefabAsset.GetComponentsInChildren<Uni2DSprite>( true ); foreach( Uni2DSprite rSpritePrefabComponent in rSpritePrefabComponents ) { Uni2DEditorSpriteSettings rSpriteSettings = rSpritePrefabComponent.SpriteSettings; this.AddSpritePrefabUsingTexture( rPrefabGUID, rSpriteSettings.textureContainer.GUID ); if( rSpriteSettings.atlas != null ) { this.AddSpritePrefabUsingAtlas( rPrefabGUID, Uni2DEditorUtils.GetUnityAssetGUID( rSpriteSettings.atlas ) ); } } rPrefabAsset = null; rSpritePrefabComponents = null; EditorUtility.UnloadUnusedAssets( ); } } ++iProcessedAssets; } } finally { this.Save( ); EditorUtility.UnloadUnusedAssets( ); EditorUtility.SetDirty( this ); EditorUtility.ClearProgressBar( ); } //Debug.Log( "Uni2D Asset Table Rebuild: Done." ); } ///// Single query ///// public string GetTextureImportGUID(string a_oTextureGUID) { string oTextureImportGUID = ""; if(m_oTextureImportGUIDDict.TryGetValue(a_oTextureGUID, out oTextureImportGUID)) { return oTextureImportGUID; } else { return ""; } } public void SetTextureImportGUID(string a_oTextureGUID, string a_oTextureImportGUID) { if(m_oTextureImportGUIDDict.ContainsKey(a_oTextureGUID)) { m_oTextureImportGUIDDict[a_oTextureGUID] = a_oTextureImportGUID; } else { m_oTextureImportGUIDDict.Add(a_oTextureGUID, a_oTextureImportGUID); } } public string[ ] GetAtlasGUIDsUsingThisTexture( string a_rTextureGUID ) { return QueryMultiValueDict( m_oTextureGUIDAtlasGUIDsMultiDict, a_rTextureGUID ); } public string[ ] GetClipGUIDsUsingThisTexture( string a_rTextureGUID ) { return QueryMultiValueDict( m_oTextureGUIDClipGUIDsMultiDict, a_rTextureGUID ); } public string[ ] GetSpritePrefabGUIDsUsingThisTexture( string a_rTextureGUID ) { return QueryMultiValueDict( m_oTextureGUIDSpritePrefabGUIDsMultiDict, a_rTextureGUID ); } public Dictionary<string,string> GetClipNamesUsingThisTexture( string a_rTextureGUID ) { return this.GetAssetNamesContainingThisTexture( m_oTextureGUIDClipGUIDsMultiDict, a_rTextureGUID ); } public Dictionary<string,string> GetAtlasNamesUsingThisTexture( string a_rTextureGUID ) { return this.GetAssetNamesContainingThisTexture( m_oTextureGUIDAtlasGUIDsMultiDict, a_rTextureGUID ); } public string[ ] GetSpritePrefabGUIDsUsingThisAtlas( string a_rAtlasGUID ) { return this.QueryMultiValueDict( m_oAtlasGUIDSpritePrefabGUIDsMultiDict, a_rAtlasGUID ); } ///// Multi query ///// public string[ ] GetAtlasGUIDsUsingTheseTextures( IEnumerable<string> a_rTextureGUIDs ) { return MultiQueryMultiValueDict( m_oTextureGUIDAtlasGUIDsMultiDict, a_rTextureGUIDs ); } public string[ ] GetClipGUIDsUsingTheseTextures( IEnumerable<string> a_rTextureGUIDs ) { return MultiQueryMultiValueDict( m_oTextureGUIDClipGUIDsMultiDict, a_rTextureGUIDs ); } public string[ ] GetSpritePrefabGUIDsUsingTheseTextures( IEnumerable<string> a_rTextureGUIDs ) { return MultiQueryMultiValueDict( m_oTextureGUIDSpritePrefabGUIDsMultiDict, a_rTextureGUIDs ); } public Dictionary<string,string> GetClipNamesUsingTheseTextures( IEnumerable<string> a_rTextureGUIDs ) { return this.GetAssetNamesContainingTheseTextures( m_oTextureGUIDClipGUIDsMultiDict, a_rTextureGUIDs ); } public Dictionary<string,string> GetAtlasNamesUsingTheseTextures( IEnumerable<string> a_rTextureGUIDs ) { return this.GetAssetNamesContainingTheseTextures( m_oTextureGUIDAtlasGUIDsMultiDict, a_rTextureGUIDs ); } public string[ ] GetSpritePrefabGUIDsUsingTheseAtlases( IEnumerable<string> a_rAtlasGUIDs ) { return this.MultiQueryMultiValueDict( m_oAtlasGUIDSpritePrefabGUIDsMultiDict, a_rAtlasGUIDs ); } public Dictionary<string, string> GetAllAtlasNames( ) { Dictionary<string, string> oAtlasGUIDNameDict = new Dictionary<string, string>( m_oAtlasPathGUIDDict.Count ); foreach( KeyValuePair<string, string> rKeyValuePair in m_oAtlasPathGUIDDict ) { oAtlasGUIDNameDict.Add( rKeyValuePair.Value, Path.GetFileNameWithoutExtension( rKeyValuePair.Key ) ); } return oAtlasGUIDNameDict; } public Dictionary<string, string> GetAllClipNames( ) { Dictionary<string, string> oClipGUIDNameDict = new Dictionary<string, string>( m_oClipPathGUIDDict.Count ); foreach( KeyValuePair<string, string> rKeyValuePair in m_oClipPathGUIDDict ) { oClipGUIDNameDict.Add( rKeyValuePair.Value, Path.GetFileNameWithoutExtension( rKeyValuePair.Key ) ); } return oClipGUIDNameDict; } ///// Add methods ///// public void AddAtlasUsingTexture( string a_rAtlasGUID, string a_rTextureGUID ) { m_oTextureGUIDAtlasGUIDsMultiDict.Add( a_rTextureGUID, a_rAtlasGUID ); EditorUtility.SetDirty( this ); } public void AddClipUsingTexture( string a_rAnimationClipGUID, string a_rTextureGUID ) { m_oTextureGUIDClipGUIDsMultiDict.Add( a_rTextureGUID, a_rAnimationClipGUID ); EditorUtility.SetDirty( this ); } public void AddSpritePrefabUsingTexture( string a_rSpritePrefabGUID, string a_rTextureGUID ) { m_oTextureGUIDSpritePrefabGUIDsMultiDict.Add( a_rTextureGUID, a_rSpritePrefabGUID ); EditorUtility.SetDirty( this ); } public void AddSpritePrefabUsingAtlas( string a_rSpritePrefabGUID, string a_rAtlasGUID ) { m_oAtlasGUIDSpritePrefabGUIDsMultiDict.Add( a_rAtlasGUID, a_rSpritePrefabGUID ); EditorUtility.SetDirty( this ); } ///// Remove methods ///// public void RemoveAtlasUsingTexture( string a_rAtlasGUID, string a_rTextureGUID ) { m_oTextureGUIDAtlasGUIDsMultiDict.Remove( a_rTextureGUID, a_rAtlasGUID ); EditorUtility.SetDirty( this ); } public void RemoveClipUsingTexture( string a_rAnimationClipGUID, string a_rTextureGUID ) { m_oTextureGUIDClipGUIDsMultiDict.Remove( a_rTextureGUID, a_rAnimationClipGUID ); EditorUtility.SetDirty( this ); } public void RemoveSpritePrefabUsingTexture( string a_rSpritePrefabGUID, string a_rTextureGUID ) { m_oTextureGUIDSpritePrefabGUIDsMultiDict.Remove( a_rTextureGUID, a_rSpritePrefabGUID ); EditorUtility.SetDirty( this ); } public void RemoveSpritePrefabUsingAtlas( string a_rSpritePrefabGUID, string a_rAtlasGUID ) { m_oAtlasGUIDSpritePrefabGUIDsMultiDict.Remove( a_rAtlasGUID, a_rSpritePrefabGUID ); EditorUtility.SetDirty( this ); } public void AddAtlasPath( string a_rAtlasPath, string a_rAtlasGUID ) { m_oAtlasPathGUIDDict[ a_rAtlasPath ] = a_rAtlasGUID; EditorUtility.SetDirty( this ); } public void AddClipPath( string a_rClipPath, string a_rClipGUID ) { m_oClipPathGUIDDict[ a_rClipPath ] = a_rClipGUID; EditorUtility.SetDirty( this ); } public bool RemoveAtlasFromPath( string a_rAtlasPath, bool a_bRemoveDependencies ) { string rAtlasGUID; if( m_oAtlasPathGUIDDict.TryGetValue( a_rAtlasPath, out rAtlasGUID ) ) { if( a_bRemoveDependencies ) { string[ ] rSpritePrefabGUIDs = this.GetSpritePrefabGUIDsUsingThisAtlas( rAtlasGUID ); foreach( string rSpritePrefabGUID in rSpritePrefabGUIDs ) { this.RemoveSpritePrefabUsingAtlas( rSpritePrefabGUID, rAtlasGUID ); } m_oTextureGUIDAtlasGUIDsMultiDict.RemoveAll( rAtlasGUID ); } m_oAtlasPathGUIDDict.Remove( a_rAtlasPath ); EditorUtility.SetDirty( this ); return true; } return false; } public bool RemoveClipFromPath( string a_rClipPath, bool a_bRemoveDependencies ) { string rClipGUID; if( m_oClipPathGUIDDict.TryGetValue( a_rClipPath, out rClipGUID ) ) { if( a_bRemoveDependencies ) { m_oTextureGUIDClipGUIDsMultiDict.RemoveAll( rClipGUID ); } m_oClipPathGUIDDict.Remove( a_rClipPath ); EditorUtility.SetDirty( this ); return true; } return false; } public string[ ] GetSpritePrefabGUIDsUsingThisAtlasPath( string a_rAtlasPath ) { string oAtlasGUID; if( m_oAtlasPathGUIDDict.TryGetValue( a_rAtlasPath, out oAtlasGUID ) ) { return this.GetSpritePrefabGUIDsUsingThisAtlas( oAtlasGUID ); } return new string[ 0 ]; } ///// Internal logic methods ///// private Dictionary<string,string> GetAssetNamesContainingThisTexture( MultiValueDictionary<string,string> a_rMultiDict, string a_rTextureGUID ) { string[ ] rGUIDs = this.QueryMultiValueDict( a_rMultiDict, a_rTextureGUID ); return this.GetAssetNamesFromGUIDsAndRemoveOutdatedOnes( a_rMultiDict, rGUIDs ); } private Dictionary<string,string> GetAssetNamesContainingTheseTextures( MultiValueDictionary<string,string> a_rMultiDict, IEnumerable<string> a_rTextureGUIDs ) { string[ ] rGUIDs = this.MultiQueryMultiValueDict( a_rMultiDict, a_rTextureGUIDs ); return this.GetAssetNamesFromGUIDsAndRemoveOutdatedOnes( a_rMultiDict, rGUIDs ); } private Dictionary<string,string> GetAssetNamesFromGUIDsAndRemoveOutdatedOnes( MultiValueDictionary<string,string> a_rMultiDict, IEnumerable<string> a_rGUIDs ) { Dictionary<string,string> oGUIDNamesDict = new Dictionary<string,string>( ); List<string> oOutdatedGUIDs = new List<string>( ); foreach( string rGUID in a_rGUIDs ) { string oName = Uni2DEditorUtils.GetAssetNameFromUnityGUID( rGUID ); if( oName != null ) { oGUIDNamesDict.Add( rGUID, oName ); } else { // Name is null => asset doesn't exist anymore oOutdatedGUIDs.Add( rGUID ); } } // Remove the outdated GUID from our multi-value dict foreach( string rOutdatedGUID in oOutdatedGUIDs ) { MultiValueDictionary<string,string>.KeyCollection rKeys = a_rMultiDict.Keys; foreach( string rKey in rKeys ) { if( a_rMultiDict.ContainsValue( rKey, rOutdatedGUID ) ) { a_rMultiDict.Remove( rKey, rOutdatedGUID ); } } // TODO: save? } return oGUIDNamesDict; } private Dictionary<string, string> BuildDictFromEntries( List<SimpleValueEntry> a_rEntries ) { Dictionary<string, string> oDict = new Dictionary<string, string>( a_rEntries.Count ); foreach( SimpleValueEntry rEntry in a_rEntries ) { oDict.Add( rEntry.key, rEntry.genericValue ); } return oDict; } private MultiValueDictionary<string,string> BuildMultiDictFromEntries( List<MultiValueEntry> a_rEntries ) { MultiValueDictionary<string,string> oMultiDict = new MultiValueDictionary<string, string>( ); foreach( MultiValueEntry rEntry in a_rEntries ) { string rKey = rEntry.key; foreach( string rValue in rEntry.genericValue ) { oMultiDict.Add( rKey, rValue ); } } return oMultiDict; } private void BuildEntriesFromMultiDict( MultiValueDictionary<string, string> a_rMultiDictToSplit, out List<MultiValueEntry> a_rEntries ) { a_rEntries = new List<MultiValueEntry>( a_rMultiDictToSplit.Count ); foreach( KeyValuePair<string, HashSet<string> > rEntry in a_rMultiDictToSplit ) { a_rEntries.Add( new MultiValueEntry( rEntry.Key, new List<string>( rEntry.Value ) ) ); } } private void BuildEntriesFromDict( Dictionary<string, string> a_rDictToSplit, out List<SimpleValueEntry> a_rEntries ) { a_rEntries = new List<SimpleValueEntry>( a_rDictToSplit.Count ); foreach( KeyValuePair<string, string> rEntry in a_rDictToSplit ) { a_rEntries.Add( new SimpleValueEntry( rEntry.Key, rEntry.Value ) ); } } private string[ ] QueryMultiValueDict( MultiValueDictionary<string, string> a_rMultiDict, string a_rKey ) { HashSet<string> rValues; if( a_rMultiDict.TryGetValue( a_rKey, out rValues ) ) { return new List<string>( rValues ).ToArray( ); } else { return new string[ 0 ]; } } private string[ ] MultiQueryMultiValueDict( MultiValueDictionary<string, string> a_rMultiDict, IEnumerable<string> a_rKeys, bool a_bUnionResults = true ) { HashSet<string> rResults = new HashSet<string>( ); if( a_bUnionResults ) { foreach( string rKey in a_rKeys ) { HashSet<string> rValues = null; if( a_rMultiDict.TryGetValue( rKey, out rValues ) ) { rResults.UnionWith( rValues ); } } } else { foreach( string rKey in a_rKeys ) { HashSet<string> rValues = null; if( a_rMultiDict.TryGetValue( rKey, out rValues ) ) { rResults.IntersectWith( rValues ); } } } return new List<string>( rResults ).ToArray( ); } } #endif
// ***************************************************************************** // // (c) Crownwood Consulting Limited 2002 // All rights reserved. The software and associated documentation // supplied hereunder are the proprietary information of Crownwood Consulting // Limited, Haxey, North Lincolnshire, England and are supplied subject to // licence terms. // // IDE Version 1.7 www.dotnetmagic.com // ***************************************************************************** using System; using System.Drawing; using System.Windows.Forms; using IDE.Common; namespace IDE.Docking { internal class HotZoneFloating : HotZone { // Instance fields protected Point _offset; protected Point _drawPos; protected Rectangle _drawRect; protected RedockerContent _redocker; public HotZoneFloating(Rectangle hotArea, Rectangle newSize, Point offset, RedockerContent redocker) : base(hotArea, newSize) { // Store initial state _offset = offset; _redocker = redocker; Size floatSize = CalculateFloatingSize(); float widthPercentage = (float)floatSize.Width / (float)_newSize.Width; float heightPercentage = (float)floatSize.Height / (float)_newSize.Height; _newSize.Width = floatSize.Width; _newSize.Height = floatSize.Height + SystemInformation.ToolWindowCaptionHeight; _offset.X = (int)((float) _offset.X * widthPercentage); _offset.Y = (int)((float) _offset.Y * heightPercentage); // We do not want the indicator to be too far away from the cursor, so limit check the offset if (_offset.X > newSize.Width) _offset.X = newSize.Width; if (_offset.Y > newSize.Height) _offset.Y = newSize.Height; } public override bool ApplyChange(Point screenPos, Redocker parent) { // Should always be the appropriate type RedockerContent redock = parent as RedockerContent; DockingManager dockingManager = redock.DockingManager; Zone newZone = null; // Manageing Zones should remove display AutoHide windows dockingManager.RemoveShowingAutoHideWindows(); switch(redock.DockingSource) { case RedockerContent.Source.RawContent: { // Perform State specific Restore actions redock.Content.ContentBecomesFloating(); // Create a new Window to host Content Window w = dockingManager.CreateWindowForContent(redock.Content); // We need to create a Zone for containing the transfered content newZone = dockingManager.CreateZoneForContent(State.Floating); // Add into Zone newZone.Windows.Add(w); } break; case RedockerContent.Source.WindowContent: // Perform State specific Restore actions foreach(Content c in redock.WindowContent.Contents) c.ContentBecomesFloating(); // Remove WindowContent from old Zone if (redock.WindowContent.ParentZone != null) redock.WindowContent.ParentZone.Windows.Remove(redock.WindowContent); // We need to create a Zone for containing the transfered content newZone = dockingManager.CreateZoneForContent(State.Floating); // Add into new Zone newZone.Windows.Add(redock.WindowContent); break; case RedockerContent.Source.ContentInsideWindow: { // Perform State specific Restore actions redock.Content.ContentBecomesFloating(); // Remove Content from existing WindowContent if (redock.Content.ParentWindowContent != null) redock.Content.ParentWindowContent.Contents.Remove(redock.Content); // Create a new Window to host Content Window w = dockingManager.CreateWindowForContent(redock.Content); // We need to create a Zone for containing the transfered content newZone = dockingManager.CreateZoneForContent(State.Floating); // Add into Zone newZone.Windows.Add(w); } break; case RedockerContent.Source.FloatingForm: redock.FloatingForm.Location = new Point(screenPos.X - _offset.X, screenPos.Y - _offset.Y); return false; } dockingManager.UpdateInsideFill(); // Create a new floating form FloatingForm floating = new FloatingForm(redock.DockingManager, newZone, new ContextHandler(dockingManager.OnShowContextMenu)); // Find screen location/size _drawRect = new Rectangle(screenPos.X, screenPos.Y, _newSize.Width, _newSize.Height); // Adjust for mouse starting position relative to source control _drawRect.X -= _offset.X; _drawRect.Y -= _offset.Y; // Define its location/size floating.Location = new Point(_drawRect.Left, _drawRect.Top); floating.Size = new Size(_drawRect.Width, _drawRect.Height); // Show it! floating.Show(); return true; } public override void UpdateForMousePosition(Point screenPos, Redocker parent) { // Remember the current mouse pos Point newPos = screenPos; // Calculate the new drawing rectangle Rectangle newRect = new Rectangle(newPos.X, newPos.Y, _newSize.Width, _newSize.Height); // Adjust for mouse starting position relative to source control newRect.X -= _offset.X; newRect.Y -= _offset.Y; // Draw both the old rectangle and the new one, that will remove flicker as the // draw method will only actually draw areas that differ between the two rectangles DrawHelper.DrawDragRectangles(new Rectangle[]{_drawRect,newRect}, _dragWidth); // Remember new values _drawPos = newPos; _drawRect = newRect; } public override void DrawIndicator(Point mousePos) { // Remember the current mouse pos _drawPos = mousePos; // Calculate the new drawing rectangle _drawRect = new Rectangle(_drawPos.X, _drawPos.Y, _newSize.Width, _newSize.Height); // Adjust for mouse starting position relative to source control _drawRect.X -= _offset.X; _drawRect.Y -= _offset.Y; DrawReversible(_drawRect); } public override void RemoveIndicator(Point mousePos) { DrawReversible(_drawRect); } protected Size CalculateFloatingSize() { Size floatingSize = new Size(0,0); // Get specific redocker type RedockerContent redock = _redocker as RedockerContent; switch(redock.DockingSource) { case RedockerContent.Source.RawContent: // Whole Form is size requested by single Content floatingSize = redock.Content.FloatingSize; break; case RedockerContent.Source.WindowContent: // Find the largest requested floating size foreach(Content c in redock.WindowContent.Contents) { if (c.FloatingSize.Width > floatingSize.Width) floatingSize.Width = c.FloatingSize.Width; if (c.FloatingSize.Height > floatingSize.Height) floatingSize.Height = c.FloatingSize.Height; } // Apply same size to all Content objects foreach(Content c in redock.WindowContent.Contents) c.FloatingSize = floatingSize; break; case RedockerContent.Source.ContentInsideWindow: // Whole Form is size requested by single Content floatingSize = redock.Content.FloatingSize; break; case RedockerContent.Source.FloatingForm: // Use the requested size floatingSize.Width = _newSize.Width; floatingSize.Height = _newSize.Height; break; } return floatingSize; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Xml; using System.Text; using System.IO; using System.Globalization; using OLEDB.Test.ModuleCore; using System.Collections.Generic; using System.Threading.Tasks; /// <summary> /// Summary description for Class1 /// </summary> namespace XmlCoreTest.Common { public class aaaa { }; public class AsyncUtil { public static bool IsAsyncEnabled { get { // looking for ltm command line option like "/Async true" string asyncOption = CModInfo.Options["Async"] as string; if (!string.IsNullOrEmpty(asyncOption)) { if (string.Compare("TRUE", asyncOption) == 0) return true; } return false; } } private static bool _redirectReader = true; // for debugging, set this to false if want to stop the async XmlReader testing temporary during debugging public static bool RedirectReader { get { return _redirectReader; } } private static bool _redirectWriter = true; // for debugging, set this to false if want to stop the async XmlWriter testing temporary during debugging public static bool RedirectWriter { get { return _redirectWriter; } } } public class RedirectSyncCallToAsyncCallXmlReader : XmlReader, IXmlLineInfo //inherit from XmlReader so that we don't have the change the return type of function that returns a XmlReader { // the real XmlReader private XmlReader _reader = null; public XmlReader CoreReader { get { return _reader; } set { _reader = value; } } public RedirectSyncCallToAsyncCallXmlReader(XmlReader xr) { CoreReader = xr; } // #region Rewrite Methods has async counterpart public override bool Read() { if (AsyncUtil.RedirectReader) { try { Task<bool> t = CoreReader.ReadAsync(); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.Read(); } } public override Task<bool> ReadAsync() { return CoreReader.ReadAsync(); } public override string Value { get { if (AsyncUtil.RedirectReader) { try { Task<string> t = CoreReader.GetValueAsync(); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.Value; } } } public override Task<string> GetValueAsync() { return CoreReader.GetValueAsync(); } public override XmlNodeType MoveToContent() { if (AsyncUtil.RedirectReader) { try { Task<XmlNodeType> t = CoreReader.MoveToContentAsync(); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.MoveToContent(); } } public override Task<XmlNodeType> MoveToContentAsync() { return CoreReader.MoveToContentAsync(); } public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { if (AsyncUtil.RedirectReader) { try { Task<object> t = CoreReader.ReadContentAsAsync(returnType, namespaceResolver); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadContentAs(returnType, namespaceResolver); } } public override Task<object> ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver) { return CoreReader.ReadContentAsAsync(returnType, namespaceResolver); } public override int ReadContentAsBase64(byte[] buffer, int index, int count) { if (AsyncUtil.RedirectReader) { try { Task<int> t = CoreReader.ReadContentAsBase64Async(buffer, index, count); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadContentAsBase64(buffer, index, count); } } public override Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count) { return CoreReader.ReadContentAsBase64Async(buffer, index, count); } public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { if (AsyncUtil.RedirectReader) { try { Task<int> t = CoreReader.ReadContentAsBinHexAsync(buffer, index, count); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadContentAsBinHex(buffer, index, count); } } public override Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count) { return CoreReader.ReadContentAsBinHexAsync(buffer, index, count); } public override object ReadContentAsObject() { if (AsyncUtil.RedirectReader) { try { Task<object> t = CoreReader.ReadContentAsObjectAsync(); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadContentAsObject(); } } public override Task<object> ReadContentAsObjectAsync() { return CoreReader.ReadContentAsObjectAsync(); } public override string ReadContentAsString() { if (AsyncUtil.RedirectReader) { try { Task<string> t = CoreReader.ReadContentAsStringAsync(); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadContentAsString(); } } public override Task<string> ReadContentAsStringAsync() { return CoreReader.ReadContentAsStringAsync(); } public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { if (AsyncUtil.RedirectReader) { try { Task<object> t = CoreReader.ReadElementContentAsAsync(returnType, namespaceResolver); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadElementContentAs(returnType, namespaceResolver); } } public override Task<object> ReadElementContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver) { return CoreReader.ReadElementContentAsAsync(returnType, namespaceResolver); } public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { if (AsyncUtil.RedirectReader) { try { Task<int> t = CoreReader.ReadElementContentAsBase64Async(buffer, index, count); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadElementContentAsBase64(buffer, index, count); } } public override Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count) { return CoreReader.ReadElementContentAsBase64Async(buffer, index, count); } public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { if (AsyncUtil.RedirectReader) { try { Task<int> t = CoreReader.ReadElementContentAsBinHexAsync(buffer, index, count); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadElementContentAsBinHex(buffer, index, count); } } public override Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) { return CoreReader.ReadElementContentAsBinHexAsync(buffer, index, count); } public override object ReadElementContentAsObject() { if (AsyncUtil.RedirectReader) { try { Task<object> t = CoreReader.ReadElementContentAsObjectAsync(); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadElementContentAsObject(); } } public override Task<object> ReadElementContentAsObjectAsync() { return CoreReader.ReadElementContentAsObjectAsync(); } public override string ReadElementContentAsString() { if (AsyncUtil.RedirectReader) { try { Task<string> t = CoreReader.ReadElementContentAsStringAsync(); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadElementContentAsString(); } } public override Task<string> ReadElementContentAsStringAsync() { return CoreReader.ReadElementContentAsStringAsync(); } public override string ReadInnerXml() { if (AsyncUtil.RedirectReader) { try { Task<string> t = CoreReader.ReadInnerXmlAsync(); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadInnerXml(); } } public override Task<string> ReadInnerXmlAsync() { return CoreReader.ReadInnerXmlAsync(); } public override string ReadOuterXml() { if (AsyncUtil.RedirectReader) { try { Task<string> t = CoreReader.ReadOuterXmlAsync(); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadOuterXml(); } } public override Task<string> ReadOuterXmlAsync() { return CoreReader.ReadOuterXmlAsync(); } public override int ReadValueChunk(char[] buffer, int index, int count) { if (AsyncUtil.RedirectReader) { try { Task<int> t = CoreReader.ReadValueChunkAsync(buffer, index, count); t.Wait(); return t.Result; } catch (AggregateException ae) { throw ae.InnerException; } } else { return CoreReader.ReadValueChunk(buffer, index, count); } } public override Task<int> ReadValueChunkAsync(char[] buffer, int index, int count) { return CoreReader.ReadValueChunkAsync(buffer, index, count); } public override void Skip() { if (AsyncUtil.RedirectReader) { try { CoreReader.SkipAsync().Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreReader.Skip(); } } public override Task SkipAsync() { return CoreReader.SkipAsync(); } //#endregion #region Forward the call to the core reader /// <summary> /// Attributes and methods that don't need redirect /// </summary> public override XmlReaderSettings Settings { get { return CoreReader.Settings; } } public override XmlNodeType NodeType { get { return CoreReader.NodeType; } } public override string Name { get { return CoreReader.Name; } } public override string LocalName { get { return CoreReader.LocalName; } } public override string NamespaceURI { get { return CoreReader.NamespaceURI; } } public override string Prefix { get { return CoreReader.Prefix; } } public override bool HasValue { get { return CoreReader.HasValue; } } public override int Depth { get { return CoreReader.Depth; } } public override string BaseURI { get { return CoreReader.BaseURI; } } public override bool IsEmptyElement { get { return CoreReader.IsEmptyElement; } } public override bool IsDefault { get { return CoreReader.IsDefault; } } public override XmlSpace XmlSpace { get { return CoreReader.XmlSpace; } } public override string XmlLang { get { return CoreReader.XmlLang; } } public override System.Type ValueType { get { return CoreReader.ValueType; } } public override int AttributeCount { get { return CoreReader.AttributeCount; } } public override string GetAttribute(string name) { return CoreReader.GetAttribute(name); } public override string GetAttribute(string name, string namespaceURI) { return CoreReader.GetAttribute(name, namespaceURI); } public override string GetAttribute(int i) { return CoreReader.GetAttribute(i); } public override string this[int i] { get { return CoreReader.GetAttribute(i); } } public override string this[string name] { get { return CoreReader.GetAttribute(name); } } public override string this[string name, string namespaceURI] { get { return CoreReader.GetAttribute(name, namespaceURI); } } public override bool MoveToAttribute(string name) { return CoreReader.MoveToAttribute(name); } public override bool MoveToAttribute(string name, string ns) { return CoreReader.MoveToAttribute(name, ns); } public override void MoveToAttribute(int i) { CoreReader.MoveToAttribute(i); } // Moves to the first attribute of the current node. public override bool MoveToFirstAttribute() { return CoreReader.MoveToFirstAttribute(); } // Moves to the next attribute. public override bool MoveToNextAttribute() { return CoreReader.MoveToNextAttribute(); } // Moves to the element that contains the current attribute node. public override bool MoveToElement() { return CoreReader.MoveToElement(); } public override bool ReadAttributeValue() { return CoreReader.ReadAttributeValue(); } public override bool EOF { get { return CoreReader.EOF; } } public override ReadState ReadState { get { return CoreReader.ReadState; } } public override XmlNameTable NameTable { get { return CoreReader.NameTable; } } public override string LookupNamespace(string prefix) { return CoreReader.LookupNamespace(prefix); } public override bool CanResolveEntity { get { return CoreReader.CanResolveEntity; } } public override void ResolveEntity() { CoreReader.ResolveEntity(); } public override bool CanReadBinaryContent { get { return CoreReader.CanReadBinaryContent; } } public override bool CanReadValueChunk { get { return CoreReader.CanReadValueChunk; } } public override bool IsStartElement() { return CoreReader.IsStartElement(); } public override bool IsStartElement(string name) { return CoreReader.IsStartElement(name); } public override bool IsStartElement(string localname, string ns) { return CoreReader.IsStartElement(localname, ns); } public override XmlReader ReadSubtree() { return CoreReader.ReadSubtree(); } public override bool HasAttributes { get { return CoreReader.HasAttributes; } } public new void Dispose() { CoreReader.Dispose(); } public bool HasLineInfo() { IXmlLineInfo ili = CoreReader as IXmlLineInfo; if (ili != null) return ili.HasLineInfo(); return false; } public override bool ReadContentAsBoolean() { return CoreReader.ReadContentAsBoolean(); } public override DateTimeOffset ReadContentAsDateTimeOffset() { return CoreReader.ReadContentAsDateTimeOffset(); } public override double ReadContentAsDouble() { return CoreReader.ReadContentAsDouble(); } public override float ReadContentAsFloat() { return CoreReader.ReadContentAsFloat(); } public override decimal ReadContentAsDecimal() { return CoreReader.ReadContentAsDecimal(); } public override int ReadContentAsInt() { return CoreReader.ReadContentAsInt(); } public override long ReadContentAsLong() { return CoreReader.ReadContentAsLong(); } public override object ReadElementContentAsObject(string localName, string namespaceURI) { return CoreReader.ReadElementContentAsObject(localName, namespaceURI); } public override bool ReadElementContentAsBoolean() { return CoreReader.ReadElementContentAsBoolean(); } public override bool ReadElementContentAsBoolean(string localName, string namespaceURI) { return CoreReader.ReadElementContentAsBoolean(localName, namespaceURI); } public override double ReadElementContentAsDouble() { return CoreReader.ReadElementContentAsDouble(); } public override double ReadElementContentAsDouble(string localName, string namespaceURI) { return CoreReader.ReadElementContentAsDouble(localName, namespaceURI); } public override float ReadElementContentAsFloat() { return CoreReader.ReadElementContentAsFloat(); } public override float ReadElementContentAsFloat(string localName, string namespaceURI) { return CoreReader.ReadElementContentAsFloat(localName, namespaceURI); } public override decimal ReadElementContentAsDecimal() { return CoreReader.ReadElementContentAsDecimal(); } public override decimal ReadElementContentAsDecimal(string localName, string namespaceURI) { return CoreReader.ReadElementContentAsDecimal(localName, namespaceURI); } public override int ReadElementContentAsInt() { return CoreReader.ReadElementContentAsInt(); } public override int ReadElementContentAsInt(string localName, string namespaceURI) { return CoreReader.ReadElementContentAsInt(localName, namespaceURI); } public override long ReadElementContentAsLong() { return CoreReader.ReadElementContentAsLong(); } public override long ReadElementContentAsLong(string localName, string namespaceURI) { return CoreReader.ReadElementContentAsLong(localName, namespaceURI); } public override string ReadElementContentAsString(string localName, string namespaceURI) { return CoreReader.ReadElementContentAsString(localName, namespaceURI); } public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI) { return CoreReader.ReadElementContentAs(returnType, namespaceResolver, localName, namespaceURI); } public override void ReadStartElement() { CoreReader.ReadStartElement(); } public override void ReadStartElement(string name) { CoreReader.ReadStartElement(name); } public override void ReadStartElement(string localname, string ns) { CoreReader.ReadStartElement(localname, ns); } public override void ReadEndElement() { CoreReader.ReadEndElement(); } public override bool ReadToFollowing(string name) { return CoreReader.ReadToFollowing(name); } public override bool ReadToFollowing(string localName, string namespaceURI) { return CoreReader.ReadToFollowing(localName, namespaceURI); } public override bool ReadToDescendant(string name) { return CoreReader.ReadToDescendant(name); } public override bool ReadToDescendant(string localName, string namespaceURI) { return CoreReader.ReadToDescendant(localName, namespaceURI); } public override bool ReadToNextSibling(string name) { return CoreReader.ReadToNextSibling(name); } public override bool ReadToNextSibling(string localName, string namespaceURI) { return CoreReader.ReadToNextSibling(localName, namespaceURI); } // Returns the line number of the current node public int LineNumber { get { IXmlLineInfo ili = CoreReader as IXmlLineInfo; if (ili != null) return ili.LineNumber; return 0; } } // Returns the line position of the current node public int LinePosition { get { IXmlLineInfo ili = CoreReader as IXmlLineInfo; if (ili != null) return ili.LinePosition; return 0; } } #endregion } /// <summary> /// This class provide serials Create() methods to create async XmlReader, designed to replace XmlReaderCreate() with XmlReaderAsync.Create(). /// Every XmlReader created by this class will forced to be async. /// </summary> public class XmlReaderAsync { public static XmlReader Create(String inputUri, XmlReaderSettings settings = null, XmlParserContext inputContext = null) { if (settings == null) { settings = new XmlReaderSettings(); } if (AsyncUtil.RedirectWriter) { settings.Async = true; // force async } inputContext = null; return new RedirectSyncCallToAsyncCallXmlReader(XmlReader.Create(inputUri, settings)); } public static XmlReader Create(Stream input) { return Create(input, (XmlReaderSettings)null, (string)string.Empty); } public static XmlReader Create(Stream input, XmlReaderSettings settings) { return Create(input, settings, string.Empty); } public static XmlReader Create(Stream input, XmlReaderSettings settings, string baseUri) { if (settings == null) { settings = new XmlReaderSettings(); } if (AsyncUtil.RedirectWriter) { settings.Async = true; // force async } baseUri = null; return new RedirectSyncCallToAsyncCallXmlReader(XmlReader.Create(input, settings)); } public static XmlReader Create(Stream input, XmlReaderSettings settings, XmlParserContext inputContext) { if (settings == null) { settings = new XmlReaderSettings(); } if (AsyncUtil.RedirectWriter) { settings.Async = true; // force async } return new RedirectSyncCallToAsyncCallXmlReader(XmlReader.Create(input, settings, inputContext)); } public static XmlReader Create(TextReader input) { return Create(input, (XmlReaderSettings)null, (string)string.Empty); } public static XmlReader Create(TextReader input, XmlReaderSettings settings) { return Create(input, settings, string.Empty); } public static XmlReader Create(TextReader input, XmlReaderSettings settings, String baseUri) { if (settings == null) { settings = new XmlReaderSettings(); } if (AsyncUtil.RedirectWriter) { settings.Async = true; // force async } baseUri = null; return new RedirectSyncCallToAsyncCallXmlReader(XmlReader.Create(input, settings)); } public static XmlReader Create(TextReader input, XmlReaderSettings settings, XmlParserContext inputContext) { if (settings == null) { settings = new XmlReaderSettings(); } if (AsyncUtil.RedirectWriter) { settings.Async = true; // force async } return new RedirectSyncCallToAsyncCallXmlReader(XmlReader.Create(input, settings, inputContext)); } public static XmlReader Create(XmlReader reader, XmlReaderSettings settings) { if (settings == null) { settings = new XmlReaderSettings(); } if (AsyncUtil.RedirectWriter) { settings.Async = true; // force async } return new RedirectSyncCallToAsyncCallXmlReader(XmlReader.Create(reader, settings)); } } public class RedirectSyncCallToAsyncCallXmlWriter : XmlWriter { private XmlWriter _writer = null; // the core writer public XmlWriter CoreWriter { get { return _writer; } set { _writer = value; } } public RedirectSyncCallToAsyncCallXmlWriter(XmlWriter xw) { CoreWriter = xw; } public override void Flush() { if (AsyncUtil.RedirectWriter) { try { CoreWriter.FlushAsync().Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.Flush(); } } public override Task FlushAsync() { return CoreWriter.FlushAsync(); } public override void WriteAttributes(XmlReader reader, bool defattr) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteAttributesAsync(reader, defattr).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteAttributes(reader, defattr); } } public override Task WriteAttributesAsync(XmlReader reader, bool defattr) { return CoreWriter.WriteAttributesAsync(reader, defattr); } public new void WriteAttributeString(string prefix, string localName, string ns, string value) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteAttributeStringAsync(prefix, localName, ns, value).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteAttributeString(prefix, localName, ns, value); } } public new Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value) { return CoreWriter.WriteAttributeStringAsync(prefix, localName, ns, value); } public override void WriteBase64(byte[] buffer, int index, int count) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteBase64Async(buffer, index, count).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteBase64(buffer, index, count); } } public override Task WriteBase64Async(byte[] buffer, int index, int count) { return CoreWriter.WriteBase64Async(buffer, index, count); } public override void WriteBinHex(byte[] buffer, int index, int count) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteBinHexAsync(buffer, index, count).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteBinHex(buffer, index, count); } } public override Task WriteBinHexAsync(byte[] buffer, int index, int count) { return CoreWriter.WriteBinHexAsync(buffer, index, count); } public override void WriteCData(string text) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteCDataAsync(text).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteCData(text); } } public override Task WriteCDataAsync(string text) { return CoreWriter.WriteCDataAsync(text); } public override void WriteCharEntity(char ch) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteCharEntityAsync(ch).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteCharEntity(ch); } } public override Task WriteCharEntityAsync(char ch) { return CoreWriter.WriteCharEntityAsync(ch); } public override void WriteChars(char[] buffer, int index, int count) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteCharsAsync(buffer, index, count).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteChars(buffer, index, count); } } public override Task WriteCharsAsync(char[] buffer, int index, int count) { return CoreWriter.WriteCharsAsync(buffer, index, count); } public override void WriteComment(string text) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteCommentAsync(text).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteComment(text); } } public override Task WriteCommentAsync(string text) { return CoreWriter.WriteCommentAsync(text); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteDocTypeAsync(name, pubid, sysid, subset).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteDocType(name, pubid, sysid, subset); } } public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { return CoreWriter.WriteDocTypeAsync(name, pubid, sysid, subset); } public new void WriteElementString(string prefix, String localName, String ns, String value) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteElementStringAsync(prefix, localName, ns, value).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteElementString(prefix, localName, ns, value); } } public new Task WriteElementStringAsync(string prefix, String localName, String ns, String value) { return CoreWriter.WriteElementStringAsync(prefix, localName, ns, value); } public override void WriteEndDocument() { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteEndDocumentAsync().Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteEndDocument(); } } public override Task WriteEndDocumentAsync() { return CoreWriter.WriteEndDocumentAsync(); } public override void WriteEndElement() { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteEndElementAsync().Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteEndElement(); } } public override Task WriteEndElementAsync() { return CoreWriter.WriteEndElementAsync(); } public override void WriteEntityRef(string name) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteEntityRefAsync(name).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteEntityRef(name); } } public override Task WriteEntityRefAsync(string name) { return CoreWriter.WriteEntityRefAsync(name); } public override void WriteFullEndElement() { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteFullEndElementAsync().Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteFullEndElement(); } } public override Task WriteFullEndElementAsync() { return CoreWriter.WriteFullEndElementAsync(); } public override void WriteName(string name) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteNameAsync(name).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteName(name); } } public override Task WriteNameAsync(string name) { return CoreWriter.WriteNameAsync(name); } public override void WriteNmToken(string name) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteNmTokenAsync(name).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteNmToken(name); } } public override Task WriteNmTokenAsync(string name) { return CoreWriter.WriteNmTokenAsync(name); } public override void WriteNode(XmlReader reader, bool defattr) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteNodeAsync(reader, defattr).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteNode(reader, defattr); } } public override Task WriteNodeAsync(XmlReader reader, bool defattr) { return CoreWriter.WriteNodeAsync(reader, defattr); } public override void WriteProcessingInstruction(string name, string text) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteProcessingInstructionAsync(name, text).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteProcessingInstruction(name, text); } } public override Task WriteProcessingInstructionAsync(string name, string text) { return CoreWriter.WriteProcessingInstructionAsync(name, text); } public override void WriteQualifiedName(string localName, string ns) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteQualifiedNameAsync(localName, ns).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteQualifiedName(localName, ns); } } public override Task WriteQualifiedNameAsync(string localName, string ns) { return CoreWriter.WriteQualifiedNameAsync(localName, ns); } public override void WriteRaw(char[] buffer, int index, int count) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteRawAsync(buffer, index, count).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteRaw(buffer, index, count); } } public override Task WriteRawAsync(char[] buffer, int index, int count) { return CoreWriter.WriteRawAsync(buffer, index, count); } public override void WriteRaw(string data) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteRawAsync(data).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteRaw(data); } } public override Task WriteRawAsync(string data) { return CoreWriter.WriteRawAsync(data); } public override void WriteStartDocument() { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteStartDocumentAsync().Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteStartDocument(); } } public override Task WriteStartDocumentAsync() { return CoreWriter.WriteStartDocumentAsync(); } public override void WriteStartDocument(bool standalone) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteStartDocumentAsync(standalone).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteStartDocument(standalone); } } public override Task WriteStartDocumentAsync(bool standalone) { return CoreWriter.WriteStartDocumentAsync(standalone); } public override void WriteStartElement(string prefix, string localName, string ns) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteStartElementAsync(prefix, localName, ns).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteStartElement(prefix, localName, ns); } } public override Task WriteStartElementAsync(string prefix, string localName, string ns) { return CoreWriter.WriteStartElementAsync(prefix, localName, ns); } public override void WriteString(string text) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteStringAsync(text).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteString(text); } } public override Task WriteStringAsync(string text) { return CoreWriter.WriteStringAsync(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteSurrogateCharEntityAsync(lowChar, highChar).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteSurrogateCharEntity(lowChar, highChar); } } public override Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { return CoreWriter.WriteSurrogateCharEntityAsync(lowChar, highChar); } public override void WriteWhitespace(string ws) { if (AsyncUtil.RedirectWriter) { try { CoreWriter.WriteWhitespaceAsync(ws).Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } else { CoreWriter.WriteWhitespace(ws); } } public override Task WriteWhitespaceAsync(string ws) { return CoreWriter.WriteWhitespaceAsync(ws); } /// <summary> /// //////////////////////////////// /// </summary> #region public methods without async version public override XmlWriterSettings Settings { get { return CoreWriter.Settings; } } public override WriteState WriteState { get { return CoreWriter.WriteState; } } public override string LookupPrefix(string ns) { return CoreWriter.LookupPrefix(ns); } public override XmlSpace XmlSpace { get { return CoreWriter.XmlSpace; } } public override string XmlLang { get { return CoreWriter.XmlLang; } } public new void Dispose() { CoreWriter.Dispose(); } public new void WriteStartElement(string localName, string ns) { CoreWriter.WriteStartElement(localName, ns); } public new void WriteStartElement(string localName) { CoreWriter.WriteStartElement(localName); } public new void WriteAttributeString(string localName, string ns, string value) { CoreWriter.WriteAttributeString(localName, ns, value); } public new void WriteAttributeString(string localName, string value) { CoreWriter.WriteAttributeString(localName, value); } public override void WriteStartAttribute(string prefix, string localName, string ns) { CoreWriter.WriteStartAttribute(prefix, localName, ns); } public new void WriteStartAttribute(string localName) { CoreWriter.WriteStartAttribute(localName); } public override void WriteEndAttribute() { CoreWriter.WriteEndAttribute(); } public override void WriteValue(object value) { CoreWriter.WriteValue(value); } public override void WriteValue(string value) { CoreWriter.WriteValue(value); } public override void WriteValue(bool value) { CoreWriter.WriteValue(value); } public override void WriteValue(DateTimeOffset value) { CoreWriter.WriteValue(value); } public override void WriteValue(double value) { CoreWriter.WriteValue(value); } public override void WriteValue(float value) { CoreWriter.WriteValue(value); } public override void WriteValue(decimal value) { CoreWriter.WriteValue(value); } public override void WriteValue(int value) { CoreWriter.WriteValue(value); } public override void WriteValue(long value) { CoreWriter.WriteValue(value); } public new void WriteElementString(string localName, String value) { CoreWriter.WriteElementString(localName, value); } public new void WriteElementString(string localName, String ns, String value) { CoreWriter.WriteElementString(localName, ns, value); } #endregion } public class XmlWriterAsync { public static XmlWriter Create(string outputFileName) { return Create(outputFileName, null); } public static XmlWriter Create(string outputFileName, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } if (AsyncUtil.RedirectWriter) { settings.Async = true; } return null; } public static XmlWriter Create(Stream output) { return Create(output, null); } public static XmlWriter Create(Stream output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } if (AsyncUtil.RedirectWriter) { settings.Async = true; } return new RedirectSyncCallToAsyncCallXmlWriter(XmlWriter.Create(output, settings)); } public static XmlWriter Create(TextWriter output) { return Create(output, null); } public static XmlWriter Create(TextWriter output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } if (AsyncUtil.RedirectWriter) { settings.Async = true; } return new RedirectSyncCallToAsyncCallXmlWriter(XmlWriter.Create(output, settings)); } public static XmlWriter Create(StringBuilder output) { return Create(output, null); } public static XmlWriter Create(StringBuilder output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } if (output == null) { throw new ArgumentNullException(nameof(output)); } if (AsyncUtil.RedirectWriter) { settings.Async = true; } return new RedirectSyncCallToAsyncCallXmlWriter(XmlWriter.Create(output, settings)); } public static XmlWriter Create(XmlWriter output) { return Create(output, null); } public static XmlWriter Create(XmlWriter output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } if (AsyncUtil.RedirectWriter) { settings.Async = true; } return new RedirectSyncCallToAsyncCallXmlWriter(XmlWriter.Create(output, settings)); } } }
using System; using System.Collections.Generic; using System.Text; namespace ICSimulator { public enum MemoryRequestType { RD, DAT, WB, } public class MemoryRequest { public Request request; public MemoryRequestType type; public int memoryRequesterID; //summary>LLC node</summary> public ulong timeOfArrival; public bool isMarked; public ulong creationTime; public int m_index; //summary>memory index pertaining to the block address</summary> public int b_index; //summary>bank index pertaining to the block address</summary> public ulong r_index; //summary>row index pertaining to the block address</summary> public int glob_b_index; //summary>global bank index (for central arbiter)</summary> //scheduling related public MemSched sched; //summary>the memory scheduler this request is destined to; determined by memory index</summary> public int buf_index; //summary>within the memory scheduler, this request's index in the buffer; saves the effort of searching through entire buffer</summary> //public int bufferSlot; // that is just an optimization that I don't need to search over the buffer anymore! public Simulator.Ready cb; // completion callback public static void mapAddr(ulong block, out int m_index, out int b_index, out ulong r_index, out int glob_b_index) { ulong shift_row; ulong shift_mem; ulong shift_bank; int groupID = (int)(block >> (48 - Config.cache_block)); switch (Config.memory.address_mapping) { case AddressMap.BMR: /** * row-level striping (inter-mem): default * RMS (BMR; really original) */ shift_row = block >> Config.memory.row_bit; m_index = (int)((shift_row ^ (ulong)groupID) % (ulong)Config.memory.mem_max); //Console.WriteLine("Common/Request.cs : m_index:{0}, groupID:{1}, mem_max:{2}", m_index, groupID, Config.memory.mem_max); shift_mem = (ulong)(shift_row >> Config.memory.mem_bit); b_index = (int)((shift_mem ^ (ulong)groupID) % (ulong)Config.memory.bank_max_per_mem); r_index = (ulong)(shift_mem >> Config.memory.bank_bit); break; case AddressMap.BRM: /** * block-level striping (inter-mem) * BMS (BRM; original) */ m_index = (int)(block % (ulong)Config.memory.mem_max); shift_mem = block >> Config.memory.mem_bit; shift_row = shift_mem >> Config.memory.row_bit; b_index = (int)(shift_row % (ulong)Config.memory.bank_max_per_mem); r_index = (ulong)(shift_row >> Config.memory.bank_bit); break; case AddressMap.MBR: /** * row-level striping (inter-bank) * RBS (MBR; new) */ shift_row = block >> Config.memory.row_bit; b_index = (int)(shift_row % (ulong)Config.memory.bank_max_per_mem); shift_bank = (ulong)(shift_row >> Config.memory.bank_bit); m_index = (int)(shift_bank % (ulong)Config.memory.mem_max); r_index = (ulong)(shift_bank >> Config.memory.mem_bit); break; case AddressMap.MRB: /** * block-level striping (inter-bank) * BBS */ //Console.WriteLine(block.ToString("x")); b_index = (int)(block % (ulong)Config.memory.bank_max_per_mem); shift_bank = block >> Config.memory.bank_bit; shift_row = shift_bank >> Config.memory.row_bit; m_index = (int)(shift_row % (ulong)Config.memory.mem_max); r_index = shift_row >> Config.memory.mem_bit; //Console.WriteLine("bmpm:{0} bb:{1} b:{2} m:{3} r:{4}", Config.memory.bank_max_per_mem, Config.memory.bank_bit, b_index.ToString("x"), m_index.ToString("x"), r_index.ToString("x")); break; default: throw new Exception("Unknown address map!"); } //central arbiter related if (Config.memory.is_shared_MC) { glob_b_index = m_index * Config.memory.bank_max_per_mem + b_index; } else { glob_b_index = b_index; } } public static int mapMC(ulong block) { int m, b, glob_b; ulong r; mapAddr(block, out m, out b, out r, out glob_b); return m; } public MemoryRequest(Request req, Simulator.Ready cb) { this.cb = cb; request = req; req.beenToMemory = true; mapAddr(req.blockAddress, out m_index, out b_index, out r_index, out glob_b_index); //scheduling related //sched = Config.memory.mem[m_index].sched; sched = null; isMarked = false; } } public class Request { /// <summary> Reasons for a request to be delayed, such as addr packet transmission, data packet injection, memory queueing, etc. </summary> public enum DelaySources { //TODO: this (with coherency awareness) UNKNOWN, COHERENCE, MEMORY, LACK_OF_MSHRS, ADDR_PACKET, DATA_PACKET, MC_ADDR_PACKET, MC_DATA_PACKET, INJ_ADDR_PACKET, INJ_DATA_PACKET, INJ_MC_ADDR_PACKET, INJ_MC_DATA_PACKET } public bool write { get { return _write; } } private bool _write; public ulong blockAddress { get { return _address >> Config.cache_block; } } public ulong address { get { return _address; } } private ulong _address; public int requesterID { get { return _requesterID; } } private int _requesterID; public ulong creationTime { get { return _creationTime; } } private ulong _creationTime; public int mshr; /// <summary> Packet/MemoryRequest/CoherentDir.Entry on the critical path of the serving of this request. </summary> // e.g. the address packet, then data pack on the way back // or addr, mc_addr, mc_request, mc_data and then data // or upgrade(to dir), release(to owner), release_data(to dir), data_exclusive(to requestor) //object _carrier; public void setCarrier(object carrier) { // _carrier = carrier; } // Statistics gathering /// <summary> Records cycles spent in each portion of its path (see Request.TimeSources) </summary> //private ulong[] cyclesPerLocation; /// <summary> Record number of stalls caused by this request while it's the oldest in the inst window </summary> public double backStallsCaused; public Request(int requesterID, ulong address, bool write) { this._requesterID = requesterID; this._address = address; this._write = write; this._creationTime = Simulator.CurrentRound; } public override string ToString() { return String.Format("Request: address {0:X} (block {1:X}), write {2}, requestor {3}", _address, blockAddress, _write, _requesterID); } private ulong _serviceCycle = ulong.MaxValue; public void service() { if (_serviceCycle != ulong.MaxValue) throw new Exception("Retired request serviced twice!"); _serviceCycle = Simulator.CurrentRound; } public bool beenToNetwork = false; public bool beenToMemory = false; public void retire() { if (_serviceCycle == ulong.MaxValue) throw new Exception("Retired request never serviced!"); ulong slack = Simulator.CurrentRound - _serviceCycle; Simulator.stats.all_slack_persrc[requesterID].Add(slack); Simulator.stats.all_slack.Add(slack); Simulator.stats.all_stall_persrc[requesterID].Add(backStallsCaused); Simulator.stats.all_stall.Add(backStallsCaused); if (beenToNetwork) { Simulator.stats.net_slack_persrc[requesterID].Add(slack); Simulator.stats.net_slack.Add(slack); Simulator.stats.net_stall_persrc[requesterID].Add(backStallsCaused); Simulator.stats.net_stall.Add(backStallsCaused); } if (beenToMemory) { Simulator.stats.mem_slack_persrc[requesterID].Add(slack); Simulator.stats.mem_slack.Add(slack); Simulator.stats.mem_stall_persrc[requesterID].Add(backStallsCaused); Simulator.stats.mem_stall.Add(backStallsCaused); } if (beenToNetwork) { Simulator.stats.req_rtt.Add(_serviceCycle - _creationTime); } } } //For reference: public enum OldInstructionType { Read, Write }; public class OldRequest { public ulong blockAddress; public ulong timeOfArrival; public int threadID; public bool isMarked; public OldInstructionType type; public ulong associatedAddressPacketInjectionTime; public ulong associatedAddressPacketCreationTime; public Packet carrier; // this is the packet which is currently moving the request through the system //members copied from Req class of FairMemSim for use in MCs public int m_index; ///<memory index pertaining to the block address public int b_index; ///<bank index pertaining to the block address public ulong r_index; ///<row index pertaining to the block address public int glob_b_index; ///<global bank index (for central arbiter) //scheduling related public MemSched sched; ///<the memory scheduler this request is destined to; determined by memory index public int buf_index; ///<within the memory scheduler, this request's index in the buffer; saves the effort of searching through entire buffer public int bufferSlot; // that is just an optimization that I don't need to search over the buffer anymore! private double frontStallsCaused; private double backStallsCaused; private ulong[] locationCycles; // record how many cycles spent in each Request.TimeSources location public OldRequest() { isMarked = false; } public override string ToString() { return "Request: ProcID=" + threadID + " IsMarked=" + isMarked + /*" Bank=" + bankIndex.ToString() + " Row=" + rowIndex.ToString() + */" Block=" + (blockAddress).ToString() + " " + type.ToString(); } public void initialize(ulong blockAddress) { this.blockAddress = blockAddress; frontStallsCaused = 0; backStallsCaused = 0; locationCycles = new ulong[Enum.GetValues(typeof(Request.DelaySources)).Length]; if (Config.PerfectLastLevelCache) return; ulong shift_row; ulong shift_mem; ulong shift_bank; switch (Config.memory.address_mapping) { case AddressMap.BMR: /** * row-level striping (inter-mem): default * RMS (BMR; really original) */ shift_row = blockAddress >> Config.memory.row_bit; m_index = (int)(shift_row % (ulong)Config.memory.mem_max); shift_mem = (ulong)(shift_row >> Config.memory.mem_bit); b_index = (int)(shift_mem % (ulong)Config.memory.bank_max_per_mem); r_index = (ulong)(shift_mem >> Config.memory.bank_bit); break; case AddressMap.BRM: /** * block-level striping (inter-mem) * BMS (BRM; original) */ m_index = (int)(blockAddress % (ulong)Config.memory.mem_max); shift_mem = blockAddress >> Config.memory.mem_bit; shift_row = shift_mem >> Config.memory.row_bit; b_index = (int)(shift_row % (ulong)Config.memory.bank_max_per_mem); r_index = (ulong)(shift_row >> Config.memory.bank_bit); break; case AddressMap.MBR: /** * row-level striping (inter-bank) * RBS (MBR; new) */ shift_row = blockAddress >> Config.memory.row_bit; b_index = (int)(shift_row % (ulong)Config.memory.bank_max_per_mem); shift_bank = (ulong)(shift_row >> Config.memory.bank_bit); m_index = (int)(shift_bank % (ulong)Config.memory.mem_max); r_index = (ulong)(shift_bank >> Config.memory.mem_bit); break; case AddressMap.MRB: /** * block-level striping (inter-bank) * BBS */ //Console.WriteLine(blockAddress.ToString("x")); b_index = (int)(blockAddress % (ulong)Config.memory.bank_max_per_mem); shift_bank = blockAddress >> Config.memory.bank_bit; shift_row = shift_bank >> Config.memory.row_bit; m_index = (int)(shift_row % (ulong)Config.memory.mem_max); r_index = shift_row >> Config.memory.mem_bit; //Console.WriteLine("bmpm:{0} bb:{1} b:{2} m:{3} r:{4}", Config.memory.bank_max_per_mem, Config.memory.bank_bit, b_index.ToString("x"), m_index.ToString("x"), r_index.ToString("x")); break; default: throw new Exception("Unknown address map!"); } //scheduling related //sched = Config.memory.mem[m_index].sched; sched = null; isMarked = false; glob_b_index = b_index; } public void blameFrontStall(double weight) { frontStallsCaused += weight; } public void blameBackStall(double weight) { backStallsCaused += weight; } /* public void blameCycle() { Request.DelaySources staller = Request.DelaySources.UNKNOWN; if (carrier.GetType() == typeof(MemoryRequest)) staller = Request.DelaySources.MEMORY; else if (carrier.GetType() == typeof(Packet)) { bool injected = ((Packet)carrier).injectionTime != ulong.MaxValue; if (carrier.GetType() == typeof(CachePacket)) { CachePacket carrierPacket = (CachePacket)carrier; switch (carrierPacket.type) { case CachePacketType.RD: staller = injected ? Request.DelaySources.ADDR_PACKET : Request.DelaySources.INJ_ADDR_PACKET; break; case CachePacketType.DAT_EX: case CachePacketType.DAT_SHR: staller = injected ? Request.DelaySources.DATA_PACKET : Request.DelaySources.INJ_DATA_PACKET; break; default: throw new Exception("Unsupported packet type carrying request"); } } else if (carrier.GetType() == typeof(MemoryPacket)) { MemoryPacket carrierPacket = (MemoryPacket)carrier; switch (carrierPacket.type) { case MemoryRequestType.RD: if (m_index == int.MaxValue) { staller = Request.DelaySources.MEMORY; break; } staller = injected ? Request.DelaySources.MC_ADDR_PACKET : Request.DelaySources.INJ_MC_ADDR_PACKET; break; case MemoryRequestType.DAT: staller = injected ? Request.DelaySources.MC_DATA_PACKET : Request.DelaySources.INJ_MC_DATA_PACKET; break; default: throw new Exception("Unsupported packet type carrying request"); } } else { //unknown! staller = Request.DelaySources.UNKNOWN; } locationCycles[(int)staller]++; } } */ public void storeStats() { double sum = 0; foreach (double d in locationCycles) sum += d; for (int i = 0; i < locationCycles.Length; i++) { //Simulator.stats.front_stalls_persrc[threadID].Add(i, frontStallsCaused * locationCycles[i] / sum); //Simulator.stats.back_stalls_persrc[threadID].Add(i, backStallsCaused * locationCycles[i] / sum); } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; using DotSpatial.Data; using DotSpatial.Data.Forms; using DotSpatial.Symbology; using DotSpatial.Symbology.Forms; namespace DotSpatial.Controls { /// <summary> /// The legend is used to show a list of all the layers inside of Map. It describes the different categories of each layer with the help of a symbol and the categories legend text. /// </summary> [ToolboxItem(true)] public class Legend : ScrollingControl, ILegend { #region Fields private readonly ContextMenu _contextMenu; private readonly TextBox _editBox; private readonly Icon _icoChecked; private readonly Icon _icoUnchecked; private readonly HashSet<ILegendItem> _selection; private LegendBox _dragItem; private LegendBox _dragTarget; private IColorCategory _editCategory; private Pen _highlightBorderPen; private bool _ignoreHide; private bool _isDragging; private bool _isMouseDown; private List<LegendBox> _legendBoxes; // for hit-testing private Rectangle _previousLine; private LegendBox _previousMouseDown; private Brush _selectionFontBrush; private Color _selectionFontColor; private Color _selectionHighlight; private TabColorDialog _tabColorDialog; private bool _wasDoubleClick; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Legend"/> class. /// </summary> public Legend() { RootNodes = new List<ILegendItem>(); _icoChecked = Images.Checked; _icoUnchecked = Images.Unchecked; _contextMenu = new ContextMenu(); _selection = new HashSet<ILegendItem>(); _editBox = new TextBox { Parent = this, Visible = false }; _editBox.LostFocus += EditBoxLostFocus; Indentation = 30; _legendBoxes = new List<LegendBox>(); BackColor = Color.White; SelectionFontColor = Color.Black; SelectionHighlight = Color.FromArgb(215, 238, 252); // Adding a legend ensures that symbology dialogs will be properly launched. // Otherwise, an ordinary map may not even need them. SharedEventHandlers = new SymbologyEventManager { Owner = FindForm() }; } #endregion #region Events /// <summary> /// Occurs when a mouse up is initiated within a checkbox. /// </summary> public event EventHandler<ItemMouseEventArgs> CheckBoxMouseUp; /// <summary> /// Occurs when a mouse down is initiated within an expand box. /// </summary> public event EventHandler<ItemMouseEventArgs> ExpandBoxMouseDown; /// <summary> /// Occurs when a mousedown is initiated within an existing legend item /// </summary> public event EventHandler<ItemMouseEventArgs> ItemMouseDown; /// <summary> /// Occurs when the mouse is moving over an item. /// </summary> public event EventHandler<ItemMouseEventArgs> ItemMouseMove; /// <summary> /// Occurs when a mouse up occurs insize of a specific item. /// </summary> public event EventHandler<ItemMouseEventArgs> ItemMouseUp; /// <summary> /// Occurs when the drag method is used to alter the order of layers or /// groups in the legend. /// </summary> public event EventHandler OrderChanged; #endregion #region Properties /// <summary> /// Gets or sets an integer representing how far child nodes are indented when compared to the parent nodes. /// </summary> [Category("Appearance")] [Description("Gets or sets the indentation in pixels between a parent item and its children.")] public int Indentation { get; set; } /// <summary> /// Gets a height for each item based on the height of the font. /// </summary> [Category("Appearance")] [Description("Gets the height (which depends on the font) for each item.")] public int ItemHeight { get { if (Font.Height < 20) return 20; return Font.Height + 4; } } /// <summary> /// Gets or sets the progress handler for any progress messages like re-drawing images for rasters /// </summary> [Category("Controls")] [Description("Gets or sets the progress handler for any progress messages like re-drawing images for rasters")] public IProgressHandler ProgressHandler { get; set; } /// <summary> /// Gets or sets the list of map frames being displayed by this legend. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public List<ILegendItem> RootNodes { get; set; } /// <summary> /// Gets or sets the selection font color /// </summary> [Category("Appearance")] [Description("Specifies the color of the font in selected legend items.")] public Color SelectionFontColor { get { return _selectionFontColor; } set { _selectionFontColor = value; _selectionFontBrush?.Dispose(); _selectionFontBrush = new SolidBrush(_selectionFontColor); IsInitialized = false; } } /// <summary> /// Gets or sets the principal color that a selected text box is highlighted with. /// </summary> [Category("Appearance")] [Description("Specifies the color that a selected text box is highlighted with.")] public Color SelectionHighlight { get { return _selectionHighlight; } set { _selectionHighlight = value; _highlightBorderPen?.Dispose(); float med = _selectionHighlight.GetBrightness(); float border = med - .25f; if (border < 0f) border = 0f; _highlightBorderPen = new Pen(SymbologyGlobal.ColorFromHsl(_selectionHighlight.GetHue(), _selectionHighlight.GetSaturation(), border)); } } /// <summary> /// Gets or sets the SharedEventHandler that is used for working with shared layer events. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public SymbologyEventManager SharedEventHandlers { get; set; } /// <summary> /// Gets or sets a value indicating whether the legend is used to determine whether a layer is selectable. /// If true, a layer is only selectable if it or a superior object (parental group, mapframe) is selected in legend. /// If false, the selectable state of the layers gets either determined by a plugin like SetSelectable or developers handle the selectable state by code. /// By default legend is used, but if the SetSelectable plugin gets loaded this is used instead of the legend. /// </summary> public bool UseLegendForSelection { get; set; } = false; /// <summary> /// Gets the bottom box in the legend. /// </summary> private LegendBox BottomBox => _legendBoxes[_legendBoxes.Count - 1]; #endregion #region Methods // CGX public HashSet<ILegendItem> getSelection() { return _selection; } // FIN CGX /// <summary> /// Adds a map frame as a root node, and links an event handler to update /// when the mapframe triggers an ItemChanged event. /// </summary> /// <param name="mapFrame">The map frame that gets added.</param> public void AddMapFrame(IFrame mapFrame) { mapFrame.IsSelected = true; if (!RootNodes.Contains(mapFrame)) { OnIncludeMapFrame(mapFrame); } RootNodes.Add(mapFrame); RefreshNodes(); } /// <summary> /// Un-selects any selected items in the legend. /// </summary> public void ClearSelection() { var list = _selection.ToList(); IFrame parentMap = null; if (list.Count > 0) { parentMap = list[0].ParentMapFrame(); parentMap?.SuspendEvents(); } foreach (var lb in list) { lb.IsSelected = false; } _selection.Clear(); parentMap?.ResumeEvents(); RefreshNodes(); } /// <summary> /// Given the current list of Maps or 3DMaps, it rebuilds the treeview nodes. /// </summary> public void RefreshNodes() { // do any code that needs to happen if content changes _previousMouseDown = null; // to avoid memory leaks, because LegendBox contains reference to Layer IsInitialized = false; Invalidate(); } /// <summary> /// Removes the specified map frame if it is a root node. /// </summary> /// <param name="mapFrame">Map frame that gets removed.</param> /// <param name="preventRefresh">Boolean, if true, removing the map frame will not automatically force a refresh of the legend.</param> public void RemoveMapFrame(IFrame mapFrame, bool preventRefresh) { RootNodes.Remove(mapFrame); if (!RootNodes.Contains(mapFrame)) OnExcludeMapFrame(mapFrame); if (preventRefresh) return; RefreshNodes(); } /// <summary> /// Overrides the drawing method to account for drawing lines when an item is being dragged to a new position. /// </summary> /// <param name="e">A PaintEventArgs</param> protected override void OnDraw(PaintEventArgs e) { base.OnDraw(e); using (var pen = new Pen(BackColor)) { e.Graphics.DrawRectangle(pen, e.ClipRectangle); } if (_isDragging && !_previousLine.IsEmpty) { e.Graphics.DrawLine(Pens.Black, _previousLine.X, _previousLine.Y + 2, _previousLine.Right, _previousLine.Y + 2); } } /// <summary> /// Occurs when we need to no longer listen to the map frame events. /// </summary> /// <param name="mapFrame">Map frame that gets excluded.</param> protected virtual void OnExcludeMapFrame(IFrame mapFrame) { mapFrame.ItemChanged -= MapFrameItemChanged; mapFrame.LayerSelected -= LayersLayerSelected; mapFrame.LayerRemoved -= MapFrameOnLayerRemoved; } /// <summary> /// Also hides the edit box so that it doesn't seem displaced from the item /// </summary> /// <param name="sender">Sender that raised the event.</param> /// <param name="e">The event args.</param> protected override void OnHorizontalScroll(object sender, ScrollEventArgs e) { HideEditBox(); base.OnHorizontalScroll(sender, e); } /// <summary> /// Occurs when linking the map frame. /// </summary> /// <param name="mapFrame">Map frame that gets included.</param> protected virtual void OnIncludeMapFrame(IFrame mapFrame) { mapFrame.ItemChanged += MapFrameItemChanged; mapFrame.LayerSelected += LayersLayerSelected; mapFrame.LayerRemoved += MapFrameOnLayerRemoved; } /// <summary> /// Extends initialize to draw "non-selected" elements. /// </summary> /// <param name="e">The event args.</param> protected override void OnInitialize(PaintEventArgs e) { // draw standard background image to buffer base.OnInitialize(e); PointF topLeft = new Point(0, 0); if (RootNodes == null || RootNodes.Count == 0) return; _legendBoxes = new List<LegendBox>(); foreach (var item in RootNodes) { var args = new DrawLegendItemArgs(e.Graphics, item, ClientRectangle, topLeft); OnInitializeItem(args); topLeft.Y += SizeItem((int)topLeft.X, item, e.Graphics).Height; } } /// <summary> /// Draws the legend item from the DrawLegendItemArgs with all its child items. /// </summary> /// <param name="e">DrawLegendItemArgs that are needed to draw the legend item.</param> /// <returns>The position where the next LegendItem can be drawn.</returns> protected virtual PointF OnInitializeItem(DrawLegendItemArgs e) { if (!e.Item.LegendItemVisible) return e.TopLeft; UpdateActions(e.Item); PointF topLeft = e.TopLeft; PointF tempTopLeft = topLeft; if (topLeft.Y > ControlRectangle.Bottom) { return topLeft; // drawing would be below the screen } if (topLeft.Y > ControlRectangle.Top - ItemHeight) { // Draw the item itself var itemBox = new LegendBox { Item = e.Item, Bounds = new Rectangle(0, (int)topLeft.Y, Width, ItemHeight), Indent = (int)topLeft.X / Indentation }; _legendBoxes.Add(itemBox); DrawPlusMinus(e.Graphics, ref tempTopLeft, itemBox); int ih = ItemHeight; if (e.Item.LegendSymbolMode == SymbolMode.Symbol) { Size s = e.Item.GetLegendSymbolSize(); if (s.Height > ih) tempTopLeft.Y += 3; } if (e.Item.LegendSymbolMode == SymbolMode.Symbol || e.Item.LegendSymbolMode == SymbolMode.GroupSymbol) { DrawSymbol(e.Graphics, ref tempTopLeft, itemBox); } if (e.Item.LegendSymbolMode == SymbolMode.Checkbox) { DrawCheckBoxes(e.Graphics, ref tempTopLeft, itemBox); } int width = (int)e.Graphics.MeasureString(e.Item.LegendText, Font).Width; int dY = 0; if (e.Item.LegendSymbolMode == SymbolMode.Symbol) { Size s = e.Item.GetLegendSymbolSize(); if (s.Height > ih) dY = (s.Height - ih) / 2; tempTopLeft.Y += dY; } tempTopLeft.Y += (ih - Font.Height) / 2F; itemBox.Textbox = new Rectangle((int)tempTopLeft.X, (int)topLeft.Y + dY, width, ItemHeight); if (itemBox.Item.IsSelected) { _selection.Add(itemBox.Item); Rectangle innerBox = itemBox.Textbox; innerBox.Inflate(-1, -1); using (var b = HighlightBrush(innerBox)) { e.Graphics.FillRectangle(b, innerBox); } SymbologyGlobal.DrawRoundedRectangle(e.Graphics, _highlightBorderPen, itemBox.Textbox); e.Graphics.DrawString(e.Item.LegendText, Font, _selectionFontBrush, tempTopLeft); } else { e.Graphics.DrawString(e.Item.LegendText, Font, Brushes.Black, tempTopLeft); } } int h = ItemHeight; if (e.Item.LegendSymbolMode == SymbolMode.Symbol) { Size s = e.Item.GetLegendSymbolSize(); if (s.Height > h) h = s.Height + 6; } topLeft.Y += h; if (e.Item.IsExpanded) { topLeft.X += Indentation; if (e.Item.LegendItems != null) { List<ILegendItem> items = e.Item.LegendItems.ToList(); if (e.Item is IGroup) items.Reverse(); // reverse layers because of drawing order, don't bother reversing categories. foreach (var item in items) { var args = new DrawLegendItemArgs(e.Graphics, item, e.ClipRectangle, topLeft); topLeft = OnInitializeItem(args); if (topLeft.Y > ControlRectangle.Bottom) break; } } topLeft.X -= Indentation; } return topLeft; } /// <summary> /// The coordinates are in legend coordinates, but a LegendBox is provided to define the /// coordinates of the specified object. /// </summary> /// <param name="e">An ItemMouseEventArgs</param> protected virtual void OnItemMouseDown(ItemMouseEventArgs e) { ItemMouseDown?.Invoke(this, e); } /// <summary> /// Fires the ItemMouseMove Event, which handles the mouse moving over one of the legend items. /// </summary> /// <param name="e">An ItemMouseEventArgs</param> protected virtual void OnItemMouseMove(ItemMouseEventArgs e) { ItemMouseMove?.Invoke(this, e); } /// <summary> /// Checks for checkbox changes and fires the ItemMouseUp event. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnItemMouseUp(ItemMouseEventArgs e) { ItemMouseUp?.Invoke(this, e); } /// <inheritdoc /> protected override void OnMouseDoubleClick(MouseEventArgs e) { _wasDoubleClick = true; Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); foreach (LegendBox lb in _legendBoxes) { if (!lb.Bounds.Contains(loc) || lb.CheckBox.Contains(loc)) continue; ILineCategory lc = lb.Item as ILineCategory; if (lc != null /*CGX*/ && lc.Symbolizer != null) { using (var lsDialog = new DetailedLineSymbolDialog(lc.Symbolizer)) { lsDialog.ShowDialog(); } } IPointCategory pc = lb.Item as IPointCategory; if (pc != null /*CGX*/ && pc.Symbolizer != null) { using (var dlg = new DetailedPointSymbolDialog(pc.Symbolizer)) { dlg.ShowDialog(); } } IPolygonCategory polyCat = lb.Item as IPolygonCategory; if (polyCat != null /*CGX*/ && polyCat.Symbolizer != null) { using (var dlg = new DetailedPolygonSymbolDialog(polyCat.Symbolizer)) { dlg.ShowDialog(); } } IFeatureLayer fl = lb.Item as IFeatureLayer; if (fl != null) { using (var layDialog = new LayerDialog(fl, new FeatureCategoryControl())) { layDialog.ShowDialog(); } } IRasterLayer rl = lb.Item as IRasterLayer; if (rl != null) { using (var dlg = new LayerDialog(rl, new RasterCategoryControl())) { dlg.ShowDialog(); } } IColorCategory cb = lb.Item as IColorCategory; if (cb != null) { _tabColorDialog = new TabColorDialog(); _tabColorDialog.ChangesApplied += TabColorDialogChangesApplied; _tabColorDialog.StartColor = cb.LowColor; _tabColorDialog.EndColor = cb.HighColor; _editCategory = cb; _tabColorDialog.ShowDialog(this); } } base.OnMouseDoubleClick(e); } /// <summary> /// Handles the case where the mouse down occurs. /// </summary> /// <param name="e">A MouseEventArgs</param> protected override void OnMouseDown(MouseEventArgs e) { HideEditBox(); if (_legendBoxes == null || _legendBoxes.Count == 0) return; Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); foreach (LegendBox box in _legendBoxes) { if (box.Bounds.Contains(loc)) { ItemMouseEventArgs args = new ItemMouseEventArgs(e, box); DoItemMouseDown(args); } } base.OnMouseDown(e); } /// <summary> /// Performs the default handling for mouse movememnt, and decides /// whether or not to fire an ItemMouseMove event. /// </summary> /// <param name="e">A MouseEventArgs</param> protected override void OnMouseMove(MouseEventArgs e) { if (_legendBoxes == null) return; bool cursorHandled = false; LegendBox currentBox = null; Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); foreach (LegendBox box in _legendBoxes) { if (box.Bounds.Contains(loc)) { currentBox = box; ItemMouseEventArgs args = new ItemMouseEventArgs(e, box); DoItemMouseMove(args); } } if (_isMouseDown) _isDragging = true; if (_isDragging) { _dragTarget = currentBox; if (_dragTarget == null && ClientRectangle.Contains(e.Location)) { _dragTarget = BottomBox; } if (!_previousLine.IsEmpty) Invalidate(_previousLine); _previousLine = Rectangle.Empty; if (_dragTarget != null && _dragItem != null) { int left = 0; LegendBox container = BoxFromItem(_dragTarget != _dragItem ? _dragTarget.Item.GetValidContainerFor(_dragItem.Item) : _dragItem.Item); bool indenting = false; if (container != null) { // if the mouse x is smaller than the right corner of the expand box, the user is trying to move the layer out of the current group into the parent group // so we indent the line based on the parent group if (loc.X < container.ExpandBox.Right) { var c = BoxFromItem(container.Item.GetParentItem()); if (c != null) container = c; indenting = true; } left = (container.Indent + 1) * Indentation; } LegendBox boxOverLine; if (_dragTarget.Item.CanReceiveItem(_dragItem.Item)) { boxOverLine = _dragTarget; } else if (_dragTarget.Item.LegendType == LegendType.Layer && _dragItem.Item.LegendType == LegendType.Layer) { boxOverLine = BoxFromItem(_dragTarget.Item.BottomMember()); } else { boxOverLine = BoxFromItem(_dragTarget.Item.GetParentItem().BottomMember()); } if (boxOverLine == null || boxOverLine.Item.IsChildOf(_dragItem.Item) || (boxOverLine.Item == _dragItem.Item && !indenting)) { // items may not be moved onto themselves, so we show the forbidden cursor _dragTarget = null; Cursor = Cursors.No; cursorHandled = true; } else { // draw the line on the position the layer would be moved to _dragTarget = boxOverLine; _previousLine = new Rectangle(left - ControlRectangle.X, boxOverLine.Bounds.Bottom - ControlRectangle.Y, Width - left, 4); Cursor = Cursors.Hand; cursorHandled = true; Invalidate(_previousLine); } } else { _isMouseDown = false; } if (!cursorHandled) { Cursor = Cursors.No; cursorHandled = true; } } if (!cursorHandled) { Cursor = Cursors.Arrow; } base.OnMouseMove(e); } /// <summary> /// Checks the Mouse Up event to see if it occurs inside a legend item. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseUp(MouseEventArgs e) { Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); // if it was neither dragged nor double clicked, the item will be renamed if (!_wasDoubleClick && !_isDragging) { foreach (LegendBox box in _legendBoxes) { if (!box.Bounds.Contains(loc)) continue; ItemMouseEventArgs args = new ItemMouseEventArgs(e, box); DoItemMouseUp(args); } } // if the item was dragged it has to be moved to the new position if (_isDragging) { if (_dragItem != null && _dragTarget != null) { ILegendItem potentialParent = null; if (_dragTarget.Item != _dragItem.Item) { potentialParent = _dragTarget.Item.GetValidContainerFor(_dragItem.Item); } if (potentialParent != null /*CGX*/ && potentialParent.ParentMapFrame() != null) { // update the parent, if the user is trying to move the item up the tree var container = BoxFromItem(potentialParent); if (loc.X < container.ExpandBox.Right) { potentialParent = container.Item.GetParentItem(); } // The target must be a group, and the item must be a layer. ILayer lyr = _dragItem.Item as ILayer; IGroup grp = potentialParent as IGroup; if (lyr != null && grp != null) { // when original location is inside group, remove layer from the group. IGroup grp1 = _dragItem.Item.GetParentItem() as IGroup; int newIndex = potentialParent.InsertIndex(_dragTarget.Item) - 1; var oldIndex = grp1?.IndexOf(lyr); // only move the layer if the user doesn't move it to the same position as before if (grp1 != grp || oldIndex != newIndex) { potentialParent.ParentMapFrame().SuspendEvents(); lyr.LockDispose(); grp1?.SuspendEvents(); grp.SuspendEvents(); grp1?.Remove(lyr); var index = potentialParent.InsertIndex(_dragTarget.Item); if (index == -1) index = 0; grp.Insert(index, lyr); grp.ResumeEvents(); grp1?.ResumeEvents(); // when the target is a group, assign the parent item. lyr.SetParentItem(grp); lyr.UnlockDispose(); potentialParent.ParentMapFrame().ResumeEvents(); OnOrderChanged(); potentialParent.ParentMapFrame().Invalidate(); } } } } Cursor = Cursors.Arrow; _isDragging = false; Invalidate(); } _isMouseDown = false; _wasDoubleClick = false; base.OnMouseUp(e); } /// <summary> /// Fires the OrderChanged Event. /// </summary> protected virtual void OnOrderChanged() { OrderChanged?.Invoke(this, EventArgs.Empty); } /// <summary> /// Also hides the edit box so that it doesn't seme displaced from the item. /// </summary> /// <param name="sender">Sender that raised the event.</param> /// <param name="e">The event args.</param> protected override void OnVerticalScroll(object sender, ScrollEventArgs e) { HideEditBox(); base.OnVerticalScroll(sender, e); } /// <summary> /// Recursive add method to handle nesting of menu items. /// </summary> /// <param name="parent">The parent</param> /// <param name="mi">The menu item.</param> private static void AddMenuItem(Menu.MenuItemCollection parent, SymbologyMenuItem mi) { MenuItem m; if (mi.Icon != null) { m = new IconMenuItem(mi.Name, mi.Icon, mi.ClickHandler); } else if (mi.Image != null) { m = new IconMenuItem(mi.Name, mi.Image, mi.ClickHandler); } else { m = new IconMenuItem(mi.Name, mi.ClickHandler); } parent.Add(m); foreach (SymbologyMenuItem child in mi.MenuItems) { AddMenuItem(m.MenuItems, child); } } /// <summary> /// Sets SelectionEnabled true for all the children of the given collection. /// </summary> /// <param name="layers">Collection whose items SelectionEnabled state should be set to true.</param> private static void SetSelectionEnabledForChildren(IMapLayerCollection layers) { foreach (var mapLayer in layers) { mapLayer.SelectionEnabled = true; mapLayer.IsSelected = false; // the selection comes from higher up, so the layers gets deselected, so the user doesn't assume that only the selected items in the group are used for selection var gr = mapLayer as IMapGroup; if (gr != null) { SetSelectionEnabledForChildren(gr.Layers); } else { IFeatureLayer fl = mapLayer as IFeatureLayer; if (fl != null) { // all categories get selection enabled foreach (var cat in fl.Symbology.GetCategories()) { cat.SelectionEnabled = true; cat.IsSelected = false; // the selection comes from higher up, so the category gets deselected, so the user doesn't assume that only the selected categories of the layer get used for selection } } } } } /// <summary> /// Updates the SelectionEnabled property of all the layers in the given collection. /// </summary> /// <param name="layers">The collection that gets updated.</param> private static void UpdateSelectionEnabled(IEnumerable<object> layers) { foreach (var mapLayer in layers.OfType<ILayer>()) { mapLayer.SelectionEnabled = mapLayer.IsSelected; // enable selection if the current item is selected var gr = mapLayer as IMapGroup; if (gr != null) { // this is a group if (gr.IsSelected) { SetSelectionEnabledForChildren(gr.Layers); // group is the selected item, so everything below is selected } else { UpdateSelectionEnabled(gr.Layers); // group is not the selected item, so find the selected item } } else { IFeatureLayer fl = mapLayer as IFeatureLayer; if (fl != null) { var cats = fl.Symbology.GetCategories().ToList(); // this is a layer with categories if (mapLayer.IsSelected) { // all categories get selection enabled foreach (var cat in cats) { cat.SelectionEnabled = true; cat.IsSelected = false; // layer is selected, so the category gets deselected, so the user doesn't assume that only the selected categories of the layer get used for selection } } else { // only selected categories get selection enabled foreach (var cat in cats) { cat.SelectionEnabled = cat.IsSelected; } mapLayer.SelectionEnabled = cats.Any(_ => _.SelectionEnabled); } } } } } /// <summary> /// Given a legend item, it searches the list of LegendBoxes until it finds it. /// </summary> /// <param name="item">LegendItem to find.</param> /// <returns>LegendBox belonging to the item.</returns> private LegendBox BoxFromItem(ILegendItem item) { return _legendBoxes.FirstOrDefault(box => box.Item == item); } private void DoItemMouseDown(ItemMouseEventArgs e) { Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); // Toggle expansion if (e.ItemBox.ExpandBox.Contains(loc)) { e.ItemBox.Item.IsExpanded = !e.ItemBox.Item.IsExpanded; ExpandBoxMouseDown?.Invoke(this, e); ResetLegend(); return; } // if the item was already selected if (e.ItemBox.Item.IsSelected) { // and the left mouse button is clicked while the shift key is held, we deselect the item if (ModifierKeys == Keys.Control && e.Button == MouseButtons.Left) { e.ItemBox.Item.IsSelected = false; return; } // Start dragging if (e.Button == MouseButtons.Left) { var box = e.ItemBox; // otherwise we prepare to edit in textbox if (_previousMouseDown == null) { ClearSelection(); box = _legendBoxes.Find(_ => _.Item == e.ItemBox.Item); box.Item.IsSelected = true; _previousMouseDown = box; } _isMouseDown = true; ILegendItem li = box.Item; ILayer lyr = li as ILayer; if (lyr == null) { // this is a category, it may be renamed but not moved } else if (RootNodes.Contains(lyr)) { // this is a root node, it may not be renamed or moved _isMouseDown = false; } else { // this is a layer, it may be moved and renamed _dragItem = BoxFromItem(lyr); } } } else { // Check for textbox clicking if (e.ItemBox.Textbox.Contains(loc)) { if (ModifierKeys != Keys.Control) { ClearSelection(); } e.ItemBox.Item.IsSelected = true; if (UseLegendForSelection) { UpdateSelectionEnabled(RootNodes.OfType<IMapFrame>().AsEnumerable()); } } } } private void DoItemMouseMove(ItemMouseEventArgs e) { OnItemMouseMove(e); } private void DoItemMouseUp(ItemMouseEventArgs e) { Point loc = new Point(e.X + ControlRectangle.X, e.Location.Y + ControlRectangle.Top); if (e.Button == MouseButtons.Left) { if (e.ItemBox.Item.LegendSymbolMode == SymbolMode.Checkbox && e.ItemBox.CheckBox.Contains(loc)) { IRenderableLegendItem rendItem = e.ItemBox.Item as IRenderableLegendItem; if (rendItem != null) { // force a re-draw in the case where we are talking about layers. rendItem.IsVisible = !rendItem.IsVisible; } else { e.ItemBox.Item.Checked = !e.ItemBox.Item.Checked; } CheckBoxMouseUp?.Invoke(this, e); RefreshNodes(); } // left click on a text box makes the textbox editable, if it was clicked before if (e.ItemBox.Textbox.Contains(loc)) { if (e.ItemBox.Item == _previousMouseDown?.Item) { if (!e.ItemBox.Item.LegendTextReadOnly) { // Edit via text box _editBox.Left = e.ItemBox.Textbox.Left; _editBox.Width = e.ItemBox.Textbox.Width + 10; _editBox.Top = e.ItemBox.Bounds.Top; _editBox.Height = e.ItemBox.Bounds.Height; _editBox.SelectedText = e.ItemBox.Item.LegendText; _editBox.Font = Font; _editBox.Visible = true; } } else if (ModifierKeys == Keys.Control) { RefreshNodes(); } } } else if (e.Button == MouseButtons.Right) { // right click shows the context menu if (e.ItemBox.Item.ContextMenuItems == null) return; _contextMenu.MenuItems.Clear(); foreach (SymbologyMenuItem mi in e.ItemBox.Item.ContextMenuItems) { AddMenuItem(_contextMenu.MenuItems, mi); } _contextMenu.Show(this, e.Location); _contextMenu.MenuItems.Clear(); } } /// <summary> /// If the LegendBox contains a checkbox item draw the checkbox for an item. /// </summary> /// <param name="g">Graphics object used for drawing.</param> /// <param name="topLeft">TopLeft position where the symbol should be drawn.</param> /// <param name="itemBox">LegendBox of the item, the checkbox should be added to.</param> private void DrawCheckBoxes(Graphics g, ref PointF topLeft, LegendBox itemBox) { ILegendItem item = itemBox.Item; if (item?.LegendSymbolMode != SymbolMode.Checkbox) return; if (item.Checked) { int top = (int)topLeft.Y + ((ItemHeight - _icoChecked.Height) / 2); int left = (int)topLeft.X + 6; g.DrawIcon(_icoChecked, left, top); Rectangle box = new Rectangle(left, top, _icoChecked.Width, _icoChecked.Height); itemBox.CheckBox = box; } else { int top = (int)topLeft.Y + ((ItemHeight - _icoUnchecked.Height) / 2); int left = (int)topLeft.X + 6; g.DrawIcon(_icoUnchecked, left, top); Rectangle box = new Rectangle(left, top, _icoChecked.Width, _icoChecked.Height); itemBox.CheckBox = box; } topLeft.X += 22; } /// <summary> /// If the LegendBox doesn't contain a symbol draw the plus or minus visible for controlling expansion. /// </summary> /// <param name="g">Graphics object used for drawing.</param> /// <param name="topLeft">TopLeft position where the symbol should be drawn.</param> /// <param name="itemBox">LegendBox of the item, the +/- should be added to.</param> private void DrawPlusMinus(Graphics g, ref PointF topLeft, LegendBox itemBox) { ILegendItem item = itemBox.Item; if (item == null) return; if (item.LegendSymbolMode == SymbolMode.Symbol) return; // don't allow symbols to expand Point tl = new Point((int)topLeft.X, (int)topLeft.Y); tl.Y += (ItemHeight - 8) / 2; tl.X += 3; Rectangle box = new Rectangle(tl.X, tl.Y, 8, 8); itemBox.ExpandBox = box; Point center = new Point(tl.X + 4, (int)topLeft.Y + (ItemHeight / 2)); g.FillRectangle(Brushes.White, box); g.DrawRectangle(Pens.Gray, box); if (item.IsExpanded) { g.DrawRectangle(Pens.Gray, box); } else if (item.LegendItems != null && item.LegendItems.Any()) { g.DrawLine(Pens.Black, center.X, center.Y - 2, center.X, center.Y + 2); } g.DrawLine(Pens.Black, center.X - 2, center.Y, center.X + 2, center.Y); topLeft.X += 13; } /// <summary> /// Draw the symbol for a particular item. /// </summary> /// <param name="g">Graphics object used for drawing.</param> /// <param name="topLeft">TopLeft position where the symbol should be drawn.</param> /// <param name="itemBox">LegendBox of the item, the symbol should be added to.</param> private void DrawSymbol(Graphics g, ref PointF topLeft, LegendBox itemBox) { ILegendItem item = itemBox.Item; // Align symbols so that their right side is about 20 pixels left // of the top-left X, but allow up to 128x128 sized symbols Size s = item.GetLegendSymbolSize(); int h = s.Height; if (h < 1) h = 1; if (h > 128) h = 128; int w = s.Width; if (w < 1) w = 1; if (w > 128) w = 128; int tH = ItemHeight; int x = (int)topLeft.X + tH - w; int y = (int)topLeft.Y; if (tH > h) y += (tH - h) / 2; Rectangle box = new Rectangle(x, y, w, h); itemBox.SymbolBox = box; item.LegendSymbolPainted(g, box); topLeft.X += tH + 6; } private void EditBoxLostFocus(object sender, EventArgs e) { HideEditBox(); } private void HideEditBox() { if (_editBox.Visible && !_ignoreHide /*CGX*/&& _previousMouseDown != null) { _ignoreHide = true; _previousMouseDown.Item.LegendText = _editBox.Text; _previousMouseDown = null; _editBox.Visible = false; _editBox.Text = string.Empty; _ignoreHide = false; RefreshNodes(); } } // a good selectionHighlight color: 215, 238, 252 private Brush HighlightBrush(Rectangle box) { float med = _selectionHighlight.GetBrightness(); float bright = med + 0.05f; if (bright > 1f) bright = 1f; float dark = med - 0.05f; if (dark < 0f) dark = 0f; Color brtCol = SymbologyGlobal.ColorFromHsl(_selectionHighlight.GetHue(), _selectionHighlight.GetSaturation(), bright); Color drkCol = SymbologyGlobal.ColorFromHsl(_selectionHighlight.GetHue(), _selectionHighlight.GetSaturation(), dark); return new LinearGradientBrush(box, brtCol, drkCol, LinearGradientMode.Vertical); } private void LayersLayerSelected(object sender, LayerSelectedEventArgs e) { if (e.IsSelected) { _selection.Add(e.Layer); } else { _selection.Remove(e.Layer); } } /// <summary> /// This isn't the best way to catch this. Only items in view should trigger a refresh. /// </summary> /// <param name="sender">Sender that raised the event.</param> /// <param name="e">The event args.</param> private void MapFrameItemChanged(object sender, EventArgs e) { ResetLegend(); } private void MapFrameOnLayerRemoved(object sender, LayerEventArgs e) { _selection.Remove(e.Layer); } private void ResetLegend() { SizePage(); ResetScroll(); RefreshNodes(); } private Size SizeItem(int offset, ILegendItem item, Graphics g) { if (item == null) return new Size(0, 0); int width = offset + 30 + (int)g.MeasureString(item.LegendText, Font).Width; int height = ItemHeight; if (item.LegendSymbolMode == SymbolMode.Symbol) { Size s = item.GetLegendSymbolSize(); if (s.Height > ItemHeight) height = s.Height; } if (item.IsExpanded) { if (item.LegendItems != null) { foreach (ILegendItem child in item.LegendItems) { Size cs = SizeItem(offset + Indentation, child, g); height += cs.Height; if (cs.Width > width) width = cs.Width; } } } return new Size(width, height); } /// <summary> /// Checks all the legend items and calculates a "page" large enough to contain everything currently visible. /// </summary> private void SizePage() { int w = Width; int totalHeight = 0; using (var g = CreateGraphics()) { foreach (var li in RootNodes) { var itemSize = SizeItem(0, li, g); totalHeight += itemSize.Height; if (itemSize.Width > w) w = itemSize.Width; } } int h = totalHeight; DocumentRectangle = new Rectangle(0, 0, w, h); } private void TabColorDialogChangesApplied(object sender, EventArgs e) { _editCategory.LowColor = _tabColorDialog.StartColor; _editCategory.HighColor = _tabColorDialog.EndColor; ILegendItem test = _editCategory.GetParentItem(); IRasterLayer rl = test as IRasterLayer; rl?.WriteBitmap(); } private void UpdateActions(ILegendItem mapLayer) { var manager = SharedEventHandlers; var layer = mapLayer as Layer; if (layer != null) { layer.LayerActions = manager?.LayerActions; } var cc = mapLayer as ColorCategory; if (cc != null) { cc.ColorCategoryActions = manager?.ColorCategoryActions; } var fl = mapLayer as FeatureLayer; if (fl != null) { fl.FeatureLayerActions = manager?.FeatureLayerActions; } var il = mapLayer as ImageLayer; if (il != null) { il.ImageLayerActions = manager?.ImageLayerActions; } var rl = mapLayer as RasterLayer; if (rl != null) { rl.RasterLayerActions = manager?.RasterLayerActions; } } #endregion } }
/* * 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.Drawing; using System.IO; using System.Reflection; using System.Text; using System.Threading; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using CSJ2K; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Agent.TextureSender { public delegate void J2KDecodeDelegate(UUID assetID); [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "J2KDecoderModule")] public class J2KDecoderModule : ISharedRegionModule, IJ2KDecoder { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary>Temporarily holds deserialized layer data information in memory</summary> private readonly ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]> m_decodedCache = new ExpiringCache<UUID,OpenJPEG.J2KLayerInfo[]>(); /// <summary>List of client methods to notify of results of decode</summary> private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList = new Dictionary<UUID, List<DecodedCallback>>(); /// <summary>Cache that will store decoded JPEG2000 layer boundary data</summary> private IAssetCache m_cache; private IAssetCache Cache { get { if (m_cache == null) m_cache = m_scene.RequestModuleInterface<IAssetCache>(); return m_cache; } } /// <summary>Reference to a scene (doesn't matter which one as long as it can load the cache module)</summary> private UUID m_CreatorID = UUID.Zero; private Scene m_scene; #region ISharedRegionModule private bool m_useCSJ2K = true; public string Name { get { return "J2KDecoderModule"; } } public J2KDecoderModule() { } public void Initialise(IConfigSource source) { IConfig startupConfig = source.Configs["Startup"]; if (startupConfig != null) { m_useCSJ2K = startupConfig.GetBoolean("UseCSJ2K", m_useCSJ2K); } } public void AddRegion(Scene scene) { if (m_scene == null) { m_scene = scene; m_CreatorID = scene.RegionInfo.RegionID; } scene.RegisterModuleInterface<IJ2KDecoder>(this); } public void RemoveRegion(Scene scene) { if (m_scene == scene) m_scene = null; } public void PostInitialise() { } public void Close() { } public void RegionLoaded(Scene scene) { } public Type ReplaceableInterface { get { return null; } } #endregion Region Module interface #region IJ2KDecoder public void BeginDecode(UUID assetID, byte[] j2kData, DecodedCallback callback) { OpenJPEG.J2KLayerInfo[] result; // If it's cached, return the cached results if (m_decodedCache.TryGetValue(assetID, out result)) { // m_log.DebugFormat( // "[J2KDecoderModule]: Returning existing cached {0} layers j2k decode for {1}", // result.Length, assetID); callback(assetID, result); } else { // Not cached, we need to decode it. // Add to notify list and start decoding. // Next request for this asset while it's decoding will only be added to the notify list // once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated bool decode = false; lock (m_notifyList) { if (m_notifyList.ContainsKey(assetID)) { m_notifyList[assetID].Add(callback); } else { List<DecodedCallback> notifylist = new List<DecodedCallback>(); notifylist.Add(callback); m_notifyList.Add(assetID, notifylist); decode = true; } } // Do Decode! if (decode) Util.FireAndForget(delegate { Decode(assetID, j2kData); }, null, "J2KDecoderModule.BeginDecode"); } } public bool Decode(UUID assetID, byte[] j2kData) { OpenJPEG.J2KLayerInfo[] layers; int components; return Decode(assetID, j2kData, out layers, out components); } public bool Decode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers, out int components) { return DoJ2KDecode(assetID, j2kData, out layers, out components); } public Image DecodeToImage(byte[] j2kData) { if (m_useCSJ2K) return J2kImage.FromBytes(j2kData); else { ManagedImage mimage; Image image; if (OpenJPEG.DecodeToImage(j2kData, out mimage, out image)) { mimage = null; return image; } else return null; } } #endregion IJ2KDecoder /// <summary> /// Decode Jpeg2000 Asset Data /// </summary> /// <param name="assetID">UUID of Asset</param> /// <param name="j2kData">JPEG2000 data</param> /// <param name="layers">layer data</param> /// <param name="components">number of components</param> /// <returns>true if decode was successful. false otherwise.</returns> private bool DoJ2KDecode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers, out int components) { // m_log.DebugFormat( // "[J2KDecoderModule]: Doing J2K decoding of {0} bytes for asset {1}", j2kData.Length, assetID); bool decodedSuccessfully = true; //int DecodeTime = 0; //DecodeTime = Environment.TickCount; // We don't get this from CSJ2K. Is it relevant? components = 0; if (!TryLoadCacheForAsset(assetID, out layers)) { if (m_useCSJ2K) { try { List<int> layerStarts; using (MemoryStream ms = new MemoryStream(j2kData)) { layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(ms); } if (layerStarts != null && layerStarts.Count > 0) { layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count]; for (int i = 0; i < layerStarts.Count; i++) { OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo(); if (i == 0) layer.Start = 0; else layer.Start = layerStarts[i]; if (i == layerStarts.Count - 1) layer.End = j2kData.Length; else layer.End = layerStarts[i + 1] - 1; layers[i] = layer; } } } catch (Exception ex) { m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message); decodedSuccessfully = false; } } else { if (!OpenJPEG.DecodeLayerBoundaries(j2kData, out layers, out components)) { m_log.Warn("[J2KDecoderModule]: OpenJPEG failed to decode texture " + assetID); decodedSuccessfully = false; } } if (layers == null || layers.Length == 0) { m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + assetID + ", guessing sane defaults"); // Layer decoding completely failed. Guess at sane defaults for the layer boundaries layers = CreateDefaultLayers(j2kData.Length); decodedSuccessfully = false; } // Cache Decoded layers SaveFileCacheForAsset(assetID, layers); } // Notify Interested Parties lock (m_notifyList) { if (m_notifyList.ContainsKey(assetID)) { foreach (DecodedCallback d in m_notifyList[assetID]) { if (d != null) d.DynamicInvoke(assetID, layers); } m_notifyList.Remove(assetID); } } return decodedSuccessfully; } private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength) { OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5]; for (int i = 0; i < layers.Length; i++) layers[i] = new OpenJPEG.J2KLayerInfo(); // These default layer sizes are based on a small sampling of real-world texture data // with extra padding thrown in for good measure. This is a worst case fallback plan // and may not gracefully handle all real world data layers[0].Start = 0; layers[1].Start = (int)((float)j2kLength * 0.02f); layers[2].Start = (int)((float)j2kLength * 0.05f); layers[3].Start = (int)((float)j2kLength * 0.20f); layers[4].Start = (int)((float)j2kLength * 0.50f); layers[0].End = layers[1].Start - 1; layers[1].End = layers[2].Start - 1; layers[2].End = layers[3].Start - 1; layers[3].End = layers[4].Start - 1; layers[4].End = j2kLength; return layers; } private void SaveFileCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers) { m_decodedCache.AddOrUpdate(AssetId, Layers, TimeSpan.FromMinutes(10)); if (Cache != null) { string assetID = "j2kCache_" + AssetId.ToString(); AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, (sbyte)AssetType.Notecard, m_CreatorID.ToString()); layerDecodeAsset.Local = true; layerDecodeAsset.Temporary = true; #region Serialize Layer Data StringBuilder stringResult = new StringBuilder(); string strEnd = "\n"; for (int i = 0; i < Layers.Length; i++) { if (i == Layers.Length - 1) strEnd = String.Empty; stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd); } layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString()); #endregion Serialize Layer Data Cache.Cache(layerDecodeAsset); } } bool TryLoadCacheForAsset(UUID AssetId, out OpenJPEG.J2KLayerInfo[] Layers) { if (m_decodedCache.TryGetValue(AssetId, out Layers)) { return true; } else if (Cache != null) { string assetName = "j2kCache_" + AssetId.ToString(); AssetBase layerDecodeAsset; Cache.Get(assetName, out layerDecodeAsset); if (layerDecodeAsset != null) { #region Deserialize Layer Data string readResult = Util.UTF8.GetString(layerDecodeAsset.Data); string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); if (lines.Length == 0) { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (empty) " + assetName); Cache.Expire(assetName); return false; } Layers = new OpenJPEG.J2KLayerInfo[lines.Length]; for (int i = 0; i < lines.Length; i++) { string[] elements = lines[i].Split('|'); if (elements.Length == 3) { int element1, element2; try { element1 = Convert.ToInt32(elements[0]); element2 = Convert.ToInt32(elements[1]); } catch (FormatException) { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (format) " + assetName); Cache.Expire(assetName); return false; } Layers[i] = new OpenJPEG.J2KLayerInfo(); Layers[i].Start = element1; Layers[i].End = element2; } else { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (layout) " + assetName); Cache.Expire(assetName); return false; } } #endregion Deserialize Layer Data return true; } } return false; } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: SampleFix.SampleFixPublic File: MainWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace SampleFix { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Security; using System.Windows; using Ecng.Common; using Ecng.Serialization; using Ecng.Xaml; using MoreLinq; using StockSharp.Messages; using StockSharp.BusinessEntities; using StockSharp.Fix; using StockSharp.Logging; using StockSharp.Localization; public partial class MainWindow { private bool _isInitialized; public FixTrader Trader = new FixTrader(); private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow(); private readonly TradesWindow _tradesWindow = new TradesWindow(); private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow(); private readonly OrdersWindow _ordersWindow = new OrdersWindow(); private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow(); private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow(); private readonly NewsWindow _newsWindow = new NewsWindow(); private readonly LogManager _logManager = new LogManager(); private const string _settingsFile = "fix_settings.xml"; public MainWindow() { InitializeComponent(); Title = Title.Put("FIX"); _ordersWindow.MakeHideable(); _myTradesWindow.MakeHideable(); _tradesWindow.MakeHideable(); _securitiesWindow.MakeHideable(); _stopOrdersWindow.MakeHideable(); _portfoliosWindow.MakeHideable(); _newsWindow.MakeHideable(); if (File.Exists(_settingsFile)) { Trader.Load(new XmlSerializer<SettingsStorage>().Deserialize(_settingsFile)); } MarketDataSessionSettings.SelectedObject = Trader.MarketDataAdapter; TransactionSessionSettings.SelectedObject = Trader.TransactionAdapter; MarketDataSupportedMessages.Adapter = Trader.MarketDataAdapter; TransactionSupportedMessages.Adapter = Trader.TransactionAdapter; Instance = this; Trader.LogLevel = LogLevels.Debug; _logManager.Sources.Add(Trader); _logManager.Listeners.Add(new FileLogListener { LogDirectory = "StockSharp_Fix" }); } protected override void OnClosing(CancelEventArgs e) { _ordersWindow.DeleteHideable(); _myTradesWindow.DeleteHideable(); _tradesWindow.DeleteHideable(); _securitiesWindow.DeleteHideable(); _stopOrdersWindow.DeleteHideable(); _portfoliosWindow.DeleteHideable(); _newsWindow.DeleteHideable(); _securitiesWindow.Close(); _tradesWindow.Close(); _myTradesWindow.Close(); _stopOrdersWindow.Close(); _ordersWindow.Close(); _portfoliosWindow.Close(); _newsWindow.Close(); if (Trader != null) Trader.Dispose(); base.OnClosing(e); } public static MainWindow Instance { get; private set; } private void ConnectClick(object sender, RoutedEventArgs e) { if (!_isInitialized) { _isInitialized = true; Trader.Restored += () => this.GuiAsync(() => { // update gui labes ChangeConnectStatus(true); MessageBox.Show(this, LocalizedStrings.Str2958); }); // subscribe on connection successfully event Trader.Connected += () => { this.GuiAsync(() => ChangeConnectStatus(true)); }; Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false)); // subscribe on connection error event Trader.ConnectionError += error => this.GuiAsync(() => { // update gui labes ChangeConnectStatus(false); MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959); }); // subscribe on error event Trader.Error += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955)); // subscribe on error of market data subscription event Trader.MarketDataSubscriptionFailed += (security, type, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(type, security))); Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities); Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades); Trader.NewTrades += trades => _tradesWindow.TradeGrid.Trades.AddRange(trades); Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewPortfolios += portfolios => { // subscribe on portfolio updates portfolios.ForEach(Trader.RegisterPortfolio); _portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios); }; Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions); // subscribe on error of order registration event Trader.OrdersRegisterFailed += OrdersFailed; // subscribe on error of order cancelling event Trader.OrdersCancelFailed += OrdersFailed; // subscribe on error of stop-order registration event Trader.StopOrdersRegisterFailed += OrdersFailed; // subscribe on error of stop-order cancelling event Trader.StopOrdersCancelFailed += OrdersFailed; Trader.NewNews += news => _newsWindow.NewsPanel.NewsGrid.News.Add(news); // set market data provider _securitiesWindow.SecurityPicker.MarketDataProvider = Trader; // set news provider _newsWindow.NewsPanel.NewsProvider = Trader; ShowSecurities.IsEnabled = ShowTrades.IsEnabled = ShowNews.IsEnabled = ShowMyTrades.IsEnabled = ShowOrders.IsEnabled = ShowPortfolios.IsEnabled = ShowStopOrders.IsEnabled = true; } if (Trader.ConnectionState == ConnectionStates.Failed || Trader.ConnectionState == ConnectionStates.Disconnected) { new XmlSerializer<SettingsStorage>().Serialize(Trader.Save(), _settingsFile); if (!NewPassword.Password.IsEmpty()) Trader.SendInMessage(new ChangePasswordMessage { NewPassword = NewPassword.Password.To<SecureString>() }); else Trader.Connect(); } else if (Trader.ConnectionState == ConnectionStates.Connected) { Trader.Disconnect(); } } private void OrdersFailed(IEnumerable<OrderFail> fails) { this.GuiAsync(() => { foreach (var fail in fails) MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str2960); }); } private void ChangeConnectStatus(bool isConnected) { ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect; } private void ShowSecuritiesClick(object sender, RoutedEventArgs e) { ShowOrHide(_securitiesWindow); } private void ShowTradesClick(object sender, RoutedEventArgs e) { ShowOrHide(_tradesWindow); } private void ShowMyTradesClick(object sender, RoutedEventArgs e) { ShowOrHide(_myTradesWindow); } private void ShowOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_ordersWindow); } private void ShowPortfoliosClick(object sender, RoutedEventArgs e) { ShowOrHide(_portfoliosWindow); } private void ShowStopOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_stopOrdersWindow); } private void ShowNewsClick(object sender, RoutedEventArgs e) { ShowOrHide(_newsWindow); } private static void ShowOrHide(Window window) { if (window == null) throw new ArgumentNullException(nameof(window)); if (window.Visibility == Visibility.Visible) window.Hide(); else window.Show(); } } }
namespace java.util { [global::MonoJavaBridge.JavaClass()] public partial class Hashtable : java.util.Dictionary, Map, java.lang.Cloneable, java.io.Serializable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Hashtable() { InitJNI(); } protected Hashtable(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _get15451; public override global::java.lang.Object get(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Hashtable._get15451, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._get15451, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _put15452; public override global::java.lang.Object put(java.lang.Object arg0, java.lang.Object arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Hashtable._put15452, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._put15452, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _equals15453; public override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Hashtable._equals15453, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._equals15453, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString15454; public override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Hashtable._toString15454)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._toString15454)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _values15455; public virtual global::java.util.Collection values() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Collection>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Hashtable._values15455)) as java.util.Collection; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Collection>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._values15455)) as java.util.Collection; } internal static global::MonoJavaBridge.MethodId _hashCode15456; public override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.util.Hashtable._hashCode15456); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._hashCode15456); } internal static global::MonoJavaBridge.MethodId _clone15457; public virtual new global::java.lang.Object clone() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Hashtable._clone15457)) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._clone15457)) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _clear15458; public virtual void clear() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.util.Hashtable._clear15458); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._clear15458); } internal static global::MonoJavaBridge.MethodId _isEmpty15459; public override bool isEmpty() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Hashtable._isEmpty15459); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._isEmpty15459); } internal static global::MonoJavaBridge.MethodId _contains15460; public virtual bool contains(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Hashtable._contains15460, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._contains15460, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _size15461; public override int size() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.util.Hashtable._size15461); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._size15461); } internal static global::MonoJavaBridge.MethodId _entrySet15462; public virtual global::java.util.Set entrySet() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Hashtable._entrySet15462)) as java.util.Set; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._entrySet15462)) as java.util.Set; } internal static global::MonoJavaBridge.MethodId _putAll15463; public virtual void putAll(java.util.Map arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.util.Hashtable._putAll15463, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._putAll15463, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _remove15464; public override global::java.lang.Object remove(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Hashtable._remove15464, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._remove15464, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _elements15465; public override global::java.util.Enumeration elements() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Enumeration>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Hashtable._elements15465)) as java.util.Enumeration; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Enumeration>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._elements15465)) as java.util.Enumeration; } internal static global::MonoJavaBridge.MethodId _keys15466; public override global::java.util.Enumeration keys() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Enumeration>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Hashtable._keys15466)) as java.util.Enumeration; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Enumeration>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._keys15466)) as java.util.Enumeration; } internal static global::MonoJavaBridge.MethodId _keySet15467; public virtual global::java.util.Set keySet() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Hashtable._keySet15467)) as java.util.Set; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._keySet15467)) as java.util.Set; } internal static global::MonoJavaBridge.MethodId _containsValue15468; public virtual bool containsValue(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Hashtable._containsValue15468, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._containsValue15468, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _containsKey15469; public virtual bool containsKey(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Hashtable._containsKey15469, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._containsKey15469, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _rehash15470; protected virtual void rehash() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.util.Hashtable._rehash15470); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Hashtable.staticClass, global::java.util.Hashtable._rehash15470); } internal static global::MonoJavaBridge.MethodId _Hashtable15471; public Hashtable(int arg0, float arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Hashtable.staticClass, global::java.util.Hashtable._Hashtable15471, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Hashtable15472; public Hashtable(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Hashtable.staticClass, global::java.util.Hashtable._Hashtable15472, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Hashtable15473; public Hashtable() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Hashtable.staticClass, global::java.util.Hashtable._Hashtable15473); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Hashtable15474; public Hashtable(java.util.Map arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Hashtable.staticClass, global::java.util.Hashtable._Hashtable15474, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.Hashtable.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/Hashtable")); global::java.util.Hashtable._get15451 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); global::java.util.Hashtable._put15452 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); global::java.util.Hashtable._equals15453 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::java.util.Hashtable._toString15454 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "toString", "()Ljava/lang/String;"); global::java.util.Hashtable._values15455 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "values", "()Ljava/util/Collection;"); global::java.util.Hashtable._hashCode15456 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "hashCode", "()I"); global::java.util.Hashtable._clone15457 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "clone", "()Ljava/lang/Object;"); global::java.util.Hashtable._clear15458 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "clear", "()V"); global::java.util.Hashtable._isEmpty15459 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "isEmpty", "()Z"); global::java.util.Hashtable._contains15460 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "contains", "(Ljava/lang/Object;)Z"); global::java.util.Hashtable._size15461 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "size", "()I"); global::java.util.Hashtable._entrySet15462 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "entrySet", "()Ljava/util/Set;"); global::java.util.Hashtable._putAll15463 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "putAll", "(Ljava/util/Map;)V"); global::java.util.Hashtable._remove15464 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "remove", "(Ljava/lang/Object;)Ljava/lang/Object;"); global::java.util.Hashtable._elements15465 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "elements", "()Ljava/util/Enumeration;"); global::java.util.Hashtable._keys15466 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "keys", "()Ljava/util/Enumeration;"); global::java.util.Hashtable._keySet15467 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "keySet", "()Ljava/util/Set;"); global::java.util.Hashtable._containsValue15468 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "containsValue", "(Ljava/lang/Object;)Z"); global::java.util.Hashtable._containsKey15469 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "containsKey", "(Ljava/lang/Object;)Z"); global::java.util.Hashtable._rehash15470 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "rehash", "()V"); global::java.util.Hashtable._Hashtable15471 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "<init>", "(IF)V"); global::java.util.Hashtable._Hashtable15472 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "<init>", "(I)V"); global::java.util.Hashtable._Hashtable15473 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "<init>", "()V"); global::java.util.Hashtable._Hashtable15474 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "<init>", "(Ljava/util/Map;)V"); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Houses /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KGH : EduHubEntity { #region Navigation Property Cache private SCI Cache_CAMPUS_SCI; #endregion #region Foreign Navigation Properties private IReadOnlyList<SF> Cache_KGHKEY_SF_HOUSE; private IReadOnlyList<SG> Cache_KGHKEY_SG_HOUSE; private IReadOnlyList<ST> Cache_KGHKEY_ST_HOUSE; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// (Was HOUSE) House code /// [Uppercase Alphanumeric (10)] /// </summary> public string KGHKEY { get; internal set; } /// <summary> /// House description /// [Alphanumeric (30)] /// </summary> public string DESCRIPTION { get; internal set; } /// <summary> /// Campus /// </summary> public int? CAMPUS { get; internal set; } /// <summary> /// Active house? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string ACTIVE { get; internal set; } /// <summary> /// Number of current students in the house /// </summary> public short? HOUSE_SIZE { get; internal set; } /// <summary> /// Number of current males in the house /// </summary> public short? MALES { get; internal set; } /// <summary> /// Number of current females in the house /// </summary> public short? FEMALES { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F01 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F02 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F03 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F04 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F05 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F06 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F07 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F08 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F09 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F10 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F11 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F12 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F13 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F14 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F15 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F16 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F17 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F18 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F19 { get; internal set; } /// <summary> /// Number of females aged x as at 31st Dec /// </summary> public short? AGE_F20 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M01 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M02 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M03 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M04 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M05 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M06 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M07 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M08 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M09 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M10 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M11 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M12 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M13 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M14 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M15 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M16 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M17 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M18 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M19 { get; internal set; } /// <summary> /// Number of males aged x as at 31 dec /// </summary> public short? AGE_M20 { get; internal set; } /// <summary> /// Number of self-described gender students in house /// </summary> public short? SELF_DESCRIBED { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S01 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S02 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S03 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S04 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S05 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S06 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S07 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S08 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S09 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S10 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S11 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S12 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S13 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S14 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S15 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S16 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S17 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S18 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S19 { get; internal set; } /// <summary> /// Number of self-described gender students aged x as at 31 dec /// </summary> public short? AGE_S20 { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last write operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// SCI (School Information) related entity by [KGH.CAMPUS]-&gt;[SCI.SCIKEY] /// Campus /// </summary> public SCI CAMPUS_SCI { get { if (CAMPUS == null) { return null; } if (Cache_CAMPUS_SCI == null) { Cache_CAMPUS_SCI = Context.SCI.FindBySCIKEY(CAMPUS.Value); } return Cache_CAMPUS_SCI; } } #endregion #region Foreign Navigation Properties /// <summary> /// SF (Staff) related entities by [KGH.KGHKEY]-&gt;[SF.HOUSE] /// (Was HOUSE) House code /// </summary> public IReadOnlyList<SF> KGHKEY_SF_HOUSE { get { if (Cache_KGHKEY_SF_HOUSE == null && !Context.SF.TryFindByHOUSE(KGHKEY, out Cache_KGHKEY_SF_HOUSE)) { Cache_KGHKEY_SF_HOUSE = new List<SF>().AsReadOnly(); } return Cache_KGHKEY_SF_HOUSE; } } /// <summary> /// SG (Student Groupings) related entities by [KGH.KGHKEY]-&gt;[SG.HOUSE] /// (Was HOUSE) House code /// </summary> public IReadOnlyList<SG> KGHKEY_SG_HOUSE { get { if (Cache_KGHKEY_SG_HOUSE == null && !Context.SG.TryFindByHOUSE(KGHKEY, out Cache_KGHKEY_SG_HOUSE)) { Cache_KGHKEY_SG_HOUSE = new List<SG>().AsReadOnly(); } return Cache_KGHKEY_SG_HOUSE; } } /// <summary> /// ST (Students) related entities by [KGH.KGHKEY]-&gt;[ST.HOUSE] /// (Was HOUSE) House code /// </summary> public IReadOnlyList<ST> KGHKEY_ST_HOUSE { get { if (Cache_KGHKEY_ST_HOUSE == null && !Context.ST.TryFindByHOUSE(KGHKEY, out Cache_KGHKEY_ST_HOUSE)) { Cache_KGHKEY_ST_HOUSE = new List<ST>().AsReadOnly(); } return Cache_KGHKEY_ST_HOUSE; } } #endregion } }
using System; using System.Net.Sockets; using System.IO; using System.Text; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using JeffRemote.comm; namespace JeffRemote.tcp { /// <summary> /// Summary description for TCPClient. /// </summary> public class TCPClient : IClient { private IChannel _Channel; private System.Net.Sockets.TcpClient _Client; private System.Net.Sockets.NetworkStream _Stream; private byte[] _ReadBuffer = new byte[4097]; private MemoryStream _ReadStream = new MemoryStream(); private AsyncCallback _CBRead = new AsyncCallback(OnRead); private AsyncCallback _CBWrite = new AsyncCallback(OnWrite); private Object _Data; public int _UserCode; public void setData(Object obj) { _Data = obj; } public Object getData() { return _Data; } public bool _connected = false; public TCPClient(System.Net.Sockets.TcpClient Client, IChannel Channel, int Code) { try { _Data = null; _Code = Code; _Client = Client; _Channel = Channel; _Stream = Client.GetStream(); _Stream.BeginRead(_ReadBuffer , 0, 4096, _CBRead, this); } catch(Exception e) { string error = e.ToString(); Close(); } } public TCPClient(string host, int port, IChannel Channel, int Code) { try { _Data = null; _Code = Code; _Client = new System.Net.Sockets.TcpClient(host,port); _Channel = Channel; _Stream = _Client.GetStream(); _Stream.BeginRead(_ReadBuffer , 0, 4096, _CBRead, this); _connected = true; } catch(Exception e) { string error = e.ToString(); Close(); } } public void Close() { if(_Channel != null) _Channel.OnClose(this); if (_Client != null) _Client.Close(); if (_Stream != null) _Stream.Close(); _Stream = null; _Channel = null; _Client = null; } public void OnDataItem() { // some variables // *the length of the data stream to be serialized // *the length of the integer // *the length of the whole data stream past the binary int datalen = 0, blen = 0, alen = 0; // start reading at the origin _ReadStream.Seek(0, SeekOrigin.Begin); // prepare the binary reader BinaryReader BR = new BinaryReader(_ReadStream); // what is the length of the data to be read in datalen = BR.ReadInt32(); // where are we now blen = (int) _ReadStream.Position; // go to the end for length calcuation of the stream (not the buffer) _ReadStream.Seek(0, SeekOrigin.End); // what is the length of the stream so far alen = (int) _ReadStream.Position - blen; // go back to origin _ReadStream.Seek(0, SeekOrigin.Begin); // move past initial integer datalen = BR.ReadInt32(); // can we serializat, if so do so if(alen >= datalen) { object root = null; try { IFormatter formatter = (IFormatter) new BinaryFormatter(); root = formatter.Deserialize(_ReadStream); try { _Channel.OnObject(this, root); } catch (Exception e) { String error = e.ToString(); } downShift(_ReadStream); } catch (Exception e) { // there twas an error, can't stream so remove the "bad stream" _ReadStream.Seek(alen+datalen, SeekOrigin.Begin); downShift(_ReadStream); throw e; } } else { throw new Exception("not enough data"); } } public void OnData() { try { while(true) OnDataItem(); } catch (Exception e) { string zee = e.ToString(); } } // operation that needs tweaking for speed public static void downShift(MemoryStream MS) { int curPos = (int) MS.Position; int endLen = (int) MS.Length - curPos; MemoryStream _Buffer = new MemoryStream(); MS.WriteTo(_Buffer); byte[] buffer = _Buffer.GetBuffer(); MS.Seek(0, SeekOrigin.Begin); MS.Write( buffer , curPos, endLen) ; MS.SetLength(endLen); } public void HandleR(IAsyncResult ar) { try { int BytesRead = _Stream.EndRead(ar); if(BytesRead>0) { _ReadStream.Seek(0, SeekOrigin.End); _ReadStream.Write(_ReadBuffer, 0, BytesRead); OnData(); _Stream.BeginRead(_ReadBuffer,0,4096,_CBRead,this); } else { Close(); } } catch(Exception e) { string error = e.ToString(); Close(); } } public void WriteObject(object root) { try { MemoryStream MS = new MemoryStream(); MemoryStream Pre = new MemoryStream(); BinaryWriter BW = new BinaryWriter(MS); IFormatter formatter = (IFormatter) new BinaryFormatter(); formatter.Serialize(Pre, root); BW.Write((int) Pre.Length); Pre.WriteTo(MS); _Stream.BeginWrite(MS.GetBuffer(),0,(int)MS.Length,_CBWrite,this); } catch(Exception e) { string error = e.ToString(); //System.Windows.Forms.MessageBox.Show("WriteObject Failed!"); Close(); } } public void HandleW(IAsyncResult ar) { try { _Stream.EndWrite(ar); } catch(Exception e) { string error = e.ToString(); Close(); } } public static void OnRead(IAsyncResult ar) { ((TCPClient) ar.AsyncState).HandleR(ar); } public static void OnWrite(IAsyncResult ar) { ((TCPClient ) ar.AsyncState).HandleW(ar); } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using Encog.App.Analyst.CSV.Basic; using Encog.ML.Prg.ExpValue; using Encog.ML.Prg.Ext; using Encog.Util.CSV; namespace Encog.App.Analyst.CSV.Process { public class ProcessExtension { public const String EXTENSION_DATA_NAME = "ENCOG-ANALYST-PROCESS"; // add field public static IProgramExtensionTemplate OPCODE_FIELD = new BasicTemplate( BasicTemplate.NoPrec, "field({s}{i}):{s}", NodeType.Function, true, 0, (actual) => { var pe = (ProcessExtension) actual.Owner.GetExtraData(EXTENSION_DATA_NAME); string fieldName = actual.GetChildNode(0).Evaluate().ToStringValue(); int fieldIndex = (int) actual.GetChildNode(1).Evaluate().ToFloatValue() + pe.BackwardWindowSize; String value = pe.GetField(fieldName, fieldIndex); return new ExpressionValue(value); }, null, null); // add fieldmax public static IProgramExtensionTemplate OPCODE_FIELDMAX = new BasicTemplate( BasicTemplate.NoPrec, "fieldmax({s}{i}{i}):{f}", NodeType.Function, true, 0, (actual) => { var pe = (ProcessExtension) actual.Owner.GetExtraData(EXTENSION_DATA_NAME); String fieldName = actual.GetChildNode(0).Evaluate().ToStringValue(); var startIndex = (int) actual.GetChildNode(1).Evaluate().ToIntValue(); var stopIndex = (int) actual.GetChildNode(2).Evaluate().ToIntValue(); double value = double.NegativeInfinity; for (int i = startIndex; i <= stopIndex; i++) { String str = pe.GetField(fieldName, pe.BackwardWindowSize + i); double d = pe.format.Parse(str); value = Math.Max(d, value); } return new ExpressionValue(value); }, null, null); // add fieldmaxpip public static IProgramExtensionTemplate OPCODE_FIELDMAXPIP = new BasicTemplate( BasicTemplate.NoPrec, "fieldmaxpip({s}{i}{i}):{f}", NodeType.Function, true, 0, (actual) => { var pe = (ProcessExtension) actual.Owner.GetExtraData(EXTENSION_DATA_NAME); String fieldName = actual.GetChildNode(0).Evaluate() .ToStringValue(); var startIndex = (int) actual.GetChildNode(1).Evaluate() .ToIntValue(); var stopIndex = (int) actual.GetChildNode(2).Evaluate() .ToIntValue(); int value = int.MinValue; String str = pe.GetField(fieldName, pe.BackwardWindowSize); double quoteNow = pe.Format.Parse(str); for (int i = startIndex; i <= stopIndex; i++) { str = pe.GetField(fieldName, pe.BackwardWindowSize + i); double d = pe.Format.Parse(str) - quoteNow; d /= 0.0001; d = Math.Round(d); value = Math.Max((int) d, value); } return new ExpressionValue(value); }, null, null); private readonly IList<LoadedRow> data = new List<LoadedRow>(); private readonly CSVFormat format; private readonly IDictionary<string, int> map = new Dictionary<string, int>(); private int backwardWindowSize; private int forwardWindowSize; private int totalWindowSize; /** * Add opcodes to the Encog resource registry. */ public ProcessExtension() { EncogOpcodeRegistry.Instance.Add(OPCODE_FIELD); EncogOpcodeRegistry.Instance.Add(OPCODE_FIELDMAX); EncogOpcodeRegistry.Instance.Add(OPCODE_FIELDMAXPIP); } public ProcessExtension(CSVFormat theFormat) { format = theFormat; } public int ForwardWindowSize { get { return forwardWindowSize; } } public int BackwardWindowSize { get { return backwardWindowSize; } } public int TotalWindowSize { get { return totalWindowSize; } } public CSVFormat Format { get { return format; } } public String GetField(String fieldName, int fieldIndex) { if (!map.ContainsKey(fieldName)) { throw new AnalystError("Unknown input field: " + fieldName); } int idx = map[fieldName]; if (fieldIndex >= data.Count || fieldIndex < 0) { throw new AnalystError( "The specified temporal index " + fieldIndex + " is out of bounds. You should probably increase the forward window size."); } return data[fieldIndex].Data[idx]; } public void LoadRow(LoadedRow row) { data.Insert(0, row); if (data.Count > totalWindowSize) { data.RemoveAt(data.Count - 1); } } public void Init(ReadCSV csv, int theBackwardWindowSize, int theForwardWindowSize) { forwardWindowSize = theForwardWindowSize; backwardWindowSize = theBackwardWindowSize; totalWindowSize = forwardWindowSize + backwardWindowSize + 1; int i = 0; foreach (string name in csv.ColumnNames) { map[name] = i++; } } public bool IsDataReady() { return data.Count >= totalWindowSize; } public void register(FunctionFactory functions) { functions.AddExtension(OPCODE_FIELD); functions.AddExtension(OPCODE_FIELDMAX); functions.AddExtension(OPCODE_FIELDMAXPIP); } } }
using System; using ArgData.Internals; namespace ArgData.Entities { /// <summary> /// The ITrackObjectShapePoint represents a basic point in a 3D coordinate system (X, Y and Z). /// </summary> [CLSCompliant(false)] public interface ITrackObjectShapePoint { /// <summary> /// Gets the X coordinate of the point. /// </summary> short X { get; } /// <summary> /// Gets the Y coordinate of the point. /// </summary> short Y { get; } /// <summary> /// Gets the Z coordinate of the point. /// </summary> [CLSCompliant(false)] ushort Z { get; } /// <summary> /// Returns the bytes that represent the point in the track file. /// </summary> /// <returns>Byte array.</returns> byte[] GetBytes(); } /// <summary> /// Represents the raw data of a point in the 3D shape. /// </summary> internal class TrackObjectShapeRawPoint { /// <summary> /// Gets or sets the raw X coordinate value. /// </summary> public short XCoord { get; set; } /// <summary> /// Gets or sets the X and Y coordinate reference point value (for reference points). /// /// This is the first byte of the XCoord. /// </summary> public byte ReferencePointValue { get; set; } /// <summary> /// Gets or sets the reference point flag (0x80). /// /// This is the second byte of the XCoord. /// </summary> public byte ReferencePointFlag { get; set; } /// <summary> /// Gets or sets the raw Y coordinate value. /// </summary> public short YCoord { get; set; } /// <summary> /// Gets or sets the Z coordinate value. Always positive. /// </summary> public ushort ZCoord { get; set; } /// <summary> /// Gets or sets an unknown value. Always 0 in standard tracks. /// </summary> public ushort Unknown { get; set; } } /// <summary> /// Represents a 3D point that uses the scale values to define its X, Y and Z coordinates. /// </summary> public class TrackObjectShapeScalePoint : ITrackObjectShapePoint { private readonly TrackObjectShape _shape; /// <summary> /// Initializes an instance of a TrackObjectShapeScalePoint. /// </summary> /// <param name="shape">Related TrackObjectShape.</param> public TrackObjectShapeScalePoint(TrackObjectShape shape) { _shape = shape; } /// <summary> /// Gets or sets the index of the scale value to use for the X coordinate. /// </summary> public short XScaleValueIndex { get; set; } /// <summary> /// Gets or sets whether the X coordinate value is positive or negative. /// </summary> public bool XIsNegative { get; set; } /// <summary> /// Gets the actual X point coordinate using the scale value index. /// </summary> public short X { get { if (XScaleValueIndex == -1) { return 0; } short value = _shape.ScaleValues[XScaleValueIndex]; return XIsNegative ? (short)-value : value; } } /// <summary> /// Gets or sets the index of the scale value to use for the Y coordinate. /// </summary> public short YScaleValueIndex { get; set; } /// <summary> /// Gets or sets whether the Y coordinate value is positive or negative. /// </summary> public bool YIsNegative { get; set; } /// <summary> /// Gets the actual Y point coordinate using the scale value index. /// </summary> public short Y { get { if (YScaleValueIndex == -1) { return 0; } short value = _shape.ScaleValues[YScaleValueIndex]; return YIsNegative ? (short)-value : value; } } /// <summary> /// Gets or sets the value of the Z coordinate. /// </summary> [CLSCompliant(false)] public ushort Z { get; set; } /// <summary> /// Returns the bytes that represent the point in the track file. /// </summary> /// <returns>Byte array.</returns> public byte[] GetBytes() { var bytes = new ByteList(); // Xr1 int xr1Shift = XIsNegative ? 34 : 2; byte xr1 = (byte)((XScaleValueIndex * 2) + xr1Shift); bytes.AddByte(xr1); // Xr2 bytes.AddByte(0x00); // YCoord, first part int yr1Shift = YIsNegative ? 34 : 2; byte yr1 = (byte)((YScaleValueIndex * 2) + yr1Shift); bytes.AddByte(yr1); // YCoord, second part bytes.AddByte(0x00); // Z bytes.AddUInt16(Z); // Unknown, always 0 ("TwinPoint"?) bytes.AddUInt16(0); return bytes.GetBytes(); } } /// <summary> /// The TrackObjectShapeReferencePoint class represents a 3D point that is defined by using references /// to other previously defined X and Y coordinates, but with a separate Z value. /// </summary> public class TrackObjectShapeReferencePoint : ITrackObjectShapePoint { private readonly TrackObjectShape _shape; /// <summary> /// Initializes an instance of a TrackObjectShapeReferencePoint. /// </summary> /// <param name="shape">Related TrackObjectShape.</param> public TrackObjectShapeReferencePoint(TrackObjectShape shape) { _shape = shape; } /// <summary> /// Gets or sets the index of the other point that this point uses for X and Y coordinates. /// </summary> public byte PointIndex { get; set; } /// <summary> /// Gets the actual X point coordinate using the referenced value. /// </summary> public short X { get { return _shape.Points[PointIndex].X; } } /// <summary> /// Gets the actual Y point coordinate using the referenced value. /// </summary> public short Y { get { return _shape.Points[PointIndex].Y; } } /// <summary> /// Gets the Z point coordinate. /// </summary> [CLSCompliant(false)] public ushort Z { get; set; } /// <summary> /// Returns the bytes that represent the point in the track file. /// </summary> /// <returns>Byte array.</returns> public byte[] GetBytes() { var bytes = new ByteList(); // Xr1 bytes.AddByte(PointIndex); // Xr2 bytes.AddByte(0x80); // YCoord bytes.AddUInt16(0x00); // Z bytes.AddUInt16(Z); // Unknown, always 0 ("TwinPoint"?) bytes.AddUInt16(0); return bytes.GetBytes(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // NOTE: This file is generated via a T4 template. Please do not edit this file directly. Any changes should be made // in Unsigned.tt. namespace System.Text { public static partial class PrimitiveParser { public static bool TryParseByte(ReadOnlySpan<byte> text, out byte value, out int bytesConsumed, TextFormat format = default(TextFormat), TextEncoder encoder = null) { encoder = encoder == null ? TextEncoder.Utf8 : encoder; if (!format.IsDefault && format.HasPrecision) { throw new NotImplementedException("Format with precision not supported."); } if (encoder.IsInvariantUtf8) { if (format.IsHexadecimal) { return InvariantUtf8.Hex.TryParseByte(text, out value, out bytesConsumed); } else { return InvariantUtf8.TryParseByte(text, out value, out bytesConsumed); } } else if (encoder.IsInvariantUtf16) { ReadOnlySpan<char> utf16Text = text.NonPortableCast<byte, char>(); int charsConsumed; bool result; if (format.IsHexadecimal) { result = InvariantUtf16.Hex.TryParseByte(utf16Text, out value, out charsConsumed); } else { result = InvariantUtf16.TryParseByte(utf16Text, out value, out charsConsumed); } bytesConsumed = charsConsumed * sizeof(char); return result; } if (format.IsHexadecimal) { throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16."); } if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g')) { throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol)); } uint nextSymbol; int thisSymbolConsumed; if (!encoder.TryParseSymbol(text, out nextSymbol, out thisSymbolConsumed)) { value = default(byte); bytesConsumed = 0; return false; } if (nextSymbol > 9) { value = default(byte); bytesConsumed = 0; return false; } uint parsedValue = nextSymbol; int index = thisSymbolConsumed; while (index < text.Length) { bool success = encoder.TryParseSymbol(text.Slice(index), out nextSymbol, out thisSymbolConsumed); if (!success || nextSymbol > 9) { bytesConsumed = index; value = (byte) parsedValue; return true; } // If parsedValue > (byte.MaxValue / 10), any more appended digits will cause overflow. // if parsedValue == (byte.MaxValue / 10), any nextDigit greater than 5 implies overflow. if (parsedValue > byte.MaxValue / 10 || (parsedValue == byte.MaxValue / 10 && nextSymbol > 5)) { bytesConsumed = 0; value = default(byte); return false; } index += thisSymbolConsumed; parsedValue = parsedValue * 10 + nextSymbol; } bytesConsumed = text.Length; value = (byte) parsedValue; return true; } public static bool TryParseUInt16(ReadOnlySpan<byte> text, out ushort value, out int bytesConsumed, TextFormat format = default(TextFormat), TextEncoder encoder = null) { encoder = encoder == null ? TextEncoder.Utf8 : encoder; if (!format.IsDefault && format.HasPrecision) { throw new NotImplementedException("Format with precision not supported."); } if (encoder.IsInvariantUtf8) { if (format.IsHexadecimal) { return InvariantUtf8.Hex.TryParseUInt16(text, out value, out bytesConsumed); } else { return InvariantUtf8.TryParseUInt16(text, out value, out bytesConsumed); } } else if (encoder.IsInvariantUtf16) { ReadOnlySpan<char> utf16Text = text.NonPortableCast<byte, char>(); int charsConsumed; bool result; if (format.IsHexadecimal) { result = InvariantUtf16.Hex.TryParseUInt16(utf16Text, out value, out charsConsumed); } else { result = InvariantUtf16.TryParseUInt16(utf16Text, out value, out charsConsumed); } bytesConsumed = charsConsumed * sizeof(char); return result; } if (format.IsHexadecimal) { throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16."); } if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g')) { throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol)); } uint nextSymbol; int thisSymbolConsumed; if (!encoder.TryParseSymbol(text, out nextSymbol, out thisSymbolConsumed)) { value = default(ushort); bytesConsumed = 0; return false; } if (nextSymbol > 9) { value = default(ushort); bytesConsumed = 0; return false; } uint parsedValue = nextSymbol; int index = thisSymbolConsumed; while (index < text.Length) { bool success = encoder.TryParseSymbol(text.Slice(index), out nextSymbol, out thisSymbolConsumed); if (!success || nextSymbol > 9) { bytesConsumed = index; value = (ushort) parsedValue; return true; } // If parsedValue > (ushort.MaxValue / 10), any more appended digits will cause overflow. // if parsedValue == (ushort.MaxValue / 10), any nextDigit greater than 5 implies overflow. if (parsedValue > ushort.MaxValue / 10 || (parsedValue == ushort.MaxValue / 10 && nextSymbol > 5)) { bytesConsumed = 0; value = default(ushort); return false; } index += thisSymbolConsumed; parsedValue = parsedValue * 10 + nextSymbol; } bytesConsumed = text.Length; value = (ushort) parsedValue; return true; } public static bool TryParseUInt32(ReadOnlySpan<byte> text, out uint value, out int bytesConsumed, TextFormat format = default(TextFormat), TextEncoder encoder = null) { encoder = encoder == null ? TextEncoder.Utf8 : encoder; if (!format.IsDefault && format.HasPrecision) { throw new NotImplementedException("Format with precision not supported."); } if (encoder.IsInvariantUtf8) { if (format.IsHexadecimal) { return InvariantUtf8.Hex.TryParseUInt32(text, out value, out bytesConsumed); } else { return InvariantUtf8.TryParseUInt32(text, out value, out bytesConsumed); } } else if (encoder.IsInvariantUtf16) { ReadOnlySpan<char> utf16Text = text.NonPortableCast<byte, char>(); int charsConsumed; bool result; if (format.IsHexadecimal) { result = InvariantUtf16.Hex.TryParseUInt32(utf16Text, out value, out charsConsumed); } else { result = InvariantUtf16.TryParseUInt32(utf16Text, out value, out charsConsumed); } bytesConsumed = charsConsumed * sizeof(char); return result; } if (format.IsHexadecimal) { throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16."); } if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g')) { throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol)); } uint nextSymbol; int thisSymbolConsumed; if (!encoder.TryParseSymbol(text, out nextSymbol, out thisSymbolConsumed)) { value = default(uint); bytesConsumed = 0; return false; } if (nextSymbol > 9) { value = default(uint); bytesConsumed = 0; return false; } uint parsedValue = nextSymbol; int index = thisSymbolConsumed; while (index < text.Length) { bool success = encoder.TryParseSymbol(text.Slice(index), out nextSymbol, out thisSymbolConsumed); if (!success || nextSymbol > 9) { bytesConsumed = index; value = (uint) parsedValue; return true; } // If parsedValue > (uint.MaxValue / 10), any more appended digits will cause overflow. // if parsedValue == (uint.MaxValue / 10), any nextDigit greater than 5 implies overflow. if (parsedValue > uint.MaxValue / 10 || (parsedValue == uint.MaxValue / 10 && nextSymbol > 5)) { bytesConsumed = 0; value = default(uint); return false; } index += thisSymbolConsumed; parsedValue = parsedValue * 10 + nextSymbol; } bytesConsumed = text.Length; value = (uint) parsedValue; return true; } public static bool TryParseUInt64(ReadOnlySpan<byte> text, out ulong value, out int bytesConsumed, TextFormat format = default(TextFormat), TextEncoder encoder = null) { encoder = encoder == null ? TextEncoder.Utf8 : encoder; if (!format.IsDefault && format.HasPrecision) { throw new NotImplementedException("Format with precision not supported."); } if (encoder.IsInvariantUtf8) { if (format.IsHexadecimal) { return InvariantUtf8.Hex.TryParseUInt64(text, out value, out bytesConsumed); } else { return InvariantUtf8.TryParseUInt64(text, out value, out bytesConsumed); } } else if (encoder.IsInvariantUtf16) { ReadOnlySpan<char> utf16Text = text.NonPortableCast<byte, char>(); int charsConsumed; bool result; if (format.IsHexadecimal) { result = InvariantUtf16.Hex.TryParseUInt64(utf16Text, out value, out charsConsumed); } else { result = InvariantUtf16.TryParseUInt64(utf16Text, out value, out charsConsumed); } bytesConsumed = charsConsumed * sizeof(char); return result; } if (format.IsHexadecimal) { throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16."); } if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g')) { throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol)); } uint nextSymbol; int thisSymbolConsumed; if (!encoder.TryParseSymbol(text, out nextSymbol, out thisSymbolConsumed)) { value = default(ulong); bytesConsumed = 0; return false; } if (nextSymbol > 9) { value = default(ulong); bytesConsumed = 0; return false; } ulong parsedValue = nextSymbol; int index = thisSymbolConsumed; while (index < text.Length) { bool success = encoder.TryParseSymbol(text.Slice(index), out nextSymbol, out thisSymbolConsumed); if (!success || nextSymbol > 9) { bytesConsumed = index; value = (ulong) parsedValue; return true; } // If parsedValue > (ulong.MaxValue / 10), any more appended digits will cause overflow. // if parsedValue == (ulong.MaxValue / 10), any nextDigit greater than 5 implies overflow. if (parsedValue > ulong.MaxValue / 10 || (parsedValue == ulong.MaxValue / 10 && nextSymbol > 5)) { bytesConsumed = 0; value = default(ulong); return false; } index += thisSymbolConsumed; parsedValue = parsedValue * 10 + nextSymbol; } bytesConsumed = text.Length; value = (ulong) parsedValue; return true; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.PetstoreV2AllSync { using System.Threading.Tasks; using Models; /// <summary> /// Extension methods for SwaggerPetstoreV2. /// </summary> public static partial class SwaggerPetstoreV2Extensions { /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static Pet AddPet(this ISwaggerPetstoreV2 operations, Pet body) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).AddPetAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Pet> AddPetAsync(this ISwaggerPetstoreV2 operations, Pet body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse<Pet> AddPetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.AddPetWithHttpMessagesAsync(body, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static void UpdatePet(this ISwaggerPetstoreV2 operations, Pet body) { System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task UpdatePetAsync(this ISwaggerPetstoreV2 operations, Pet body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse UpdatePetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.UpdatePetWithHttpMessagesAsync(body, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> public static System.Collections.Generic.IList<Pet> FindPetsByStatus(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<string> status) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByStatusAsync(status), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<string> status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>> FindPetsByStatusWithHttpMessages(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<string> status, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.FindPetsByStatusWithHttpMessagesAsync(status, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> public static System.Collections.Generic.IList<Pet> FindPetsByTags(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<string> tags) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByTagsAsync(tags), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>> FindPetsByTagsWithHttpMessages(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<string> tags, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.FindPetsByTagsWithHttpMessagesAsync(tags, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Find pet by Id /// </summary> /// <remarks> /// Returns a single pet /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet to return /// </param> public static Pet GetPetById(this ISwaggerPetstoreV2 operations, long petId) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetPetByIdAsync(petId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find pet by Id /// </summary> /// <remarks> /// Returns a single pet /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Pet> GetPetByIdAsync(this ISwaggerPetstoreV2 operations, long petId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find pet by Id /// </summary> /// <remarks> /// Returns a single pet /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse<Pet> GetPetByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.GetPetByIdWithHttpMessagesAsync(petId, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> public static void UpdatePetWithForm(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetWithFormAsync(petId, fileContent, fileName, status), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task UpdatePetWithFormAsync(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse UpdatePetWithFormWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> public static void DeletePet(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "") { System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeletePetAsync(petId, apiKey), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task DeletePetAsync(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse DeletePetWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.DeletePetWithHttpMessagesAsync(petId, apiKey, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.Collections.Generic.IDictionary<string, int?> GetInventory(this ISwaggerPetstoreV2 operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetInventoryAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstoreV2 operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IDictionary<string, int?>> GetInventoryWithHttpMessages(this ISwaggerPetstoreV2 operations, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.GetInventoryWithHttpMessagesAsync(customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> public static Order PlaceOrder(this ISwaggerPetstoreV2 operations, Order body) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).PlaceOrderAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Order> PlaceOrderAsync(this ISwaggerPetstoreV2 operations, Order body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse<Order> PlaceOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, Order body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.PlaceOrderWithHttpMessagesAsync(body, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Find purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> public static Order GetOrderById(this ISwaggerPetstoreV2 operations, string orderId) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetOrderByIdAsync(orderId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Order> GetOrderByIdAsync(this ISwaggerPetstoreV2 operations, string orderId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse<Order> GetOrderByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.GetOrderByIdWithHttpMessagesAsync(orderId, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Delete purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> public static void DeleteOrder(this ISwaggerPetstoreV2 operations, string orderId) { System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteOrderAsync(orderId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task DeleteOrderAsync(this ISwaggerPetstoreV2 operations, string orderId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse DeleteOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.DeleteOrderWithHttpMessagesAsync(orderId, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> public static void CreateUser(this ISwaggerPetstoreV2 operations, User body) { System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUserAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task CreateUserAsync(this ISwaggerPetstoreV2 operations, User body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse CreateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, User body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.CreateUserWithHttpMessagesAsync(body, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithArrayInput(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<User> body) { System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithArrayInputAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task CreateUsersWithArrayInputAsync(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<User> body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse CreateUsersWithArrayInputWithHttpMessages(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<User> body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithListInput(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<User> body) { System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithListInputAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task CreateUsersWithListInputAsync(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<User> body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse CreateUsersWithListInputWithHttpMessages(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<User> body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.CreateUsersWithListInputWithHttpMessagesAsync(body, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> public static string LoginUser(this ISwaggerPetstoreV2 operations, string username, string password) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LoginUserAsync(username, password), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<string> LoginUserAsync(this ISwaggerPetstoreV2 operations, string username, string password, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse<string,LoginUserHeaders> LoginUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, string password, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.LoginUserWithHttpMessagesAsync(username, password, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void LogoutUser(this ISwaggerPetstoreV2 operations) { System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LogoutUserAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task LogoutUserAsync(this ISwaggerPetstoreV2 operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse LogoutUserWithHttpMessages(this ISwaggerPetstoreV2 operations, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.LogoutUserWithHttpMessagesAsync(customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> public static User GetUserByName(this ISwaggerPetstoreV2 operations, string username) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetUserByNameAsync(username), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<User> GetUserByNameAsync(this ISwaggerPetstoreV2 operations, string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse<User> GetUserByNameWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.GetUserByNameWithHttpMessagesAsync(username, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> public static void UpdateUser(this ISwaggerPetstoreV2 operations, string username, User body) { System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdateUserAsync(username, body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task UpdateUserAsync(this ISwaggerPetstoreV2 operations, string username, User body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse UpdateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, User body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.UpdateUserWithHttpMessagesAsync(username, body, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> public static void DeleteUser(this ISwaggerPetstoreV2 operations, string username) { System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteUserAsync(username), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task DeleteUserAsync(this ISwaggerPetstoreV2 operations, string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static Microsoft.Rest.HttpOperationResponse DeleteUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null) { return operations.DeleteUserWithHttpMessagesAsync(username, customHeaders, System.Threading.CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } } }
//--------------------------------------------------------------------- // <copyright file="ColumnMap.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System; using System.Text; using System.Collections.Generic; using md = System.Data.Metadata.Edm; using mp = System.Data.Mapping; using System.Globalization; using System.Diagnostics; using System.Data.Common.Utils; // A ColumnMap is a data structure that maps columns from the C space to // the corresponding columns from one or more underlying readers. // // ColumnMaps are used by the ResultAssembly phase to assemble results in the // desired shape (as requested by the caller) from a set of underlying // (usually) flat readers. ColumnMaps are produced as part of the PlanCompiler // module of the bridge, and are consumed by the Execution phase of the bridge. // // * Simple (scalar) columns (and UDTs) are represented by a SimpleColumnMap // * Record type columns are represented by a RecordColumnMap // * A nominal type instance (that supports inheritance) is usually represented // by a PolymorphicColumnMap - this polymorphicColumnMap contains information // about the type discriminator (assumed to be a simple column), and a mapping // from type-discriminator value to the column map for the specific type // * The specific type for nominal types is represented by ComplexTypeColumnMap // for complextype columns, and EntityColumnMap for entity type columns. // EntityColumnMaps additionally have an EntityIdentity that describes // the entity identity. The entity identity is logically just a set of keys // (and the column maps), plus a column map that helps to identify the // the appropriate entity set for the entity instance // * Refs are represented by a RefColumnMap. The RefColumnMap simply contains an // EntityIdentity // * Collections are represented by either a SimpleCollectionColumnMap or a // DiscriminatedCollectionColumnMap. Both of these contain a column map for the // element type, and an optional list of simple columns (the keys) that help // demarcate the elements of a specific collection instance. // The DiscriminatedCollectionColumnMap is used in scenarios when the containing // row has multiple collections, and the different collection properties must be // differentiated. This differentiation is achieved via a Discriminator column // (a simple column), and a Discriminator value. The value of the Discriminator // column is read and compared with the DiscriminatorValue stored in this map // to determine if we're dealing with the current collection. // // NOTE: // * Key columns are assumed to be SimpleColumns. There may be more than one key // column (applies to EntityColumnMap and *CollectionColumnMap) // * TypeDiscriminator and Discriminator columns are also considered to be // SimpleColumns. There are singleton columns. // // It is the responsibility of the PlanCompiler phase to produce the right column // maps. // // The result of a query is always assumed to be a collection. The ColumnMap that we // return as part of plan compilation refers to the element type of this collection // - the element type is usually a structured type, but may also be a simple type // or another collection type. How does the DbRecord framework handle these cases? // // namespace System.Data.Query.InternalTrees { /// <summary> /// Represents a column /// </summary> internal abstract class ColumnMap { private md.TypeUsage m_type; // column datatype private string m_name; // name of the column /// <summary> /// Default Column Name; should not be set until CodeGen once we're done /// with all our transformations that might give us a good name, but put /// here for ease of finding it. /// </summary> internal const string DefaultColumnName = "Value"; /// <summary> /// Simple constructor - just needs the name and type of the column /// </summary> /// <param name="type">column type</param> /// <param name="name">column name</param> internal ColumnMap(md.TypeUsage type, string name) { Debug.Assert(type != null, "Unspecified type"); m_type = type; m_name = name; } /// <summary> /// Get the column's datatype /// </summary> internal md.TypeUsage Type { get { return m_type; } } /// <summary> /// Get the column name /// </summary> internal string Name { get { return m_name; } set { Debug.Assert(!String.IsNullOrEmpty(value), "invalid name?"); m_name = value; } } /// <summary> /// Returns whether the column already has a name; /// </summary> internal bool IsNamed { get { return m_name != null; } } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> /// <returns></returns> [DebuggerNonUserCode] internal abstract void Accept<TArgType>(ColumnMapVisitor<TArgType> visitor, TArgType arg); /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TResultType"></typeparam> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> /// <returns></returns> [DebuggerNonUserCode] internal abstract TResultType Accept<TResultType, TArgType>(ColumnMapVisitorWithResults<TResultType, TArgType> visitor, TArgType arg); } /// <summary> /// Base class for simple column maps; can be either a VarRefColumnMap or /// ScalarColumnMap; the former is used pretty much throughout the PlanCompiler, /// while the latter will only be used once we generate the final Plan. /// </summary> internal abstract class SimpleColumnMap : ColumnMap { /// <summary> /// Basic constructor /// </summary> /// <param name="type">datatype for this column</param> /// <param name="name">column name</param> internal SimpleColumnMap(md.TypeUsage type, string name) : base(type, name) { } } /// <summary> /// Column map for a scalar column - maps 1-1 with a column from a /// row of the underlying reader /// </summary> internal class ScalarColumnMap : SimpleColumnMap { private int m_commandId; private int m_columnPos; /// <summary> /// Basic constructor /// </summary> /// <param name="type">datatype for this column</param> /// <param name="name">column name</param> /// <param name="commandId">Underlying command to locate this column</param> /// <param name="columnPos">Position in underlying reader</param> internal ScalarColumnMap(md.TypeUsage type, string name, int commandId, int columnPos) : base(type, name) { Debug.Assert(commandId >= 0, "invalid command id"); Debug.Assert(columnPos >= 0, "invalid column position"); m_commandId = commandId; m_columnPos = columnPos; } /// <summary> /// The command (reader, really) to get this column value from /// </summary> internal int CommandId { get { return m_commandId; } } /// <summary> /// Column position within the reader of the command /// </summary> internal int ColumnPos { get { return m_columnPos; } } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override void Accept<TArgType>(ColumnMapVisitor<TArgType> visitor, TArgType arg) { visitor.Visit(this, arg); } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TResultType"></typeparam> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override TResultType Accept<TResultType, TArgType>(ColumnMapVisitorWithResults<TResultType, TArgType> visitor, TArgType arg) { return visitor.Visit(this, arg); } /// <summary> /// Debugging support /// </summary> /// <returns></returns> public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "S({0},{1})", this.CommandId, this.ColumnPos); } } #region Structured Columns /// <summary> /// Represents a column map for a structured column /// </summary> internal abstract class StructuredColumnMap : ColumnMap { private readonly ColumnMap[] m_properties; /// <summary> /// Structured columnmap constructor /// </summary> /// <param name="type">datatype for this column</param> /// <param name="name">column name</param> /// <param name="properties">list of properties</param> internal StructuredColumnMap(md.TypeUsage type, string name, ColumnMap[] properties) : base(type, name) { Debug.Assert(properties != null, "No properties (gasp!) for a structured type"); m_properties = properties; } /// <summary> /// Get the null sentinel column, if any. Virtual so only derived column map /// types that can have NullSentinel have to provide storage, etc. /// </summary> virtual internal SimpleColumnMap NullSentinel { get { return null; } } /// <summary> /// Get the list of properties that constitute this structured type /// </summary> internal ColumnMap[] Properties { get { return m_properties; } } /// <summary> /// Debugging support /// </summary> /// <returns></returns> public override string ToString() { StringBuilder sb = new StringBuilder(); string separator = String.Empty; sb.Append("{"); foreach (ColumnMap c in this.Properties) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}", separator, c); separator = ","; } sb.Append("}"); return sb.ToString(); } } /// <summary> /// Represents a record (an untyped structured column) /// </summary> internal class RecordColumnMap : StructuredColumnMap { private SimpleColumnMap m_nullSentinel; /// <summary> /// Constructor for a record column map /// </summary> /// <param name="type">Datatype of this column</param> /// <param name="name">column name</param> /// <param name="properties">List of ColumnMaps - one for each property</param> internal RecordColumnMap(md.TypeUsage type, string name, ColumnMap[] properties, SimpleColumnMap nullSentinel) : base(type, name, properties) { m_nullSentinel = nullSentinel; } /// <summary> /// Get the type Nullability column /// </summary> internal override SimpleColumnMap NullSentinel { get { return m_nullSentinel; } } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override void Accept<TArgType>(ColumnMapVisitor<TArgType> visitor, TArgType arg) { visitor.Visit(this, arg); } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TResultType"></typeparam> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override TResultType Accept<TResultType, TArgType>(ColumnMapVisitorWithResults<TResultType, TArgType> visitor, TArgType arg) { return visitor.Visit(this, arg); } } /// <summary> /// Column map for a "typed" column /// - either an entity type or a complex type /// </summary> internal abstract class TypedColumnMap : StructuredColumnMap { /// <summary> /// Typed columnMap constructor /// </summary> /// <param name="type">Datatype of column</param> /// <param name="name">column name</param> /// <param name="properties">List of column maps - one for each property</param> internal TypedColumnMap(md.TypeUsage type, string name, ColumnMap[] properties) : base(type, name, properties) { } } /// <summary> /// Represents a polymorphic typed column - either an entity or /// a complex type. /// </summary> internal class SimplePolymorphicColumnMap : TypedColumnMap { private SimpleColumnMap m_typeDiscriminator; private Dictionary<object, TypedColumnMap> m_typedColumnMap; /// <summary> /// Internal constructor /// </summary> /// <param name="type">datatype of the column</param> /// <param name="name">column name</param> /// <param name="typeDiscriminator">column map for type discriminator column</param> /// <param name="baseTypeColumns">base list of fields common to all types</param> /// <param name="typeChoices">map from type discriminator value->columnMap</param> internal SimplePolymorphicColumnMap(md.TypeUsage type, string name, ColumnMap[] baseTypeColumns, SimpleColumnMap typeDiscriminator, Dictionary<object, TypedColumnMap> typeChoices) : base(type, name, baseTypeColumns) { Debug.Assert(typeDiscriminator != null, "Must specify a type discriminator column"); Debug.Assert(typeChoices != null, "No type choices for polymorphic column"); m_typedColumnMap = typeChoices; m_typeDiscriminator = typeDiscriminator; } /// <summary> /// Get the type discriminator column /// </summary> internal SimpleColumnMap TypeDiscriminator { get { return m_typeDiscriminator; } } /// <summary> /// Get the type mapping /// </summary> internal Dictionary<object, TypedColumnMap> TypeChoices { get { return m_typedColumnMap; } } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override void Accept<TArgType>(ColumnMapVisitor<TArgType> visitor, TArgType arg) { visitor.Visit(this, arg); } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TResultType"></typeparam> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override TResultType Accept<TResultType, TArgType>(ColumnMapVisitorWithResults<TResultType, TArgType> visitor, TArgType arg) { return visitor.Visit(this, arg); } /// <summary> /// Debugging support /// </summary> /// <returns></returns> public override string ToString() { StringBuilder sb = new StringBuilder(); string separator = String.Empty; sb.AppendFormat(CultureInfo.InvariantCulture, "P{{TypeId={0}, ", this.TypeDiscriminator); foreach (KeyValuePair<object, TypedColumnMap> kv in this.TypeChoices) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}({1},{2})", separator, kv.Key, kv.Value); separator = ","; } sb.Append("}"); return sb.ToString(); } } /// <summary> /// Represents a function import column map. /// </summary> internal class MultipleDiscriminatorPolymorphicColumnMap : TypedColumnMap { private readonly SimpleColumnMap[] m_typeDiscriminators; private readonly Dictionary<md.EntityType, TypedColumnMap> m_typeChoices; private readonly Func<object[], md.EntityType> m_discriminate; /// <summary> /// Internal constructor /// </summary> internal MultipleDiscriminatorPolymorphicColumnMap(md.TypeUsage type, string name, ColumnMap[] baseTypeColumns, SimpleColumnMap[] typeDiscriminators, Dictionary<md.EntityType, TypedColumnMap> typeChoices, Func<object[], md.EntityType> discriminate) : base(type, name, baseTypeColumns) { Debug.Assert(typeDiscriminators != null, "Must specify type discriminator columns"); Debug.Assert(typeChoices != null, "No type choices for polymorphic column"); Debug.Assert(discriminate != null, "Must specify discriminate"); m_typeDiscriminators = typeDiscriminators; m_typeChoices = typeChoices; m_discriminate = discriminate; } /// <summary> /// Get the type discriminator column /// </summary> internal SimpleColumnMap[] TypeDiscriminators { get { return m_typeDiscriminators; } } /// <summary> /// Get the type mapping /// </summary> internal Dictionary<md.EntityType, TypedColumnMap> TypeChoices { get { return m_typeChoices; } } /// <summary> /// Gets discriminator delegate /// </summary> internal Func<object[], md.EntityType> Discriminate { get { return m_discriminate; } } /// <summary> /// Visitor Design Pattern /// </summary> [DebuggerNonUserCode] internal override void Accept<TArgType>(ColumnMapVisitor<TArgType> visitor, TArgType arg) { visitor.Visit(this, arg); } /// <summary> /// Visitor Design Pattern /// </summary> [DebuggerNonUserCode] internal override TResultType Accept<TResultType, TArgType>(ColumnMapVisitorWithResults<TResultType, TArgType> visitor, TArgType arg) { return visitor.Visit(this, arg); } /// <summary> /// Debugging support /// </summary> public override string ToString() { StringBuilder sb = new StringBuilder(); string separator = String.Empty; sb.AppendFormat(CultureInfo.InvariantCulture, "P{{TypeId=<{0}>, ", StringUtil.ToCommaSeparatedString(this.TypeDiscriminators)); foreach (var kv in this.TypeChoices) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}(<{1}>,{2})", separator, kv.Key, kv.Value); separator = ","; } sb.Append("}"); return sb.ToString(); } } /// <summary> /// Represents a column map for a specific complextype /// </summary> internal class ComplexTypeColumnMap : TypedColumnMap { private SimpleColumnMap m_nullSentinel; /// <summary> /// Constructor /// </summary> /// <param name="type">column Datatype</param> /// <param name="name">column name</param> /// <param name="properties">list of properties</param> internal ComplexTypeColumnMap(md.TypeUsage type, string name, ColumnMap[] properties, SimpleColumnMap nullSentinel) : base(type, name, properties) { m_nullSentinel = nullSentinel; } /// <summary> /// Get the type Nullability column /// </summary> internal override SimpleColumnMap NullSentinel { get { return m_nullSentinel; } } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override void Accept<TArgType>(ColumnMapVisitor<TArgType> visitor, TArgType arg) { visitor.Visit(this, arg); } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TResultType"></typeparam> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override TResultType Accept<TResultType, TArgType>(ColumnMapVisitorWithResults<TResultType, TArgType> visitor, TArgType arg) { return visitor.Visit(this, arg); } /// <summary> /// Debugging support /// </summary> /// <returns></returns> public override string ToString() { string str = String.Format(CultureInfo.InvariantCulture, "C{0}", base.ToString()); return str; } } /// <summary> /// Represents a column map for a specific entity type /// </summary> internal class EntityColumnMap : TypedColumnMap { private EntityIdentity m_entityIdentity; /// <summary> /// constructor /// </summary> /// <param name="type">column datatype</param> /// <param name="name">column name</param> /// <param name="entityIdentity">entity identity information</param> /// <param name="properties">list of properties</param> internal EntityColumnMap(md.TypeUsage type, string name, ColumnMap[] properties, EntityIdentity entityIdentity) : base(type, name, properties) { Debug.Assert(entityIdentity != null, "Must specify an entity identity"); m_entityIdentity = entityIdentity; } /// <summary> /// Get the entity identity information /// </summary> internal EntityIdentity EntityIdentity { get { return m_entityIdentity; } } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override void Accept<TArgType>(ColumnMapVisitor<TArgType> visitor, TArgType arg) { visitor.Visit(this, arg); } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TResultType"></typeparam> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override TResultType Accept<TResultType, TArgType>(ColumnMapVisitorWithResults<TResultType, TArgType> visitor, TArgType arg) { return visitor.Visit(this, arg); } /// <summary> /// Debugging support /// </summary> /// <returns></returns> public override string ToString() { string str = String.Format(CultureInfo.InvariantCulture, "E{0}", base.ToString()); return str; } } /// <summary> /// A column map that represents a ref column. /// </summary> internal class RefColumnMap: ColumnMap { private EntityIdentity m_entityIdentity; /// <summary> /// Constructor for a ref column /// </summary> /// <param name="type">column datatype</param> /// <param name="name">column name</param> /// <param name="entityIdentity">identity information for this entity</param> internal RefColumnMap(md.TypeUsage type, string name, EntityIdentity entityIdentity) : base(type, name) { Debug.Assert(entityIdentity != null, "Must specify entity identity information"); m_entityIdentity = entityIdentity; } /// <summary> /// Get the entity identity information for this ref /// </summary> internal EntityIdentity EntityIdentity { get { return m_entityIdentity; } } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override void Accept<TArgType>(ColumnMapVisitor<TArgType> visitor, TArgType arg) { visitor.Visit(this, arg); } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TResultType"></typeparam> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override TResultType Accept<TResultType, TArgType>(ColumnMapVisitorWithResults<TResultType, TArgType> visitor, TArgType arg) { return visitor.Visit(this, arg); } } #endregion #region Collections /// <summary> /// Represents a column map for a collection column. /// The "element" represents the element of the collection - usually a Structured /// type, but occasionally a collection/simple type as well. /// The "ForeignKeys" property is optional (but usually necessary) to determine the /// elements of the collection. /// </summary> internal abstract class CollectionColumnMap : ColumnMap { private readonly ColumnMap m_element; private readonly SimpleColumnMap[] m_foreignKeys; private readonly SimpleColumnMap[] m_keys; /// <summary> /// Constructor /// </summary> /// <param name="type">datatype of column</param> /// <param name="name">column name</param> /// <param name="elementMap">column map for collection element</param> /// <param name="keys">List of keys</param> /// <param name="foreignKeys">List of foreign keys</param> internal CollectionColumnMap(md.TypeUsage type, string name, ColumnMap elementMap, SimpleColumnMap[] keys, SimpleColumnMap[] foreignKeys) : base(type, name) { Debug.Assert(elementMap != null, "Must specify column map for element"); m_element = elementMap; m_keys = keys ?? new SimpleColumnMap[0]; m_foreignKeys = foreignKeys ?? new SimpleColumnMap[0]; } /// <summary> /// Get the list of columns that may comprise the foreign key /// </summary> internal SimpleColumnMap[] ForeignKeys { get { return m_foreignKeys; } } /// <summary> /// Get the list of columns that may comprise the key /// </summary> internal SimpleColumnMap[] Keys { get { return m_keys; } } /// <summary> /// Get the column map describing the collection element /// </summary> internal ColumnMap Element { get { return m_element; } } } /// <summary> /// Represents a "simple" collection map. /// </summary> internal class SimpleCollectionColumnMap : CollectionColumnMap { /// <summary> /// Basic constructor /// </summary> /// <param name="type">Column datatype</param> /// <param name="name">column name</param> /// <param name="elementMap">column map for the element of the collection</param> /// <param name="keys">list of key columns</param> /// <param name="foreignKeys">list of foreign key columns</param> internal SimpleCollectionColumnMap(md.TypeUsage type, string name, ColumnMap elementMap, SimpleColumnMap[] keys, SimpleColumnMap[] foreignKeys) : base(type, name, elementMap, keys, foreignKeys) { } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override void Accept<TArgType>(ColumnMapVisitor<TArgType> visitor, TArgType arg) { visitor.Visit(this, arg); } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TResultType"></typeparam> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override TResultType Accept<TResultType, TArgType>(ColumnMapVisitorWithResults<TResultType, TArgType> visitor, TArgType arg) { return visitor.Visit(this, arg); } } /// <summary> /// Represents a "discriminated" collection column. /// This represents a scenario when multiple collections are represented /// at the same level of the container row, and there is a need to distinguish /// between these collections /// </summary> internal class DiscriminatedCollectionColumnMap : CollectionColumnMap { private SimpleColumnMap m_discriminator; private object m_discriminatorValue; /// <summary> /// Internal constructor /// </summary> /// <param name="type">Column datatype</param> /// <param name="name">column name</param> /// <param name="elementMap">column map for collection element</param> /// <param name="keys">Keys for the collection</param> /// <param name="foreignKeys">Foreign keys for the collection</param> /// <param name="discriminator">Discriminator column map</param> /// <param name="discriminatorValue">Discriminator value</param> internal DiscriminatedCollectionColumnMap(md.TypeUsage type, string name, ColumnMap elementMap, SimpleColumnMap[] keys, SimpleColumnMap[] foreignKeys, SimpleColumnMap discriminator, object discriminatorValue) : base(type, name, elementMap, keys, foreignKeys) { Debug.Assert(discriminator != null, "Must specify a column map for the collection discriminator"); Debug.Assert(discriminatorValue != null, "Must specify a discriminator value"); m_discriminator = discriminator; m_discriminatorValue = discriminatorValue; } /// <summary> /// Get the column that describes the discriminator /// </summary> internal SimpleColumnMap Discriminator { get { return m_discriminator; } } /// <summary> /// Get the discriminator value /// </summary> internal object DiscriminatorValue { get { return m_discriminatorValue; } } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override void Accept<TArgType>(ColumnMapVisitor<TArgType> visitor, TArgType arg) { visitor.Visit(this, arg); } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TResultType"></typeparam> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override TResultType Accept<TResultType, TArgType>(ColumnMapVisitorWithResults<TResultType, TArgType> visitor, TArgType arg) { return visitor.Visit(this, arg); } /// <summary> /// Debugging support /// </summary> /// <returns></returns> public override string ToString() { string str = String.Format(CultureInfo.InvariantCulture, "M{{{0}}}", this.Element.ToString()); return str; } } #endregion #region EntityIdentity /// <summary> /// Abstract base class representing entity identity. Used by both /// EntityColumnMap and RefColumnMap. /// An EntityIdentity captures two pieces of information - the list of keys /// that uniquely identify an entity within an entityset, and the the entityset /// itself. /// </summary> internal abstract class EntityIdentity { private readonly SimpleColumnMap[] m_keys; // list of keys /// <summary> /// Simple constructor - gets a list of key columns /// </summary> /// <param name="keyColumns"></param> internal EntityIdentity(SimpleColumnMap[] keyColumns) { Debug.Assert(keyColumns != null, "Must specify column maps for key columns"); m_keys = keyColumns; } /// <summary> /// Get the key columns /// </summary> internal SimpleColumnMap[] Keys { get { return m_keys; } } } /// <summary> /// This class is a "simple" representation of the entity identity, where the /// entityset containing the entity is known a priori. This may be because /// there is exactly one entityset for the entity; or because it is inferrable /// from the query that only one entityset is relevant here /// </summary> internal class SimpleEntityIdentity : EntityIdentity { private md.EntitySet m_entitySet; // the entity set /// <summary> /// Basic constructor. /// Note: the entitySet may be null - in which case, we are referring to /// a transient entity /// </summary> /// <param name="entitySet">The entityset</param> /// <param name="keyColumns">key columns of the entity</param> internal SimpleEntityIdentity(md.EntitySet entitySet, SimpleColumnMap[] keyColumns) : base(keyColumns) { // the entityset may be null m_entitySet = entitySet; } /// <summary> /// The entityset containing the entity /// </summary> internal md.EntitySet EntitySet { get { return m_entitySet; } } /// <summary> /// Debugging support /// </summary> /// <returns></returns> public override string ToString() { StringBuilder sb = new StringBuilder(); string separator = String.Empty; sb.AppendFormat(CultureInfo.InvariantCulture, "[(ES={0}) (Keys={", this.EntitySet.Name); foreach (SimpleColumnMap c in this.Keys) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}", separator, c); separator = ","; } sb.AppendFormat(CultureInfo.InvariantCulture, "})]"); return sb.ToString(); } } /// <summary> /// This class also represents entity identity. However, this class addresses /// those scenarios where the entityset for the entity is not uniquely known /// a priori. Instead, the query is annotated with information, and based on /// the resulting information, the appropriate entityset is identified. /// Specifically, the specific entityset is represented as a SimpleColumnMap /// in the query. The value of that column is used to look up a dictionary, /// and then identify the appropriate entity set. /// It is entirely possible that no entityset may be located for the entity /// instance - this represents a transient entity instance /// </summary> internal class DiscriminatedEntityIdentity : EntityIdentity { private SimpleColumnMap m_entitySetColumn; // (optional) column map representing the entity set private md.EntitySet[] m_entitySetMap; // optional dictionary that maps values to entitysets /// <summary> /// Simple constructor /// </summary> /// <param name="entitySetColumn">column map representing the entityset</param> /// <param name="entitySetMap">Map from value -> the appropriate entityset</param> /// <param name="keyColumns">list of key columns</param> internal DiscriminatedEntityIdentity(SimpleColumnMap entitySetColumn, md.EntitySet[] entitySetMap, SimpleColumnMap[] keyColumns) : base(keyColumns) { Debug.Assert(entitySetColumn != null, "Must specify a column map to identify the entity set"); Debug.Assert(entitySetMap != null, "Must specify a dictionary to look up entitysets"); m_entitySetColumn = entitySetColumn; m_entitySetMap = entitySetMap; } /// <summary> /// Get the column map representing the entityset /// </summary> internal SimpleColumnMap EntitySetColumnMap { get { return m_entitySetColumn; } } /// <summary> /// Return the entityset map /// </summary> internal md.EntitySet[] EntitySetMap { get { return m_entitySetMap; } } /// <summary> /// Debugging support /// </summary> /// <returns></returns> public override string ToString() { StringBuilder sb = new StringBuilder(); string separator = String.Empty; sb.AppendFormat(CultureInfo.InvariantCulture, "[(Keys={"); foreach (SimpleColumnMap c in this.Keys) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}", separator, c); separator = ","; } sb.AppendFormat(CultureInfo.InvariantCulture, "})]"); return sb.ToString(); } } #endregion #region internal classes /// <summary> /// A VarRefColumnMap is our intermediate representation of a ColumnMap. /// Eventually, this gets translated into a regular ColumnMap - during the CodeGen phase /// </summary> internal class VarRefColumnMap : SimpleColumnMap { #region Public Methods /// <summary> /// Get the Var that produces this column's value /// </summary> internal InternalTrees.Var Var { get { return m_var; } } #endregion #region Constructors /// <summary> /// Simple constructor /// </summary> /// <param name="type">datatype of this Var</param> /// <param name="name">the name of the column</param> /// <param name="v">the var producing the value for this column</param> internal VarRefColumnMap(md.TypeUsage type, string name, InternalTrees.Var v) : base(type, name) { m_var = v; } internal VarRefColumnMap(InternalTrees.Var v) : this(v.Type, null, v) { } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override void Accept<TArgType>(ColumnMapVisitor<TArgType> visitor, TArgType arg) { visitor.Visit(this, arg); } /// <summary> /// Visitor Design Pattern /// </summary> /// <typeparam name="TResultType"></typeparam> /// <typeparam name="TArgType"></typeparam> /// <param name="visitor"></param> /// <param name="arg"></param> [DebuggerNonUserCode] internal override TResultType Accept<TResultType, TArgType>(ColumnMapVisitorWithResults<TResultType, TArgType> visitor, TArgType arg) { return visitor.Visit(this, arg); } /// <summary> /// Debugging support /// </summary> /// <returns></returns> public override string ToString() { return this.IsNamed ? this.Name : String.Format(CultureInfo.InvariantCulture, "{0}", m_var.Id); } #endregion #region private state private InternalTrees.Var m_var; #endregion } #endregion }
namespace Fonet.Render.Pdf.Fonts { internal class TimesItalic : Base14Font { private static readonly int[] CodePointWidths; private static readonly CodePointMapping DefaultMapping = CodePointMapping.GetMapping("WinAnsiEncoding"); public TimesItalic() : base("Times-Italic", "WinAnsiEncoding", 653, 683, -205, 32, 255, CodePointWidths, DefaultMapping) {} static TimesItalic() { CodePointWidths = new int[256]; CodePointWidths[0x0041] = 611; CodePointWidths[0x00C6] = 889; CodePointWidths[0x00C1] = 611; CodePointWidths[0x00C2] = 611; CodePointWidths[0x00C4] = 611; CodePointWidths[0x00C0] = 611; CodePointWidths[0x00C5] = 611; CodePointWidths[0x00C3] = 611; CodePointWidths[0x0042] = 611; CodePointWidths[0x0043] = 667; CodePointWidths[0x00C7] = 667; CodePointWidths[0x0044] = 722; CodePointWidths[0x0045] = 611; CodePointWidths[0x00C9] = 611; CodePointWidths[0x00CA] = 611; CodePointWidths[0x00CB] = 611; CodePointWidths[0x00C8] = 611; CodePointWidths[0x00D0] = 722; CodePointWidths[0x0080] = 500; CodePointWidths[0x0046] = 611; CodePointWidths[0x0047] = 722; CodePointWidths[0x0048] = 722; CodePointWidths[0x0049] = 333; CodePointWidths[0x00CD] = 333; CodePointWidths[0x00CE] = 333; CodePointWidths[0x00CF] = 333; CodePointWidths[0x00CC] = 333; CodePointWidths[0x004A] = 444; CodePointWidths[0x004B] = 667; CodePointWidths[0x004C] = 556; CodePointWidths[0x004D] = 833; CodePointWidths[0x004E] = 667; CodePointWidths[0x00D1] = 667; CodePointWidths[0x004F] = 722; CodePointWidths[0x008C] = 944; CodePointWidths[0x00D3] = 722; CodePointWidths[0x00D4] = 722; CodePointWidths[0x00D6] = 722; CodePointWidths[0x00D2] = 722; CodePointWidths[0x00D8] = 722; CodePointWidths[0x00D5] = 722; CodePointWidths[0x0050] = 611; CodePointWidths[0x0051] = 722; CodePointWidths[0x0052] = 611; CodePointWidths[0x0053] = 500; CodePointWidths[0x008A] = 500; CodePointWidths[0x0054] = 556; CodePointWidths[0x00DE] = 611; CodePointWidths[0x0055] = 722; CodePointWidths[0x00DA] = 722; CodePointWidths[0x00DB] = 722; CodePointWidths[0x00DC] = 722; CodePointWidths[0x00D9] = 722; CodePointWidths[0x0056] = 611; CodePointWidths[0x0057] = 833; CodePointWidths[0x0058] = 611; CodePointWidths[0x0059] = 556; CodePointWidths[0x00DD] = 556; CodePointWidths[0x009F] = 556; CodePointWidths[0x005A] = 556; CodePointWidths[0x0061] = 500; CodePointWidths[0x00E1] = 500; CodePointWidths[0x00E2] = 500; CodePointWidths[0x00B4] = 333; CodePointWidths[0x00E4] = 500; CodePointWidths[0x00E6] = 667; CodePointWidths[0x00E0] = 500; CodePointWidths[0x0026] = 778; CodePointWidths[0x00E5] = 500; CodePointWidths[0x005E] = 422; CodePointWidths[0x007E] = 541; CodePointWidths[0x002A] = 500; CodePointWidths[0x0040] = 920; CodePointWidths[0x00E3] = 500; CodePointWidths[0x0062] = 500; CodePointWidths[0x005C] = 278; CodePointWidths[0x007C] = 275; CodePointWidths[0x007B] = 400; CodePointWidths[0x007D] = 400; CodePointWidths[0x005B] = 389; CodePointWidths[0x005D] = 389; CodePointWidths[0x00A6] = 275; CodePointWidths[0x0095] = 350; CodePointWidths[0x0063] = 444; CodePointWidths[0x00E7] = 444; CodePointWidths[0x00B8] = 333; CodePointWidths[0x00A2] = 500; CodePointWidths[0x0088] = 333; CodePointWidths[0x003A] = 333; CodePointWidths[0x002C] = 250; CodePointWidths[0x00A9] = 760; CodePointWidths[0x00A4] = 500; CodePointWidths[0x0064] = 500; CodePointWidths[0x0086] = 500; CodePointWidths[0x0087] = 500; CodePointWidths[0x00B0] = 400; CodePointWidths[0x00A8] = 333; CodePointWidths[0x00F7] = 675; CodePointWidths[0x0024] = 500; CodePointWidths[0x0065] = 444; CodePointWidths[0x00E9] = 444; CodePointWidths[0x00EA] = 444; CodePointWidths[0x00EB] = 444; CodePointWidths[0x00E8] = 444; CodePointWidths[0x0038] = 500; CodePointWidths[0x0085] = 889; CodePointWidths[0x0097] = 889; CodePointWidths[0x0096] = 500; CodePointWidths[0x003D] = 675; CodePointWidths[0x00F0] = 500; CodePointWidths[0x0021] = 333; CodePointWidths[0x00A1] = 389; CodePointWidths[0x0066] = 278; CodePointWidths[0x0035] = 500; CodePointWidths[0x0083] = 500; CodePointWidths[0x0034] = 500; CodePointWidths[0xA4] = 167; CodePointWidths[0x0067] = 500; CodePointWidths[0x00DF] = 500; CodePointWidths[0x0060] = 333; CodePointWidths[0x003E] = 675; CodePointWidths[0x00AB] = 500; CodePointWidths[0x00BB] = 500; CodePointWidths[0x008B] = 333; CodePointWidths[0x009B] = 333; CodePointWidths[0x0068] = 500; CodePointWidths[0x002D] = 333; CodePointWidths[0x0069] = 278; CodePointWidths[0x00ED] = 278; CodePointWidths[0x00EE] = 278; CodePointWidths[0x00EF] = 278; CodePointWidths[0x00EC] = 278; CodePointWidths[0x006A] = 278; CodePointWidths[0x006B] = 444; CodePointWidths[0x006C] = 278; CodePointWidths[0x003C] = 675; CodePointWidths[0x00AC] = 675; CodePointWidths[0x006D] = 722; CodePointWidths[0x00AF] = 333; CodePointWidths[0x2D] = 675; CodePointWidths[0x00B5] = 500; CodePointWidths[0x00D7] = 675; CodePointWidths[0x006E] = 500; CodePointWidths[0x0039] = 500; CodePointWidths[0x00F1] = 500; CodePointWidths[0x0023] = 500; CodePointWidths[0x006F] = 500; CodePointWidths[0x00F3] = 500; CodePointWidths[0x00F4] = 500; CodePointWidths[0x00F6] = 500; CodePointWidths[0x009C] = 667; CodePointWidths[0x00F2] = 500; CodePointWidths[0x0031] = 500; CodePointWidths[0x00BD] = 750; CodePointWidths[0x00BC] = 750; CodePointWidths[0x00B9] = 300; CodePointWidths[0x00AA] = 276; CodePointWidths[0x00BA] = 310; CodePointWidths[0x00F8] = 500; CodePointWidths[0x00F5] = 500; CodePointWidths[0x0070] = 500; CodePointWidths[0x00B6] = 523; CodePointWidths[0x0028] = 333; CodePointWidths[0x0029] = 333; CodePointWidths[0x0025] = 833; CodePointWidths[0x002E] = 250; CodePointWidths[0x00B7] = 250; CodePointWidths[0x0089] = 1000; CodePointWidths[0x002B] = 675; CodePointWidths[0x00B1] = 675; CodePointWidths[0x0071] = 500; CodePointWidths[0x003F] = 500; CodePointWidths[0x00BF] = 500; CodePointWidths[0x0022] = 420; CodePointWidths[0x0084] = 556; CodePointWidths[0x0093] = 556; CodePointWidths[0x0094] = 556; CodePointWidths[0x0091] = 333; CodePointWidths[0x0092] = 333; CodePointWidths[0x0082] = 333; CodePointWidths[0x0027] = 214; CodePointWidths[0x0072] = 389; CodePointWidths[0x00AE] = 760; CodePointWidths[0x0073] = 389; CodePointWidths[0x009A] = 389; CodePointWidths[0x00A7] = 500; CodePointWidths[0x003B] = 333; CodePointWidths[0x0037] = 500; CodePointWidths[0x0036] = 500; CodePointWidths[0x002F] = 278; CodePointWidths[0x0020] = 250; CodePointWidths[0x00A0] = 250; CodePointWidths[0x00A3] = 500; CodePointWidths[0x0074] = 278; CodePointWidths[0x00FE] = 500; CodePointWidths[0x0033] = 500; CodePointWidths[0x00BE] = 750; CodePointWidths[0x00B3] = 300; CodePointWidths[0x0098] = 333; CodePointWidths[0x0099] = 980; CodePointWidths[0x0032] = 500; CodePointWidths[0x00B2] = 300; CodePointWidths[0x0075] = 500; CodePointWidths[0x00FA] = 500; CodePointWidths[0x00FB] = 500; CodePointWidths[0x00FC] = 500; CodePointWidths[0x00F9] = 500; CodePointWidths[0x005F] = 500; CodePointWidths[0x0076] = 444; CodePointWidths[0x0077] = 667; CodePointWidths[0x0078] = 444; CodePointWidths[0x0079] = 444; CodePointWidths[0x00FD] = 444; CodePointWidths[0x00FF] = 444; CodePointWidths[0x00A5] = 500; CodePointWidths[0x007A] = 389; CodePointWidths[0x0030] = 500; } } }
// DeflaterHuffman.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace GameAnalyticsSDK.Net.Utilities.Zip.Compression { /// <summary> /// This is the DeflaterHuffman class. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of deflate and setInput. /// /// author of the original java version : Jochen Hoenicke /// </summary> public class DeflaterHuffman { static int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6); static int LITERAL_NUM = 286; static int DIST_NUM = 30; static int BITLEN_NUM = 19; static int REP_3_6 = 16; static int REP_3_10 = 17; static int REP_11_138 = 18; static int EOF_SYMBOL = 256; static int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static byte[] bit4Reverse = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; /// <summary> /// Not documented /// </summary> public class Tree { /// <summary> /// Not documented /// </summary> public short[] freqs; /// <summary> /// Not documented /// </summary> public byte[] length; /// <summary> /// Not documented /// </summary> public int minNumCodes; /// <summary> /// Not documented /// </summary> public int numCodes; short[] codes; int[] bl_counts; int maxLength; DeflaterHuffman dh; /// <summary> /// Not documented /// </summary> public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength) { this.dh = dh; this.minNumCodes = minCodes; this.maxLength = maxLength; freqs = new short[elems]; bl_counts = new int[maxLength]; } /// <summary> /// Resets the internal state of the tree /// </summary> public void Reset() { for (int i = 0; i < freqs.Length; i++) { freqs[i] = 0; } codes = null; length = null; } /// <summary> /// Not documented /// </summary> public void WriteSymbol(int code) { // if (DeflaterConstants.DEBUGGING) { // freqs[code]--; // // Console.Write("writeSymbol("+freqs.length+","+code+"): "); // } dh.pending.WriteBits(codes[code] & 0xffff, length[code]); } /// <summary> /// Check that at least one frequency is non-zero /// </summary> /// <exception cref="SharpZipBaseException"> /// No frequencies are non-zero /// </exception> public void CheckEmpty() { bool empty = true; for (int i = 0; i < freqs.Length; i++) { if (freqs[i] != 0) { //Console.WriteLine("freqs[" + i + "] == " + freqs[i]); empty = false; } } if (!empty) { throw new SharpZipBaseException("!Empty"); } //Console.WriteLine("checkEmpty suceeded!"); } /// <summary> /// Set static codes and length /// </summary> /// <param name="stCodes">new codes</param> /// <param name="stLength">length for new codes</param> public void SetStaticCodes(short[] stCodes, byte[] stLength) { codes = stCodes; length = stLength; } /// <summary> /// Build dynamic codes and lengths /// </summary> public void BuildCodes() { int numSymbols = freqs.Length; int[] nextCode = new int[maxLength]; int code = 0; codes = new short[freqs.Length]; // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("buildCodes: "+freqs.Length); // } for (int bits = 0; bits < maxLength; bits++) { nextCode[bits] = code; code += bl_counts[bits] << (15 - bits); // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits] // +" nextCode: "+code); // } } if (DeflaterConstants.DEBUGGING && code != 65536) { throw new SharpZipBaseException("Inconsistent bl_counts!"); } for (int i=0; i < numCodes; i++) { int bits = length[i]; if (bits > 0) { // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"), // +bits); // } codes[i] = BitReverse(nextCode[bits-1]); nextCode[bits-1] += 1 << (16 - bits); } } } void BuildLength(int[] childs) { this.length = new byte [freqs.Length]; int numNodes = childs.Length / 2; int numLeafs = (numNodes + 1) / 2; int overflow = 0; for (int i = 0; i < maxLength; i++) { bl_counts[i] = 0; } /* First calculate optimal bit lengths */ int[] lengths = new int[numNodes]; lengths[numNodes-1] = 0; for (int i = numNodes - 1; i >= 0; i--) { if (childs[2*i+1] != -1) { int bitLength = lengths[i] + 1; if (bitLength > maxLength) { bitLength = maxLength; overflow++; } lengths[childs[2*i]] = lengths[childs[2*i+1]] = bitLength; } else { /* A leaf node */ int bitLength = lengths[i]; bl_counts[bitLength - 1]++; this.length[childs[2*i]] = (byte) lengths[i]; } } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Tree "+freqs.Length+" lengths:"); // for (int i=0; i < numLeafs; i++) { // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] // + " len: "+length[childs[2*i]]); // } // } if (overflow == 0) { return; } int incrBitLen = maxLength - 1; do { /* Find the first bit length which could increase: */ while (bl_counts[--incrBitLen] == 0) ; /* Move this node one down and remove a corresponding * amount of overflow nodes. */ do { bl_counts[incrBitLen]--; bl_counts[++incrBitLen]++; overflow -= 1 << (maxLength - 1 - incrBitLen); } while (overflow > 0 && incrBitLen < maxLength - 1); } while (overflow > 0); /* We may have overshot above. Move some nodes from maxLength to * maxLength-1 in that case. */ bl_counts[maxLength-1] += overflow; bl_counts[maxLength-2] -= overflow; /* Now recompute all bit lengths, scanning in increasing * frequency. It is simpler to reconstruct all lengths instead of * fixing only the wrong ones. This idea is taken from 'ar' * written by Haruhiko Okumura. * * The nodes were inserted with decreasing frequency into the childs * array. */ int nodePtr = 2 * numLeafs; for (int bits = maxLength; bits != 0; bits--) { int n = bl_counts[bits-1]; while (n > 0) { int childPtr = 2*childs[nodePtr++]; if (childs[childPtr + 1] == -1) { /* We found another leaf */ length[childs[childPtr]] = (byte) bits; n--; } } } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("*** After overflow elimination. ***"); // for (int i=0; i < numLeafs; i++) { // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] // + " len: "+length[childs[2*i]]); // } // } } /// <summary> /// Not documented /// </summary> public void BuildTree() { int numSymbols = freqs.Length; /* heap is a priority queue, sorted by frequency, least frequent * nodes first. The heap is a binary tree, with the property, that * the parent node is smaller than both child nodes. This assures * that the smallest node is the first parent. * * The binary tree is encoded in an array: 0 is root node and * the nodes 2*n+1, 2*n+2 are the child nodes of node n. */ int[] heap = new int[numSymbols]; int heapLen = 0; int maxCode = 0; for (int n = 0; n < numSymbols; n++) { int freq = freqs[n]; if (freq != 0) { /* Insert n into heap */ int pos = heapLen++; int ppos; while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq) { heap[pos] = heap[ppos]; pos = ppos; } heap[pos] = n; maxCode = n; } } /* We could encode a single literal with 0 bits but then we * don't see the literals. Therefore we force at least two * literals to avoid this case. We don't care about order in * this case, both literals get a 1 bit code. */ while (heapLen < 2) { int node = maxCode < 2 ? ++maxCode : 0; heap[heapLen++] = node; } numCodes = Math.Max(maxCode + 1, minNumCodes); int numLeafs = heapLen; int[] childs = new int[4*heapLen - 2]; int[] values = new int[2*heapLen - 1]; int numNodes = numLeafs; for (int i = 0; i < heapLen; i++) { int node = heap[i]; childs[2*i] = node; childs[2*i+1] = -1; values[i] = freqs[node] << 8; heap[i] = i; } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ do { int first = heap[0]; int last = heap[--heapLen]; /* Propagate the hole to the leafs of the heap */ int ppos = 0; int path = 1; while (path < heapLen) { if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) { path++; } heap[ppos] = heap[path]; ppos = path; path = path * 2 + 1; } /* Now propagate the last element down along path. Normally * it shouldn't go too deep. */ int lastVal = values[last]; while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) { heap[path] = heap[ppos]; } heap[path] = last; int second = heap[0]; /* Create a new node father of first and second */ last = numNodes++; childs[2*last] = first; childs[2*last+1] = second; int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff); values[last] = lastVal = values[first] + values[second] - mindepth + 1; /* Again, propagate the hole to the leafs */ ppos = 0; path = 1; while (path < heapLen) { if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) { path++; } heap[ppos] = heap[path]; ppos = path; path = ppos * 2 + 1; } /* Now propagate the new element down along path */ while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) { heap[path] = heap[ppos]; } heap[path] = last; } while (heapLen > 1); if (heap[0] != childs.Length / 2 - 1) { throw new SharpZipBaseException("Heap invariant violated"); } BuildLength(childs); } /// <summary> /// Get encoded length /// </summary> /// <returns>Encoded length, the sum of frequencies * lengths</returns> public int GetEncodedLength() { int len = 0; for (int i = 0; i < freqs.Length; i++) { len += freqs[i] * length[i]; } return len; } /// <summary> /// Not documented /// </summary> public void CalcBLFreq(Tree blTree) { int max_count; /* max repeat count */ int min_count; /* min repeat count */ int count; /* repeat count of the current code */ int curlen = -1; /* length of current code */ int i = 0; while (i < numCodes) { count = 1; int nextlen = length[i]; if (nextlen == 0) { max_count = 138; min_count = 3; } else { max_count = 6; min_count = 3; if (curlen != nextlen) { blTree.freqs[nextlen]++; count = 0; } } curlen = nextlen; i++; while (i < numCodes && curlen == length[i]) { i++; if (++count >= max_count) { break; } } if (count < min_count) { blTree.freqs[curlen] += (short)count; } else if (curlen != 0) { blTree.freqs[REP_3_6]++; } else if (count <= 10) { blTree.freqs[REP_3_10]++; } else { blTree.freqs[REP_11_138]++; } } } /// <summary> /// Write tree values /// </summary> /// <param name="blTree">Tree to write</param> public void WriteTree(Tree blTree) { int max_count; /* max repeat count */ int min_count; /* min repeat count */ int count; /* repeat count of the current code */ int curlen = -1; /* length of current code */ int i = 0; while (i < numCodes) { count = 1; int nextlen = length[i]; if (nextlen == 0) { max_count = 138; min_count = 3; } else { max_count = 6; min_count = 3; if (curlen != nextlen) { blTree.WriteSymbol(nextlen); count = 0; } } curlen = nextlen; i++; while (i < numCodes && curlen == length[i]) { i++; if (++count >= max_count) { break; } } if (count < min_count) { while (count-- > 0) { blTree.WriteSymbol(curlen); } } else if (curlen != 0) { blTree.WriteSymbol(REP_3_6); dh.pending.WriteBits(count - 3, 2); } else if (count <= 10) { blTree.WriteSymbol(REP_3_10); dh.pending.WriteBits(count - 3, 3); } else { blTree.WriteSymbol(REP_11_138); dh.pending.WriteBits(count - 11, 7); } } } } /// <summary> /// Pending buffer to use /// </summary> public DeflaterPending pending; Tree literalTree, distTree, blTree; short[] d_buf; byte[] l_buf; int last_lit; int extra_bits; static short[] staticLCodes; static byte[] staticLLength; static short[] staticDCodes; static byte[] staticDLength; /// <summary> /// Reverse the bits of a 16 bit value. /// </summary> /// <param name="toReverse">Value to reverse bits</param> /// <returns>Value with bits reversed</returns> public static short BitReverse(int toReverse) { return (short) (bit4Reverse[toReverse & 0xF] << 12 | bit4Reverse[(toReverse >> 4) & 0xF] << 8 | bit4Reverse[(toReverse >> 8) & 0xF] << 4 | bit4Reverse[toReverse >> 12]); } static DeflaterHuffman() { /* See RFC 1951 3.2.6 */ /* Literal codes */ staticLCodes = new short[LITERAL_NUM]; staticLLength = new byte[LITERAL_NUM]; int i = 0; while (i < 144) { staticLCodes[i] = BitReverse((0x030 + i) << 8); staticLLength[i++] = 8; } while (i < 256) { staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7); staticLLength[i++] = 9; } while (i < 280) { staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9); staticLLength[i++] = 7; } while (i < LITERAL_NUM) { staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8); staticLLength[i++] = 8; } /* Distant codes */ staticDCodes = new short[DIST_NUM]; staticDLength = new byte[DIST_NUM]; for (i = 0; i < DIST_NUM; i++) { staticDCodes[i] = BitReverse(i << 11); staticDLength[i] = 5; } } /// <summary> /// Construct instance with pending buffer /// </summary> /// <param name="pending">Pending buffer to use</param> public DeflaterHuffman(DeflaterPending pending) { this.pending = pending; literalTree = new Tree(this, LITERAL_NUM, 257, 15); distTree = new Tree(this, DIST_NUM, 1, 15); blTree = new Tree(this, BITLEN_NUM, 4, 7); d_buf = new short[BUFSIZE]; l_buf = new byte [BUFSIZE]; } /// <summary> /// Reset internal state /// </summary> public void Reset() { last_lit = 0; extra_bits = 0; literalTree.Reset(); distTree.Reset(); blTree.Reset(); } int Lcode(int len) { if (len == 255) { return 285; } int code = 257; while (len >= 8) { code += 4; len >>= 1; } return code + len; } int Dcode(int distance) { int code = 0; while (distance >= 4) { code += 2; distance >>= 1; } return code + distance; } /// <summary> /// Write all trees to pending buffer /// </summary> public void SendAllTrees(int blTreeCodes) { blTree.BuildCodes(); literalTree.BuildCodes(); distTree.BuildCodes(); pending.WriteBits(literalTree.numCodes - 257, 5); pending.WriteBits(distTree.numCodes - 1, 5); pending.WriteBits(blTreeCodes - 4, 4); for (int rank = 0; rank < blTreeCodes; rank++) { pending.WriteBits(blTree.length[BL_ORDER[rank]], 3); } literalTree.WriteTree(blTree); distTree.WriteTree(blTree); // if (DeflaterConstants.DEBUGGING) { // blTree.CheckEmpty(); // } } /// <summary> /// Compress current buffer writing data to pending buffer /// </summary> public void CompressBlock() { for (int i = 0; i < last_lit; i++) { int litlen = l_buf[i] & 0xff; int dist = d_buf[i]; if (dist-- != 0) { // if (DeflaterConstants.DEBUGGING) { // Console.Write("["+(dist+1)+","+(litlen+3)+"]: "); // } int lc = Lcode(litlen); literalTree.WriteSymbol(lc); int bits = (lc - 261) / 4; if (bits > 0 && bits <= 5) { pending.WriteBits(litlen & ((1 << bits) - 1), bits); } int dc = Dcode(dist); distTree.WriteSymbol(dc); bits = dc / 2 - 1; if (bits > 0) { pending.WriteBits(dist & ((1 << bits) - 1), bits); } } else { // if (DeflaterConstants.DEBUGGING) { // if (litlen > 32 && litlen < 127) { // Console.Write("("+(char)litlen+"): "); // } else { // Console.Write("{"+litlen+"}: "); // } // } literalTree.WriteSymbol(litlen); } } // if (DeflaterConstants.DEBUGGING) { // Console.Write("EOF: "); // } literalTree.WriteSymbol(EOF_SYMBOL); // if (DeflaterConstants.DEBUGGING) { // literalTree.CheckEmpty(); // distTree.CheckEmpty(); // } } /// <summary> /// Flush block to output with no compression /// </summary> /// <param name="stored">Data to write</param> /// <param name="storedOffset">Index of first byte to write</param> /// <param name="storedLength">Count of bytes to write</param> /// <param name="lastBlock">True if this is the last block</param> public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) { // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Flushing stored block "+ storedLength); // } pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3); pending.AlignToByte(); pending.WriteShort(storedLength); pending.WriteShort(~storedLength); pending.WriteBlock(stored, storedOffset, storedLength); Reset(); } /// <summary> /// Flush block to output with compression /// </summary> /// <param name="stored">Data to flush</param> /// <param name="storedOffset">Index of first byte to flush</param> /// <param name="storedLength">Count of bytes to flush</param> /// <param name="lastBlock">True if this is the last block</param> public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) { literalTree.freqs[EOF_SYMBOL]++; /* Build trees */ literalTree.BuildTree(); distTree.BuildTree(); /* Calculate bitlen frequency */ literalTree.CalcBLFreq(blTree); distTree.CalcBLFreq(blTree); /* Build bitlen tree */ blTree.BuildTree(); int blTreeCodes = 4; for (int i = 18; i > blTreeCodes; i--) { if (blTree.length[BL_ORDER[i]] > 0) { blTreeCodes = i+1; } } int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() + literalTree.GetEncodedLength() + distTree.GetEncodedLength() + extra_bits; int static_len = extra_bits; for (int i = 0; i < LITERAL_NUM; i++) { static_len += literalTree.freqs[i] * staticLLength[i]; } for (int i = 0; i < DIST_NUM; i++) { static_len += distTree.freqs[i] * staticDLength[i]; } if (opt_len >= static_len) { /* Force static trees */ opt_len = static_len; } if (storedOffset >= 0 && (storedLength + 4 < (opt_len >> 3))) { /* Store Block */ // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len // + " <= " + static_len); // } FlushStoredBlock(stored, storedOffset, storedLength, lastBlock); } else if (opt_len == static_len) { /* Encode with static tree */ pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3); literalTree.SetStaticCodes(staticLCodes, staticLLength); distTree.SetStaticCodes(staticDCodes, staticDLength); CompressBlock(); Reset(); } else { /* Encode with dynamic tree */ pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3); SendAllTrees(blTreeCodes); CompressBlock(); Reset(); } } /// <summary> /// Get value indicating if internal buffer is full /// </summary> /// <returns>true if buffer is full</returns> public bool IsFull() { return last_lit >= BUFSIZE; } /// <summary> /// Add literal to buffer /// </summary> /// <param name="lit"></param> /// <returns>Value indicating internal buffer is full</returns> public bool TallyLit(int lit) { // if (DeflaterConstants.DEBUGGING) { // if (lit > 32 && lit < 127) { // //Console.WriteLine("("+(char)lit+")"); // } else { // //Console.WriteLine("{"+lit+"}"); // } // } d_buf[last_lit] = 0; l_buf[last_lit++] = (byte)lit; literalTree.freqs[lit]++; return IsFull(); } /// <summary> /// Add distance code and length to literal and distance trees /// </summary> /// <param name="dist">Distance code</param> /// <param name="len">Length</param> /// <returns>Value indicating if internal buffer is full</returns> public bool TallyDist(int dist, int len) { // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("["+dist+","+len+"]"); // } d_buf[last_lit] = (short)dist; l_buf[last_lit++] = (byte)(len - 3); int lc = Lcode(len - 3); literalTree.freqs[lc]++; if (lc >= 265 && lc < 285) { extra_bits += (lc - 261) / 4; } int dc = Dcode(dist - 1); distTree.freqs[dc]++; if (dc >= 4) { extra_bits += dc / 2 - 1; } return IsFull(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. extern alias Scripting; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Interactive { using RelativePathResolver = Scripting::Microsoft.CodeAnalysis.RelativePathResolver; internal partial class InteractiveHost { /// <summary> /// A remote singleton server-activated object that lives in the interactive host process and controls it. /// </summary> internal sealed class Service : MarshalByRefObject, IDisposable { private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false); private static Control s_control; private InteractiveAssemblyLoader _assemblyLoader; private MetadataShadowCopyProvider _metadataFileProvider; private ReplServiceProvider _replServiceProvider; private InteractiveScriptGlobals _globals; // Session is not thread-safe by itself, and the compilation // and execution of scripts are asynchronous operations. // However since the operations are executed serially, it // is sufficient to lock when creating the async tasks. private readonly object _lastTaskGuard = new object(); private Task<EvaluationState> _lastTask; private struct EvaluationState { internal ImmutableArray<string> SourceSearchPaths; internal ImmutableArray<string> ReferenceSearchPaths; internal string WorkingDirectory; internal readonly ScriptState<object> ScriptStateOpt; internal readonly ScriptOptions ScriptOptions; internal EvaluationState( ScriptState<object> scriptState, ScriptOptions scriptOptions, ImmutableArray<string> sourceSearchPaths, ImmutableArray<string> referenceSearchPaths, string workingDirectory) { ScriptStateOpt = scriptState; ScriptOptions = scriptOptions; SourceSearchPaths = sourceSearchPaths; ReferenceSearchPaths = referenceSearchPaths; WorkingDirectory = workingDirectory; } internal EvaluationState WithScriptState(ScriptState<object> state) { return new EvaluationState( state, ScriptOptions, SourceSearchPaths, ReferenceSearchPaths, WorkingDirectory); } internal EvaluationState WithOptions(ScriptOptions options) { return new EvaluationState( ScriptStateOpt, options, SourceSearchPaths, ReferenceSearchPaths, WorkingDirectory); } } private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create( FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)), FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory())); #region Setup public Service() { var initialState = new EvaluationState( scriptState: null, scriptOptions: ScriptOptions.Default, sourceSearchPaths: ImmutableArray<string>.Empty, referenceSearchPaths: ImmutableArray<string>.Empty, workingDirectory: Directory.GetCurrentDirectory()); _lastTask = Task.FromResult(initialState); Console.OutputEncoding = Encoding.UTF8; // We want to be sure to delete the shadow-copied files when the process goes away. Frankly // there's nothing we can do if the process is forcefully quit or goes down in a completely // uncontrolled manner (like a stack overflow). When the process goes down in a controlled // manned, we should generally expect this event to be called. AppDomain.CurrentDomain.ProcessExit += HandleProcessExit; } private void HandleProcessExit(object sender, EventArgs e) { Dispose(); AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit; } public void Dispose() { _metadataFileProvider.Dispose(); } public override object InitializeLifetimeService() { return null; } public void Initialize(Type replServiceProviderType, string cultureName) { Debug.Assert(replServiceProviderType != null); Debug.Assert(cultureName != null); Debug.Assert(_metadataFileProvider == null); Debug.Assert(_assemblyLoader == null); Debug.Assert(_replServiceProvider == null); // TODO (tomat): we should share the copied files with the host _metadataFileProvider = new MetadataShadowCopyProvider( Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"), noShadowCopyDirectories: s_systemNoShadowCopyDirectories, documentationCommentsCulture: new CultureInfo(cultureName)); _assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider); _replServiceProvider = (ReplServiceProvider)Activator.CreateInstance(replServiceProviderType); _globals = new InteractiveScriptGlobals(Console.Out, _replServiceProvider.ObjectFormatter); } private MetadataReferenceResolver CreateMetadataReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) { return new RuntimeMetadataReferenceResolver( new RelativePathResolver(searchPaths, baseDirectory), null, GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null, (path, properties) => new ShadowCopyReference(_metadataFileProvider, path, properties)); } private SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) { return new SourceFileResolver(searchPaths, baseDirectory); } private static bool AttachToClientProcess(int clientProcessId) { Process clientProcess; try { clientProcess = Process.GetProcessById(clientProcessId); } catch (ArgumentException) { return false; } clientProcess.EnableRaisingEvents = true; clientProcess.Exited += new EventHandler((_, __) => { s_clientExited.Set(); }); return clientProcess.IsAlive(); } // for testing purposes public void EmulateClientExit() { s_clientExited.Set(); } internal static void RunServer(string[] args) { if (args.Length != 3) { throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>"); } RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture)); } /// <summary> /// Implements remote server. /// </summary> private static void RunServer(string serverPort, string semaphoreName, int clientProcessId) { if (!AttachToClientProcess(clientProcessId)) { return; } // Disables Windows Error Reporting for the process, so that the process fails fast. // Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) // Note that GetErrorMode is not available on XP at all. if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0)) { SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX); } IpcServerChannel serverChannel = null; IpcClientChannel clientChannel = null; try { using (var semaphore = Semaphore.OpenExisting(semaphoreName)) { // DEBUG: semaphore.WaitOne(); var serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; var clientProvider = new BinaryClientFormatterSinkProvider(); clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider); ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false); serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider); ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(Service), ServiceName, WellKnownObjectMode.Singleton); using (var resetEvent = new ManualResetEventSlim(false)) { var uiThread = new Thread(() => { s_control = new Control(); s_control.CreateControl(); resetEvent.Set(); Application.Run(); }); uiThread.SetApartmentState(ApartmentState.STA); uiThread.IsBackground = true; uiThread.Start(); resetEvent.Wait(); } // the client can instantiate interactive host now: semaphore.Release(); } s_clientExited.Wait(); } finally { if (serverChannel != null) { ChannelServices.UnregisterChannel(serverChannel); } if (clientChannel != null) { ChannelServices.UnregisterChannel(clientChannel); } } // force exit even if there are foreground threads running: Environment.Exit(0); } internal static string ServiceName { get { return typeof(Service).Name; } } private static string GenerateUniqueChannelLocalName() { return typeof(Service).FullName + Guid.NewGuid(); } #endregion #region Remote Async Entry Points // Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.) [OneWay] public void SetPathsAsync( RemoteAsyncOperation<RemoteExecutionResult> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { Debug.Assert(operation != null); Debug.Assert(referenceSearchPaths != null); Debug.Assert(sourceSearchPaths != null); Debug.Assert(baseDirectory != null); lock (_lastTaskGuard) { _lastTask = SetPathsAsync(_lastTask, operation, referenceSearchPaths, sourceSearchPaths, baseDirectory); } } private async Task<EvaluationState> SetPathsAsync( Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { Directory.SetCurrentDirectory(baseDirectory); _globals.ReferencePaths.Clear(); _globals.ReferencePaths.AddRange(referenceSearchPaths); _globals.SourcePaths.Clear(); _globals.SourcePaths.AddRange(sourceSearchPaths); } finally { state = CompleteExecution(state, operation, success: true); } return state; } /// <summary> /// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it. /// Execution is performed on the UI thread. /// </summary> [OneWay] public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting) { Debug.Assert(operation != null); lock (_lastTaskGuard) { _lastTask = InitializeContextAsync(_lastTask, operation, initializationFile, isRestarting); } } /// <summary> /// Adds an assembly reference to the current session. /// </summary> [OneWay] public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference) { Debug.Assert(operation != null); Debug.Assert(reference != null); lock (_lastTaskGuard) { _lastTask = AddReferenceAsync(_lastTask, operation, reference); } } private async Task<EvaluationState> AddReferenceAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<bool> operation, string reference) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); bool success = false; try { var resolvedReferences = state.ScriptOptions.MetadataResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { state = state.WithOptions(state.ScriptOptions.AddReferences(resolvedReferences)); success = true; } else { Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference)); } } catch (Exception e) { ReportUnhandledException(e); } finally { operation.Completed(success); } return state; } /// <summary> /// Executes given script snippet on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text) { Debug.Assert(operation != null); Debug.Assert(text != null); lock (_lastTaskGuard) { _lastTask = ExecuteAsync(_lastTask, operation, text); } } private async Task<EvaluationState> ExecuteAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string text) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); bool success = false; try { Script<object> script = TryCompile(state.ScriptStateOpt?.Script, text, null, state.ScriptOptions); if (script != null) { // successful if compiled success = true; // remove references and imports from the options, they have been applied and will be inherited from now on: state = state.WithOptions(state.ScriptOptions.RemoveImportsAndReferences()); var newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false); if (newScriptState != null) { DisplaySubmissionResult(newScriptState); state = state.WithScriptState(newScriptState); } } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, operation, success); } return state; } private void DisplaySubmissionResult(ScriptState<object> state) { if (state.Script.HasReturnValue()) { _globals.Print(state.ReturnValue); } } /// <summary> /// Executes given script file on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path) { Debug.Assert(operation != null); Debug.Assert(path != null); lock (_lastTaskGuard) { _lastTask = ExecuteFileAsync(operation, _lastTask, path); } } private EvaluationState CompleteExecution(EvaluationState state, RemoteAsyncOperation<RemoteExecutionResult> operation, bool success) { // send any updates to the host object and current directory back to the client: var currentSourcePaths = _globals.SourcePaths.ToArray(); var currentReferencePaths = _globals.ReferencePaths.ToArray(); var currentWorkingDirectory = Directory.GetCurrentDirectory(); var changedSourcePaths = currentSourcePaths.SequenceEqual(state.SourceSearchPaths) ? null : currentSourcePaths; var changedReferencePaths = currentReferencePaths.SequenceEqual(state.ReferenceSearchPaths) ? null : currentReferencePaths; var changedWorkingDirectory = currentWorkingDirectory == state.WorkingDirectory ? null : currentWorkingDirectory; operation.Completed(new RemoteExecutionResult(success, changedSourcePaths, changedReferencePaths, changedWorkingDirectory)); // no changes in resolvers: if (changedReferencePaths == null && changedSourcePaths == null && changedWorkingDirectory == null) { return state; } var newSourcePaths = ImmutableArray.CreateRange(currentSourcePaths); var newReferencePaths = ImmutableArray.CreateRange(currentReferencePaths); var newWorkingDirectory = currentWorkingDirectory; ScriptOptions newOptions = state.ScriptOptions; if (changedReferencePaths != null || changedWorkingDirectory != null) { newOptions = newOptions.WithMetadataResolver(CreateMetadataReferenceResolver(newReferencePaths, newWorkingDirectory)); } if (changedSourcePaths != null || changedWorkingDirectory != null) { newOptions = newOptions.WithSourceResolver(CreateSourceReferenceResolver(newSourcePaths, newWorkingDirectory)); } return new EvaluationState( state.ScriptStateOpt, newOptions, newSourcePaths, newReferencePaths, workingDirectory: newWorkingDirectory); } private static async Task<EvaluationState> ReportUnhandledExceptionIfAny(Task<EvaluationState> lastTask) { try { return await lastTask.ConfigureAwait(false); } catch (Exception e) { ReportUnhandledException(e); return lastTask.Result; } } private static void ReportUnhandledException(Exception e) { Console.Error.WriteLine("Unexpected error:"); Console.Error.WriteLine(e); Debug.Fail("Unexpected error"); Debug.WriteLine(e); } #endregion #region Operations /// <summary> /// Loads references, set options and execute files specified in the initialization file. /// Also prints logo unless <paramref name="isRestarting"/> is true. /// </summary> private async Task<EvaluationState> InitializeContextAsync( Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFileOpt, bool isRestarting) { Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt)); var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here? if (!isRestarting) { Console.Out.WriteLine(_replServiceProvider.Logo); } if (File.Exists(initializationFileOpt)) { Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt))); var parser = _replServiceProvider.CommandLineParser; // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var rspDirectory = Path.GetDirectoryName(initializationFileOpt); var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null); foreach (var error in args.Errors) { var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out; writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture)); } if (args.Errors.Length == 0) { var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory); var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory); var metadataReferences = new List<PortableExecutableReference>(); foreach (CommandLineReference cmdLineReference in args.MetadataReferences) { // interactive command line parser doesn't accept modules or linked assemblies Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes); var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { metadataReferences.AddRange(resolvedReferences); } } var scriptPathOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path; var rspState = new EvaluationState( state.ScriptStateOpt, state.ScriptOptions. WithFilePath(scriptPathOpt). WithReferences(metadataReferences). WithImports(CommandLineHelpers.GetImports(args)). WithMetadataResolver(metadataResolver). WithSourceResolver(sourceResolver), args.SourcePaths, args.ReferencePaths, rspDirectory); _globals.ReferencePaths.Clear(); _globals.ReferencePaths.AddRange(args.ReferencePaths); _globals.SourcePaths.Clear(); _globals.SourcePaths.AddRange(args.SourcePaths); _globals.Args.AddRange(args.ScriptArguments); if (scriptPathOpt != null) { var newScriptState = await ExecuteFileAsync(rspState, scriptPathOpt).ConfigureAwait(false); if (newScriptState != null) { // remove references and imports from the options, they have been applied and will be inherited from now on: rspState = rspState. WithScriptState(newScriptState). WithOptions(rspState.ScriptOptions.RemoveImportsAndReferences()); } } state = rspState; } } if (!isRestarting) { Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation); } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, operation, success: true); } return state; } private string ResolveRelativePath(string path, string baseDirectory, ImmutableArray<string> searchPaths, bool displayPath) { List<string> attempts = new List<string>(); Func<string, bool> fileExists = file => { attempts.Add(file); return File.Exists(file); }; string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, searchPaths, fileExists); if (fullPath == null) { if (displayPath) { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path); } else { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound); } if (attempts.Count > 0) { DisplaySearchPaths(Console.Error, attempts); } } return fullPath; } private Script<object> TryCompile(Script previousScript, string code, string path, ScriptOptions options) { Script script; var scriptOptions = options.WithFilePath(path); if (previousScript != null) { script = previousScript.ContinueWith(code, scriptOptions); } else { script = _replServiceProvider.CreateScript<object>(code, scriptOptions, _globals.GetType(), _assemblyLoader); } var diagnostics = script.Compile(); if (diagnostics.HasAnyErrors()) { DisplayInteractiveErrors(diagnostics, Console.Error); return null; } return (Script<object>)script; } private async Task<EvaluationState> ExecuteFileAsync( RemoteAsyncOperation<RemoteExecutionResult> operation, Task<EvaluationState> lastTask, string path) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); var success = false; try { var fullPath = ResolveRelativePath(path, state.WorkingDirectory, state.SourceSearchPaths, displayPath: false); var newScriptState = await ExecuteFileAsync(state, fullPath).ConfigureAwait(false); if (newScriptState != null) { success = true; state = state.WithScriptState(newScriptState); } } finally { state = CompleteExecution(state, operation, success); } return state; } /// <summary> /// Executes specified script file as a submission. /// </summary> /// <returns>True if the code has been executed. False if the code doesn't compile.</returns> /// <remarks> /// All errors are written to the error output stream. /// Uses source search paths to resolve unrooted paths. /// </remarks> private async Task<ScriptState<object>> ExecuteFileAsync(EvaluationState state, string fullPath) { string content = null; if (fullPath != null) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); try { content = File.ReadAllText(fullPath); } catch (Exception e) { Console.Error.WriteLine(e.Message); } } ScriptState<object> newScriptState = null; if (content != null) { Script<object> script = TryCompile(state.ScriptStateOpt?.Script, content, fullPath, state.ScriptOptions); if (script != null) { newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false); } } return newScriptState; } private static void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths) { var directories = attemptedFilePaths.Select(path => Path.GetDirectoryName(path)).ToArray(); var uniqueDirectories = new HashSet<string>(directories); writer.WriteLine(uniqueDirectories.Count == 1 ? FeaturesResources.SearchedInDirectory : FeaturesResources.SearchedInDirectories); foreach (string directory in directories) { if (uniqueDirectories.Remove(directory)) { writer.Write(" "); writer.WriteLine(directory); } } } private async Task<ScriptState<object>> ExecuteOnUIThread(Script<object> script, ScriptState<object> stateOpt) { return await ((Task<ScriptState<object>>)s_control.Invoke( (Func<Task<ScriptState<object>>>)(async () => { try { var task = (stateOpt == null) ? script.RunAsync(_globals, CancellationToken.None) : script.RunFromAsync(stateOpt, CancellationToken.None); return await task.ConfigureAwait(false); } catch (FileLoadException e) when (e.InnerException is InteractiveAssemblyLoaderException) { Console.Error.WriteLine(e.InnerException.Message); return null; } catch (Exception e) { Console.Error.WriteLine(_replServiceProvider.ObjectFormatter.FormatException(e)); return null; } }))).ConfigureAwait(false); } private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output) { var displayedDiagnostics = new List<Diagnostic>(); const int MaxErrorCount = 5; for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++) { displayedDiagnostics.Add(diagnostics[i]); } displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start); var formatter = _replServiceProvider.DiagnosticFormatter; foreach (var diagnostic in displayedDiagnostics) { output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo)); } if (diagnostics.Length > MaxErrorCount) { int notShown = diagnostics.Length - MaxErrorCount; output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors")); } } #endregion #region Win32 API [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode SetErrorMode(ErrorMode mode); [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode GetErrorMode(); [Flags] internal enum ErrorMode : int { /// <summary> /// Use the system default, which is to display all error dialog boxes. /// </summary> SEM_FAILCRITICALERRORS = 0x0001, /// <summary> /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process. /// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup. /// This is to prevent error mode dialogs from hanging the application. /// </summary> SEM_NOGPFAULTERRORBOX = 0x0002, /// <summary> /// The system automatically fixes memory alignment faults and makes them invisible to the application. /// It does this for the calling process and any descendant processes. This feature is only supported by /// certain processor architectures. For more information, see the Remarks section. /// After this value is set for a process, subsequent attempts to clear the value are ignored. /// </summary> SEM_NOALIGNMENTFAULTEXCEPT = 0x0004, /// <summary> /// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process. /// </summary> SEM_NOOPENFILEERRORBOX = 0x8000, } #endregion #region Testing // TODO(tomat): remove when the compiler supports events // For testing purposes only! public void HookMaliciousAssemblyResolve() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) => { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { Console.Error.WriteLine("in the loop"); i = i + 1; } } }); } public void RemoteConsoleWrite(byte[] data, bool isError) { using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput()) { stream.Write(data, 0, data.Length); stream.Flush(); } } public bool IsShadowCopy(string path) { return _metadataFileProvider.IsShadowCopy(path); } #endregion } } }
using Saga.Authentication.Packets; using Saga.Authentication.Utils; using Saga.Network.Packets; using Saga.Packets; using Saga.Shared.PacketLib.Login; using System; using System.Diagnostics; using System.Threading; namespace Saga.Authentication.Network { partial class LogonClient : Shared.NetworkCore.Client { public LogonClient() { Trace.TraceInformation("Client create starting timeout session"); WaitCallback callback = delegate(object obj) { int LastTick = Environment.TickCount; bool Timeout = false; //Forces to receive the header in 10 secconds if not kill the connection. while (securityToken == 0) { if (Environment.TickCount - LastTick > 10000) { Timeout = true; break; } else { Thread.Sleep(1); } } if (Timeout == true) { Console.WriteLine("Unautorized connection detetected. Make sure you connect on the gateway server not the authentication server"); Trace.WriteLine("Connection did not authenticate himself within 10 secconds. Closing connection."); this.Close(); } }; ThreadPool.QueueUserWorkItem(callback); this.OnClose += new EventHandler(LogonClient_OnClose); } private void LogonClient_OnClose(object sender, EventArgs e) { if (securityToken == 1) { Console.WriteLine("Gateway connection is closed from {0}", this.socket.RemoteEndPoint); } } protected override void ProcessPacket(ref byte[] body) { try { //Only allow listening for the the initial header handshake if (securityToken == 0) { //Skip this packet if it's not orginated from 0401 ushort packetIdentifier = (ushort)(body[7] + (body[6] << 8)); if (packetIdentifier != 0x0401) return; //Check for header handshake ushort subpacketIdentifier = (ushort)(body[13] + (body[12] << 8)); switch (subpacketIdentifier) { case 0xFFFF: HEADERRETRIEVED(); return; default: Trace.TraceWarning("Unsupported packet found with id: {0:X4}", subpacketIdentifier); break; } } else { ushort subpacketIdentifier = (ushort)(body[13] + (body[12] << 8)); switch (subpacketIdentifier) { //Custom case 0xFF01: OnNetworkExchange((CMSG_NETWORKADRESSIP)body); break; case 0xFF02: OnReleaseResources((CMSG_RELEASERESOURCES)body); break; case 0xFF03: OnSetSession(body); return; //Official case 0x0101: Login((CMSG_REQUESTLOGIN)body); return; case 0x010B: Login((CMSG_REQUESTLOGIN)body); return; case 0x0102: OnServerListRequest((CMSG_REQUESTSERVERLIST)body); return; case 0x0103: OnSelectServer((CMSG_SELECTSERVER)body); return; case 0x0104: OnSelectChar((CMSG_SELECTCHARACTER)body); return; case 0x0105: OnCreateChar((CMSG_CREATECHARACTER)body); return; case 0x0106: OnWantCharList((CMSG_REQUESTCHARACTERLIST)body); return; case 0x0107: OnGetCharData((CMSG_REQUESTCHARACTERDETAILS)body); return; case 0x0108: OnDeleteChar((CMSG_DELETECHARACTER)body); return; case 0x010A: CM_KILLEXISTINGCONNECTION((RelayPacket)body); return; case 0x0110: OnLogin((RelayPacket)body); return; default: Trace.TraceWarning("Unsupported packet found with id: {0:X4}", subpacketIdentifier); break; } } } catch (Exception e) { Console.WriteLine(e); } } private void OnSetSession(byte[] body) { uint session = 0; session = ++NextSession; if (session >= 0x40000000) { NextSession = 1; session = 1; } if (session > 0) { LoginSession logonsession = new LoginSession(); logonsession.client = this; LoginSessionHandler.sessions.Add(session, logonsession); SMSG_SETSESSION spkt = new SMSG_SETSESSION(); spkt.SessionId = session; this.Send((byte[])spkt); } else { Trace.TraceError("No session found"); } } private void OnNetworkExchange(CMSG_NETWORKADRESSIP cpkt) { //TRY TO ESTABLISH A CONNECTION TO OUR BACKEND LoginSession session; if (LoginSessionHandler.sessions.TryGetValue(cpkt.SessionId, out session)) { session.Adress = cpkt.ConnectionFrom; } else { Trace.TraceError("Session was not found: {0}", cpkt.SessionId); } } private byte securityToken = 0; private void HEADERRETRIEVED() { securityToken = 1; Console.WriteLine("Gateway connection accepted from {0}", this.socket.RemoteEndPoint); } private void OnReleaseResources(CMSG_RELEASERESOURCES cpkt) { lock (LoginSessionHandler.sessions) { if (!LoginSessionHandler.sessions.Remove(cpkt.Session)) Trace.TraceInformation("Resources are not found: {0}", cpkt.Session); } } private void OnLogin(RelayPacket cpkt) { LoginSession session; if (LoginSessionHandler.sessions.TryGetValue(cpkt.SessionId, out session)) { ServerInfo2 info; if (!ServerManager2.Instance.server.TryGetValue(session.World, out info)) { Trace.TraceError(string.Format("Server not found: {0}", session.World)); } else if (info.client == null || info.client.IsConnected == false) { Trace.TraceError(string.Format("World server not connected: {0}", session.World)); } else { Singleton.Database.UpdateSession(session.playerid, cpkt.SessionId); Singleton.Database.UpdateLastplayerWorld(session.playerid, session.World); info.Players++; SMSG_LOGIN spkt = new SMSG_LOGIN(); spkt.GmLevel = session.GmLevel; spkt.Gender = (byte)session.Gender; spkt.CharacterId = session.characterid; spkt.SessionId = cpkt.SessionId; this.Send((byte[])spkt); //Send login packet to world /* SMSG_CHARACTERLOGIN spkt2 = new SMSG_CHARACTERLOGIN(); spkt2.CharacterId = session.characterid; spkt2.SessionId = cpkt.SessionId; spkt2.Session = cpkt.SessionId; info.client.Send((byte[])spkt2);*/ } } } } }
// // AddinRegistry.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Xml; using System.Collections; using System.Collections.Specialized; using Mono.Addins.Database; using Mono.Addins.Description; using System.Collections.Generic; using System.Linq; namespace Mono.Addins { /// <summary> /// An add-in registry. /// </summary> /// <remarks> /// An add-in registry is a data structure used by the add-in engine to locate add-ins to load. /// /// A registry can be configured to look for add-ins in several directories. However, add-ins /// copied to those directories won't be detected until an explicit add-in scan is requested. /// The registry can be updated by an application by calling Registry.Update(), or by a user by /// running the 'mautil' add-in setup tool. /// /// The registry has information about the location of every add-in and a timestamp of the last /// check, so the Update method will only scan new or modified add-ins. An application can /// add a call to Registry.Update() in the Main method to detect all new add-ins every time the /// app is started. /// /// Every add-in added to the registry is parsed and validated, and if there is any error it /// will be rejected. The registry is also in charge of scanning the add-in assemblies and look /// for extensions and other information declared using custom attributes. That information is /// merged with the manifest information (if there is one) to create a complete add-in /// description ready to be used at run-time. /// /// Mono.Addins allows sharing an add-in registry among several applications. In this context, /// all applications sharing the registry share the same extension point model, and it is /// possible to implement add-ins which extend several hosts. /// </remarks> public class AddinRegistry: IDisposable { AddinDatabase database; StringCollection addinDirs; string basePath; string currentDomain; string startupDirectory; string addinsDir; string databaseDir; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="registryPath"> /// Location of the add-in registry. /// </param> /// <remarks> /// Creates a new add-in registry located in the provided path. /// The add-in registry will look for add-ins in an 'addins' /// subdirectory of the provided registryPath. /// /// When specifying a path, it is possible to use a special folder name as root. /// For example: [Personal]/.config/MyApp. In this case, [Personal] will be replaced /// by the location of the Environment.SpecialFolder.Personal folder. Any value /// of the Environment.SpecialFolder enumeration can be used (always between square /// brackets) /// </remarks> public AddinRegistry (string registryPath): this (null, registryPath, null, null, null) { } /// <summary> /// Initializes a new instance. /// </summary> /// <param name="registryPath"> /// Location of the add-in registry. /// </param> /// <param name="startupDirectory"> /// Location of the application. /// </param> /// <remarks> /// Creates a new add-in registry located in the provided path. /// The add-in registry will look for add-ins in an 'addins' /// subdirectory of the provided registryPath. /// /// When specifying a path, it is possible to use a special folder name as root. /// For example: [Personal]/.config/MyApp. In this case, [Personal] will be replaced /// by the location of the Environment.SpecialFolder.Personal folder. Any value /// of the Environment.SpecialFolder enumeration can be used (always between square /// brackets) /// </remarks> public AddinRegistry (string registryPath, string startupDirectory): this (null, registryPath, startupDirectory, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="Mono.Addins.AddinRegistry"/> class. /// </summary> /// <param name='registryPath'> /// Location of the add-in registry. /// </param> /// <param name='startupDirectory'> /// Location of the application. /// </param> /// <param name='addinsDir'> /// Add-ins directory. If the path is relative, it is considered to be relative /// to the configDir directory. /// </param> /// <remarks> /// Creates a new add-in registry located in the provided path. /// Configuration information about the add-in registry will be stored in /// 'registryPath'. The add-in registry will look for add-ins in the provided /// 'addinsDir' directory. /// /// When specifying a path, it is possible to use a special folder name as root. /// For example: [Personal]/.config/MyApp. In this case, [Personal] will be replaced /// by the location of the Environment.SpecialFolder.Personal folder. Any value /// of the Environment.SpecialFolder enumeration can be used (always between square /// brackets) /// </remarks> public AddinRegistry (string registryPath, string startupDirectory, string addinsDir): this (null, registryPath, startupDirectory, addinsDir, null) { } /// <summary> /// Initializes a new instance of the <see cref="Mono.Addins.AddinRegistry"/> class. /// </summary> /// <param name='registryPath'> /// Location of the add-in registry. /// </param> /// <param name='startupDirectory'> /// Location of the application. /// </param> /// <param name='addinsDir'> /// Add-ins directory. If the path is relative, it is considered to be relative /// to the configDir directory. /// </param> /// <param name='databaseDir'> /// Location of the add-in database. If the path is relative, it is considered to be relative /// to the configDir directory. /// </param> /// <remarks> /// Creates a new add-in registry located in the provided path. /// Configuration information about the add-in registry will be stored in /// 'registryPath'. The add-in registry will look for add-ins in the provided /// 'addinsDir' directory. Cached information about add-ins will be stored in /// the 'databaseDir' directory. /// /// When specifying a path, it is possible to use a special folder name as root. /// For example: [Personal]/.config/MyApp. In this case, [Personal] will be replaced /// by the location of the Environment.SpecialFolder.Personal folder. Any value /// of the Environment.SpecialFolder enumeration can be used (always between square /// brackets) /// </remarks> public AddinRegistry (string registryPath, string startupDirectory, string addinsDir, string databaseDir): this (null, registryPath, startupDirectory, addinsDir, databaseDir) { } internal AddinRegistry (AddinEngine engine, string registryPath, string startupDirectory, string addinsDir, string databaseDir) { basePath = Path.GetFullPath (Util.NormalizePath (registryPath)); if (addinsDir != null) { addinsDir = Util.NormalizePath (addinsDir); if (Path.IsPathRooted (addinsDir)) this.addinsDir = Path.GetFullPath (addinsDir); else this.addinsDir = Path.GetFullPath (Path.Combine (basePath, addinsDir)); } else this.addinsDir = Path.Combine (basePath, "addins"); if (databaseDir != null) { databaseDir = Util.NormalizePath (databaseDir); if (Path.IsPathRooted (databaseDir)) this.databaseDir = Path.GetFullPath (databaseDir); else this.databaseDir = Path.GetFullPath (Path.Combine (basePath, databaseDir)); } else this.databaseDir = Path.GetFullPath (basePath); // Look for add-ins in the hosts directory and in the default // addins directory addinDirs = new StringCollection (); addinDirs.Add (DefaultAddinsFolder); // Initialize the database after all paths have been set database = new AddinDatabase (engine, this); // Get the domain corresponding to the startup folder if (startupDirectory != null && startupDirectory.Length > 0) { this.startupDirectory = Util.NormalizePath (startupDirectory); currentDomain = database.GetFolderDomain (null, this.startupDirectory); } else currentDomain = AddinDatabase.GlobalDomain; } /// <summary> /// Gets the global registry. /// </summary> /// <returns> /// The global registry /// </returns> /// <remarks> /// The global add-in registry is created in "~/.config/mono.addins", /// and it is the default registry used when none is specified. /// </remarks> public static AddinRegistry GetGlobalRegistry () { return GetGlobalRegistry (null, null); } internal static AddinRegistry GetGlobalRegistry (AddinEngine engine, string startupDirectory) { AddinRegistry reg = new AddinRegistry (engine, GlobalRegistryPath, startupDirectory, null, null); string baseDir; if (Util.IsWindows) baseDir = Environment.GetFolderPath (Environment.SpecialFolder.CommonProgramFiles); else baseDir = "/etc"; reg.GlobalAddinDirectories.Add (Path.Combine (baseDir, "mono.addins")); return reg; } internal bool UnknownDomain { get { return currentDomain == AddinDatabase.UnknownDomain; } } internal static string GlobalRegistryPath { get { string customDir = Environment.GetEnvironmentVariable ("MONO_ADDINS_GLOBAL_REGISTRY"); if (customDir != null && customDir.Length > 0) return Path.GetFullPath (Util.NormalizePath (customDir)); string path = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData); path = Path.Combine (path, "mono.addins"); return Path.GetFullPath (path); } } internal string CurrentDomain { get { return currentDomain; } } /// <summary> /// Location of the add-in registry. /// </summary> public string RegistryPath { get { return basePath; } } /// <summary> /// Disposes the add-in engine. /// </summary> public void Dispose () { database.Shutdown (); } /// <summary> /// Returns an add-in from the registry. /// </summary> /// <param name="id"> /// Identifier of the add-in. /// </param> /// <returns> /// The add-in, or 'null' if not found. /// </returns> /// <remarks> /// The add-in identifier may optionally include a version number, for example: "TextEditor.Xml,1.2" /// </remarks> public Addin GetAddin (string id) { if (currentDomain == AddinDatabase.UnknownDomain) return null; Addin ad = database.GetInstalledAddin (currentDomain, id); if (ad != null && IsRegisteredForUninstall (ad.Id)) return null; return ad; } /// <summary> /// Returns an add-in from the registry. /// </summary> /// <param name="id"> /// Identifier of the add-in. /// </param> /// <param name="exactVersionMatch"> /// 'true' if the exact add-in version must be found. /// </param> /// <returns> /// The add-in, or 'null' if not found. /// </returns> /// <remarks> /// The add-in identifier may optionally include a version number, for example: "TextEditor.Xml,1.2". /// In this case, if the exact version is not found and exactVersionMatch is 'false', it will /// return one than is compatible with the required version. /// </remarks> public Addin GetAddin (string id, bool exactVersionMatch) { if (currentDomain == AddinDatabase.UnknownDomain) return null; Addin ad = database.GetInstalledAddin (currentDomain, id, exactVersionMatch); if (ad != null && IsRegisteredForUninstall (ad.Id)) return null; return ad; } /// <summary> /// Gets all add-ins or add-in roots registered in the registry. /// </summary> /// <returns> /// The addins. /// </returns> /// <param name='flags'> /// Flags. /// </param> public Addin[] GetModules (AddinSearchFlags flags) { if (currentDomain == AddinDatabase.UnknownDomain) return new Addin [0]; AddinSearchFlagsInternal f = (AddinSearchFlagsInternal)(int)flags; return database.GetInstalledAddins (currentDomain, f | AddinSearchFlagsInternal.ExcludePendingUninstall).ToArray (); } /// <summary> /// Gets all add-ins registered in the registry. /// </summary> /// <returns> /// Add-ins registered in the registry. /// </returns> public Addin[] GetAddins () { return GetModules (AddinSearchFlags.IncludeAddins); } /// <summary> /// Gets all add-in roots registered in the registry. /// </summary> /// <returns> /// Descriptions of all add-in roots. /// </returns> public Addin[] GetAddinRoots () { return GetModules (AddinSearchFlags.IncludeRoots); } /// <summary> /// Loads an add-in description /// </summary> /// <param name="progressStatus"> /// Progress tracker. /// </param> /// <param name="file"> /// Name of the file to load /// </param> /// <returns> /// An add-in description /// </returns> /// <remarks> /// This method loads an add-in description from a file. The file can be an XML manifest or an /// assembly that implements an add-in. /// </remarks> public AddinDescription GetAddinDescription (IProgressStatus progressStatus, string file) { if (currentDomain == AddinDatabase.UnknownDomain) return null; string outFile = Path.GetTempFileName (); try { database.ParseAddin (progressStatus, currentDomain, file, outFile, false); } catch { File.Delete (outFile); throw; } try { AddinDescription desc = AddinDescription.Read (outFile); if (desc != null) { desc.AddinFile = file; desc.OwnerDatabase = database; } return desc; } catch { // Errors are already reported using the progress status object return null; } finally { File.Delete (outFile); } } /// <summary> /// Reads an XML add-in manifest /// </summary> /// <param name="file"> /// Path to the XML file /// </param> /// <returns> /// An add-in description /// </returns> public AddinDescription ReadAddinManifestFile (string file) { AddinDescription desc = AddinDescription.Read (file); if (currentDomain != AddinDatabase.UnknownDomain) { desc.OwnerDatabase = database; desc.Domain = currentDomain; } return desc; } /// <summary> /// Reads an XML add-in manifest /// </summary> /// <param name="reader"> /// Reader that contains the XML /// </param> /// <param name="baseFile"> /// Base path to use to discover add-in files /// </param> /// <returns> /// An add-in description /// </returns> public AddinDescription ReadAddinManifestFile (TextReader reader, string baseFile) { if (currentDomain == AddinDatabase.UnknownDomain) return null; AddinDescription desc = AddinDescription.Read (reader, baseFile); desc.OwnerDatabase = database; desc.Domain = currentDomain; return desc; } /// <summary> /// Checks whether an add-in is enabled. /// </summary> /// <param name="id"> /// Identifier of the add-in. /// </param> /// <returns> /// 'true' if the add-in is enabled. /// </returns> public bool IsAddinEnabled (string id) { if (currentDomain == AddinDatabase.UnknownDomain) return false; return database.IsAddinEnabled (currentDomain, id); } /// <summary> /// Enables an add-in. /// </summary> /// <param name="id"> /// Identifier of the add-in /// </param> /// <remarks> /// If the enabled add-in depends on other add-ins which are disabled, /// those will automatically be enabled too. /// </remarks> public void EnableAddin (string id) { if (currentDomain == AddinDatabase.UnknownDomain) return; database.EnableAddin (currentDomain, id, true); } /// <summary> /// Disables an add-in. /// </summary> /// <param name="id"> /// Identifier of the add-in. /// </param> /// <remarks> /// When an add-in is disabled, all extension points it defines will be ignored /// by the add-in engine. Other add-ins which depend on the disabled add-in will /// also automatically be disabled. /// </remarks> public void DisableAddin (string id) { if (currentDomain == AddinDatabase.UnknownDomain) return; database.DisableAddin (currentDomain, id); } /// <summary> /// Disables an add-in. /// </summary> /// <param name="id"> /// Identifier of the add-in. /// </param> /// <param name="exactVersionMatch"> /// If true, it disables the add-in that exactly matches the provided version. If false, it disables /// all versions of add-ins with the same Id /// </param> /// <remarks> /// When an add-in is disabled, all extension points it defines will be ignored /// by the add-in engine. Other add-ins which depend on the disabled add-in will /// also automatically be disabled. /// </remarks> public void DisableAddin (string id, bool exactVersionMatch) { if (currentDomain == AddinDatabase.UnknownDomain) return; database.DisableAddin (currentDomain, id, exactVersionMatch); } /// <summary> /// Registers a set of add-ins for uninstallation. /// </summary> /// <param name='id'> /// Identifier of the add-in /// </param> /// <param name='files'> /// Files to be uninstalled /// </param> /// <remarks> /// This method can be used to instruct the add-in manager to uninstall /// an add-in the next time the registry is updated. This is useful /// when an add-in manager can't delete an add-in because if it is /// loaded. /// </remarks> public void RegisterForUninstall (string id, IEnumerable<string> files) { database.RegisterForUninstall (currentDomain, id, files); } /// <summary> /// Determines whether an add-in is registered for uninstallation /// </summary> /// <returns> /// <c>true</c> if the add-in is registered for uninstallation /// </returns> /// <param name='addinId'> /// Identifier of the add-in /// </param> public bool IsRegisteredForUninstall (string addinId) { return database.IsRegisteredForUninstall (currentDomain, addinId); } /// <summary> /// Gets a value indicating whether there are pending add-ins to be uninstalled installed /// </summary> public bool HasPendingUninstalls { get { return database.HasPendingUninstalls (currentDomain); } } /// <summary> /// Internal use only /// </summary> public void DumpFile (string file) { Mono.Addins.Serialization.BinaryXmlReader.DumpFile (file); } /// <summary> /// Resets the configuration files of the registry /// </summary> public void ResetConfiguration () { database.ResetConfiguration (); } internal void NotifyDatabaseUpdated () { if (startupDirectory != null) currentDomain = database.GetFolderDomain (null, startupDirectory); } /// <summary> /// Updates the add-in registry. /// </summary> /// <remarks> /// This method must be called after modifying, installing or uninstalling add-ins. /// /// When calling Update, every add-in added to the registry is parsed and validated, /// and if there is any error it will be rejected. It will also cache add-in information /// needed at run-time. /// /// If during the update operation the registry finds new add-ins or detects that some /// add-ins have been deleted, the loaded extension points will be updated to include /// or exclude extension nodes from those add-ins. /// </remarks> public void Update () { Update (new ConsoleProgressStatus (false)); } /// <summary> /// Updates the add-in registry. /// </summary> /// <param name="monitor"> /// Progress monitor to keep track of the update operation. /// </param> /// <remarks> /// This method must be called after modifying, installing or uninstalling add-ins. /// /// When calling Update, every add-in added to the registry is parsed and validated, /// and if there is any error it will be rejected. It will also cache add-in information /// needed at run-time. /// /// If during the update operation the registry finds new add-ins or detects that some /// add-ins have been deleted, the loaded extension points will be updated to include /// or exclude extension nodes from those add-ins. /// </remarks> public void Update (IProgressStatus monitor) { database.Update (monitor, currentDomain); } /// <summary> /// Regenerates the cached data of the add-in registry. /// </summary> /// <param name="monitor"> /// Progress monitor to keep track of the rebuild operation. /// </param> public void Rebuild (IProgressStatus monitor) { var context = new ScanOptions (); context.CleanGeneratedAddinScanDataFiles = true; database.Repair (monitor, currentDomain, context); // A full rebuild may cause the domain to change if (!string.IsNullOrEmpty (startupDirectory)) currentDomain = database.GetFolderDomain (null, startupDirectory); } /// <summary> /// Generates add-in data cache files for add-ins in the provided folder /// and any other directory included through a .addins file. /// If folder is not provided, it scans the startup directory. /// </summary> /// <param name="monitor"> /// Progress monitor to keep track of the rebuild operation. /// </param> /// <param name="folder"> /// Folder that contains the add-ins to be scanned. /// </param> /// <param name="recursive"> /// If true, sub-directories are scanned recursively /// </param> public void GenerateAddinScanDataFiles (IProgressStatus monitor, string folder = null, bool recursive = false) { database.GenerateScanDataFiles (monitor, folder ?? StartupDirectory, recursive); } /// <summary> /// Registers an extension. Only AddinFileSystemExtension extensions are supported right now. /// </summary> /// <param name='extension'> /// The extension to register /// </param> public void RegisterExtension (object extension) { database.RegisterExtension (extension); } /// <summary> /// Unregisters an extension. /// </summary> /// <param name='extension'> /// The extension to unregister /// </param> public void UnregisterExtension (object extension) { database.UnregisterExtension (extension); } internal void CopyExtensionsFrom (AddinRegistry other) { database.CopyExtensions (other.database); } internal Addin GetAddinForHostAssembly (string filePath) { if (currentDomain == AddinDatabase.UnknownDomain) return null; return database.GetAddinForHostAssembly (currentDomain, filePath); } internal bool AddinDependsOn (string id1, string id2) { return database.AddinDependsOn (currentDomain, id1, id2); } internal void ScanFolders (IProgressStatus monitor, string folderToScan, ScanOptions context) { database.ScanFolders (monitor, currentDomain, folderToScan, context); } internal void GenerateScanDataFilesInProcess (IProgressStatus monitor, string folderToScan, bool recursive) { database.GenerateScanDataFilesInProcess (monitor, folderToScan, recursive); } internal void ParseAddin (IProgressStatus progressStatus, string file, string outFile) { database.ParseAddin (progressStatus, currentDomain, file, outFile, true); } /// <summary> /// Gets the default add-ins folder of the registry. /// </summary> /// <remarks> /// For every add-in registry there is an add-in folder where the registry will look for add-ins by default. /// This folder is an "addins" subdirectory of the directory where the repository is located. In most cases, /// this folder will only contain .addins files referencing other more convenient locations for add-ins. /// </remarks> public string DefaultAddinsFolder { get { return addinsDir; } } internal string AddinCachePath { get { return databaseDir; } } internal StringCollection GlobalAddinDirectories { get { return addinDirs; } } internal string StartupDirectory { get { return startupDirectory; } } internal bool CreateHostAddinsFile (string hostFile) { hostFile = Path.GetFullPath (hostFile); string baseName = Path.GetFileNameWithoutExtension (hostFile); if (!Directory.Exists (database.HostsPath)) Directory.CreateDirectory (database.HostsPath); foreach (string s in Directory.EnumerateFiles (database.HostsPath, baseName + "*.addins")) { try { using (StreamReader sr = new StreamReader (s)) { XmlTextReader tr = new XmlTextReader (sr); tr.MoveToContent (); string host = tr.GetAttribute ("host-reference"); if (host == hostFile) return false; } } catch { // Ignore this file } } string file = Path.Combine (database.HostsPath, baseName) + ".addins"; int n=1; while (File.Exists (file)) { file = Path.Combine (database.HostsPath, baseName) + "_" + n + ".addins"; n++; } using (StreamWriter sw = new StreamWriter (file)) { XmlTextWriter tw = new XmlTextWriter (sw); tw.Formatting = Formatting.Indented; tw.WriteStartElement ("Addins"); tw.WriteAttributeString ("host-reference", hostFile); tw.WriteStartElement ("Directory"); tw.WriteAttributeString ("shared", "false"); tw.WriteString (Path.GetDirectoryName (hostFile)); tw.WriteEndElement (); tw.Close (); } return true; } #pragma warning disable 1591 [Obsolete] public static string[] GetRegisteredStartupFolders (string registryPath) { string dbDir = Path.Combine (registryPath, "addin-db-" + AddinDatabase.VersionTag); dbDir = Path.Combine (dbDir, "hosts"); if (!Directory.Exists (dbDir)) return new string [0]; ArrayList dirs = new ArrayList (); foreach (string s in Directory.GetFiles (dbDir, "*.addins")) { try { using (StreamReader sr = new StreamReader (s)) { XmlTextReader tr = new XmlTextReader (sr); tr.MoveToContent (); string host = tr.GetAttribute ("host-reference"); host = Path.GetDirectoryName (host); if (!dirs.Contains (host)) dirs.Add (host); } } catch { // Ignore this file } } return (string[]) dirs.ToArray (typeof(string)); } #pragma warning restore 1591 } /// <summary> /// Addin search flags. /// </summary> [Flags] public enum AddinSearchFlags { /// <summary> /// Add-ins are included in the search /// </summary> IncludeAddins = 1, /// <summary> /// Add-in roots are included in the search /// </summary> IncludeRoots = 1 << 1, /// <summary> /// Both add-in and add-in roots are included in the search /// </summary> IncludeAll = IncludeAddins | IncludeRoots, /// <summary> /// Only the latest version of every add-in or add-in root is included in the search /// </summary> LatestVersionsOnly = 1 << 3 } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Threading; using System.Text; using System.Xml; using System.Xml.Linq; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { public class InventoryArchiveReadRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The maximum major version of archive that we can read. Minor versions shouldn't need a max number since version /// bumps here should be compatible. /// </summary> public static int MAX_MAJOR_VERSION = 1; protected TarArchiveReader archive; private UserAccount m_userInfo; private string m_invPath; /// <summary> /// Do we want to merge this load with existing inventory? /// </summary> protected bool m_merge; /// <value> /// We only use this to request modules /// </value> protected Scene m_scene; /// <value> /// The stream from which the inventory archive will be loaded. /// </value> private Stream m_loadStream; /// <summary> /// Has the control file been loaded for this archive? /// </summary> public bool ControlFileLoaded { get; private set; } /// <summary> /// Do we want to enforce the check. IAR versions before 0.2 and 1.1 do not guarantee this order, so we can't /// enforce. /// </summary> public bool EnforceControlFileCheck { get; private set; } protected bool m_assetsLoaded; protected bool m_inventoryNodesLoaded; protected int m_successfulAssetRestores; protected int m_failedAssetRestores; protected int m_successfulItemRestores; /// <summary> /// Root destination folder for the IAR load. /// </summary> protected InventoryFolderBase m_rootDestinationFolder; /// <summary> /// Inventory nodes loaded from the iar. /// </summary> protected HashSet<InventoryNodeBase> m_loadedNodes = new HashSet<InventoryNodeBase>(); /// <summary> /// In order to load identically named folders, we need to keep track of the folders that we have already /// resolved. /// </summary> Dictionary <string, InventoryFolderBase> m_resolvedFolders = new Dictionary<string, InventoryFolderBase>(); /// <summary> /// Record the creator id that should be associated with an asset. This is used to adjust asset creator ids /// after OSP resolution (since OSP creators are only stored in the item /// </summary> protected Dictionary<UUID, UUID> m_creatorIdForAssetId = new Dictionary<UUID, UUID>(); public InventoryArchiveReadRequest( Scene scene, UserAccount userInfo, string invPath, string loadPath, bool merge) : this( scene, userInfo, invPath, new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress), merge) { } public InventoryArchiveReadRequest( Scene scene, UserAccount userInfo, string invPath, Stream loadStream, bool merge) { m_scene = scene; m_merge = merge; m_userInfo = userInfo; m_invPath = invPath; m_loadStream = loadStream; // FIXME: Do not perform this check since older versions of OpenSim do save the control file after other things // (I thought they weren't). We will need to bump the version number and perform this check on all // subsequent IAR versions only ControlFileLoaded = true; } /// <summary> /// Execute the request /// </summary> /// <remarks> /// Only call this once. To load another IAR, construct another request object. /// </remarks> /// <returns> /// A list of the inventory nodes loaded. If folders were loaded then only the root folders are /// returned /// </returns> /// <exception cref="System.Exception">Thrown if load fails.</exception> public HashSet<InventoryNodeBase> Execute() { try { string filePath = "ERROR"; List<InventoryFolderBase> folderCandidates = InventoryArchiveUtils.FindFolderByPath( m_scene.InventoryService, m_userInfo.PrincipalID, m_invPath); if (folderCandidates.Count == 0) { // Possibly provide an option later on to automatically create this folder if it does not exist m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath); return m_loadedNodes; } m_rootDestinationFolder = folderCandidates[0]; archive = new TarArchiveReader(m_loadStream); byte[] data; TarArchiveReader.TarEntryType entryType; while ((data = archive.ReadEntry(out filePath, out entryType)) != null) { if (filePath == ArchiveConstants.CONTROL_FILE_PATH) { LoadControlFile(filePath, data); } else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { LoadAssetFile(filePath, data); } else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH)) { LoadInventoryFile(filePath, entryType, data); } } archive.Close(); m_log.DebugFormat( "[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures", m_successfulAssetRestores, m_failedAssetRestores); m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", m_successfulItemRestores); return m_loadedNodes; } finally { m_loadStream.Close(); } } public void Close() { if (m_loadStream != null) m_loadStream.Close(); } /// <summary> /// Replicate the inventory paths in the archive to the user's inventory as necessary. /// </summary> /// <param name="iarPath">The item archive path to replicate</param> /// <param name="rootDestinationFolder">The root folder for the inventory load</param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// This method will add more folders if necessary /// </param> /// <param name="loadedNodes"> /// Track the inventory nodes created. /// </param> /// <returns>The last user inventory folder created or found for the archive path</returns> public InventoryFolderBase ReplicateArchivePathToUserInventory( string iarPath, InventoryFolderBase rootDestFolder, Dictionary <string, InventoryFolderBase> resolvedFolders, HashSet<InventoryNodeBase> loadedNodes) { string iarPathExisting = iarPath; // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Loading folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID); InventoryFolderBase destFolder = ResolveDestinationFolder(rootDestFolder, ref iarPathExisting, resolvedFolders); // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: originalArchivePath [{0}], section already loaded [{1}]", // iarPath, iarPathExisting); string iarPathToCreate = iarPath.Substring(iarPathExisting.Length); CreateFoldersForPath(destFolder, iarPathExisting, iarPathToCreate, resolvedFolders, loadedNodes); return destFolder; } /// <summary> /// Resolve a destination folder /// </summary> /// /// We require here a root destination folder (usually the root of the user's inventory) and the archive /// path. We also pass in a list of previously resolved folders in case we've found this one previously. /// /// <param name="archivePath"> /// The item archive path to resolve. The portion of the path passed back is that /// which corresponds to the resolved desintation folder. /// <param name="rootDestinationFolder"> /// The root folder for the inventory load /// </param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// </param> /// <returns> /// The folder in the user's inventory that matches best the archive path given. If no such folder was found /// then the passed in root destination folder is returned. /// </returns> protected InventoryFolderBase ResolveDestinationFolder( InventoryFolderBase rootDestFolder, ref string archivePath, Dictionary <string, InventoryFolderBase> resolvedFolders) { // string originalArchivePath = archivePath; while (archivePath.Length > 0) { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Trying to resolve destination folder {0}", archivePath); if (resolvedFolders.ContainsKey(archivePath)) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath); return resolvedFolders[archivePath]; } else { if (m_merge) { // TODO: Using m_invPath is totally wrong - what we need to do is strip the uuid from the // iar name and try to find that instead. string plainPath = ArchiveConstants.ExtractPlainPathFromIarPath(archivePath); List<InventoryFolderBase> folderCandidates = InventoryArchiveUtils.FindFolderByPath( m_scene.InventoryService, m_userInfo.PrincipalID, plainPath); if (folderCandidates.Count != 0) { InventoryFolderBase destFolder = folderCandidates[0]; resolvedFolders[archivePath] = destFolder; return destFolder; } } // Don't include the last slash so find the penultimate one int penultimateSlashIndex = archivePath.LastIndexOf("/", archivePath.Length - 2); if (penultimateSlashIndex >= 0) { // Remove the last section of path so that we can see if we've already resolved the parent archivePath = archivePath.Remove(penultimateSlashIndex + 1); } else { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Found no previously created folder for archive path {0}", // originalArchivePath); archivePath = string.Empty; return rootDestFolder; } } } return rootDestFolder; } /// <summary> /// Create a set of folders for the given path. /// </summary> /// <param name="destFolder"> /// The root folder from which the creation will take place. /// </param> /// <param name="iarPathExisting"> /// the part of the iar path that already exists /// </param> /// <param name="iarPathToReplicate"> /// The path to replicate in the user's inventory from iar /// </param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// </param> /// <param name="loadedNodes"> /// Track the inventory nodes created. /// </param> protected void CreateFoldersForPath( InventoryFolderBase destFolder, string iarPathExisting, string iarPathToReplicate, Dictionary <string, InventoryFolderBase> resolvedFolders, HashSet<InventoryNodeBase> loadedNodes) { string[] rawDirsToCreate = iarPathToReplicate.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < rawDirsToCreate.Length; i++) { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0} from IAR", rawDirsToCreate[i]); if (!rawDirsToCreate[i].Contains(ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR)) continue; int identicalNameIdentifierIndex = rawDirsToCreate[i].LastIndexOf( ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR); string newFolderName = rawDirsToCreate[i].Remove(identicalNameIdentifierIndex); newFolderName = InventoryArchiveUtils.UnescapeArchivePath(newFolderName); UUID newFolderId = UUID.Random(); // Asset type has to be Unknown here rather than Folder, otherwise the created folder can't be // deleted once the client has relogged. // The root folder appears to be labelled AssetType.Folder (shows up as "Category" in the client) // even though there is a AssetType.RootCategory destFolder = new InventoryFolderBase( newFolderId, newFolderName, m_userInfo.PrincipalID, (short)AssetType.Unknown, destFolder.ID, 1); m_scene.InventoryService.AddFolder(destFolder); // Record that we have now created this folder iarPathExisting += rawDirsToCreate[i] + "/"; m_log.DebugFormat("[INVENTORY ARCHIVER]: Created folder {0} from IAR", iarPathExisting); resolvedFolders[iarPathExisting] = destFolder; if (0 == i) loadedNodes.Add(destFolder); } } /// <summary> /// Load an item from the archive /// </summary> /// <param name="filePath">The archive path for the item</param> /// <param name="data">The raw item data</param> /// <param name="rootDestinationFolder">The root destination folder for loaded items</param> /// <param name="nodesLoaded">All the inventory nodes (items and folders) loaded so far</param> protected InventoryItemBase LoadItem(byte[] data, InventoryFolderBase loadFolder) { InventoryItemBase item = UserInventoryItemSerializer.Deserialize(data); // Don't use the item ID that's in the file item.ID = UUID.Random(); UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_scene.UserAccountService); if (UUID.Zero != ospResolvedId) // The user exists in this grid { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Found creator {0} via OSPA resolution", ospResolvedId); item.CreatorIdAsUuid = ospResolvedId; // Don't preserve the OSPA in the creator id (which actually gets persisted to the // database). Instead, replace with the UUID that we found. item.CreatorId = ospResolvedId.ToString(); item.CreatorData = string.Empty; } else if (item.CreatorData == null || item.CreatorData == String.Empty) { item.CreatorId = m_userInfo.PrincipalID.ToString(); item.CreatorIdAsUuid = new UUID(item.CreatorId); } item.Owner = m_userInfo.PrincipalID; // Reset folder ID to the one in which we want to load it item.Folder = loadFolder.ID; // Record the creator id for the item's asset so that we can use it later, if necessary, when the asset // is loaded. // FIXME: This relies on the items coming before the assets in the TAR file. Need to create stronger // checks for this, and maybe even an external tool for creating OARs which enforces this, rather than // relying on native tar tools. m_creatorIdForAssetId[item.AssetID] = item.CreatorIdAsUuid; m_scene.AddInventoryItem(item); return item; } /// <summary> /// Load an asset /// </summary> /// <param name="assetFilename"></param> /// <param name="data"></param> /// <returns>true if asset was successfully loaded, false otherwise</returns> private bool LoadAsset(string assetPath, byte[] data) { //IRegionSerialiser serialiser = scene.RequestModuleInterface<IRegionSerialiser>(); // Right now we're nastily obtaining the UUID from the filename string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR); if (i == -1) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping", assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR); return false; } string extension = filename.Substring(i); string rawUuid = filename.Remove(filename.Length - extension.Length); UUID assetId = new UUID(rawUuid); if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension)) { sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension]; if (assetType == (sbyte)AssetType.Unknown) { m_log.WarnFormat("[INVENTORY ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, assetId); } else if (assetType == (sbyte)AssetType.Object) { if (m_creatorIdForAssetId.ContainsKey(assetId)) { string xmlData = Utils.BytesToString(data); List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>(); CoalescedSceneObjects coa = null; if (CoalescedSceneObjectsSerializer.TryFromXml(xmlData, out coa)) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Loaded coalescence {0} has {1} objects", assetId, coa.Count); sceneObjects.AddRange(coa.Objects); } else { sceneObjects.Add(SceneObjectSerializer.FromOriginalXmlFormat(xmlData)); } foreach (SceneObjectGroup sog in sceneObjects) foreach (SceneObjectPart sop in sog.Parts) if (sop.CreatorData == null || sop.CreatorData == "") sop.CreatorID = m_creatorIdForAssetId[assetId]; if (coa != null) data = Utils.StringToBytes(CoalescedSceneObjectsSerializer.ToXml(coa)); else data = Utils.StringToBytes(SceneObjectSerializer.ToOriginalXmlFormat(sceneObjects[0])); } } //m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); AssetBase asset = new AssetBase(assetId, "From IAR", assetType, UUID.Zero.ToString()); asset.Data = data; m_scene.AssetService.Store(asset); return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}", assetPath, extension); return false; } } /// <summary> /// Load control file /// </summary> /// <param name="path"></param> /// <param name="data"></param> public void LoadControlFile(string path, byte[] data) { XDocument doc = XDocument.Parse(Encoding.ASCII.GetString(data)); XElement archiveElement = doc.Element("archive"); int majorVersion = int.Parse(archiveElement.Attribute("major_version").Value); int minorVersion = int.Parse(archiveElement.Attribute("minor_version").Value); string version = string.Format("{0}.{1}", majorVersion, minorVersion); if (majorVersion > MAX_MAJOR_VERSION) { throw new Exception( string.Format( "The IAR you are trying to load has major version number of {0} but this version of OpenSim can only load IARs with major version number {1} and below", majorVersion, MAX_MAJOR_VERSION)); } ControlFileLoaded = true; m_log.InfoFormat("[INVENTORY ARCHIVER]: Loading IAR with version {0}", version); } /// <summary> /// Load inventory file /// </summary> /// <param name="path"></param> /// <param name="entryType"></param> /// <param name="data"></param> protected void LoadInventoryFile(string path, TarArchiveReader.TarEntryType entryType, byte[] data) { if (!ControlFileLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list {0} before {1}. Aborting load", ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.INVENTORY_PATH)); if (m_assetsLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list all {0} before {1}. Aborting load", ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH)); path = path.Substring(ArchiveConstants.INVENTORY_PATH.Length); // Trim off the file portion if we aren't already dealing with a directory path if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) path = path.Remove(path.LastIndexOf("/") + 1); InventoryFolderBase foundFolder = ReplicateArchivePathToUserInventory( path, m_rootDestinationFolder, m_resolvedFolders, m_loadedNodes); if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) { InventoryItemBase item = LoadItem(data, foundFolder); if (item != null) { m_successfulItemRestores++; // If we aren't loading the folder containing the item then well need to update the // viewer separately for that item. if (!m_loadedNodes.Contains(foundFolder)) m_loadedNodes.Add(item); } } m_inventoryNodesLoaded = true; } /// <summary> /// Load asset file /// </summary> /// <param name="path"></param> /// <param name="data"></param> protected void LoadAssetFile(string path, byte[] data) { if (!ControlFileLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list {0} before {1}. Aborting load", ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.ASSETS_PATH)); if (!m_inventoryNodesLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list all {0} before {1}. Aborting load", ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH)); if (LoadAsset(path, data)) m_successfulAssetRestores++; else m_failedAssetRestores++; if ((m_successfulAssetRestores) % 50 == 0) m_log.DebugFormat( "[INVENTORY ARCHIVER]: Loaded {0} assets...", m_successfulAssetRestores); m_assetsLoaded = true; } } }
using Marten.Schema; using Marten.Linq.SoftDeletes; using Shouldly; using System; using System.Linq; using System.Threading.Tasks; using Marten.Testing.Harness; using Xunit; namespace Marten.Testing.Acceptance { [Collection("metadata")] public class document_metadata_specs : OneOffConfigurationsContext { public document_metadata_specs() : base("metadata") { } [Fact] public void set_the_metadata_projections_through_the_fluent_interface() { StoreOptions(_ => { _.Schema.For<DocWithMeta>().Metadata(m => { m.Version.MapTo(x => x.Version); m.LastModified.MapTo(x => x.LastModified); m.IsSoftDeleted.MapTo(x => x.Deleted); m.SoftDeletedAt.MapTo(x => x.DeletedAt); }) .SoftDeleted(); }); theStore.Storage.MappingFor(typeof(DocWithMeta)) .Metadata.Version.Member.Name.ShouldBe(nameof(DocWithMeta.Version)); theStore.Storage.MappingFor(typeof(DocWithMeta)) .Metadata.LastModified.Member.Name.ShouldBe(nameof(DocWithMeta.LastModified)); theStore.Storage.MappingFor(typeof(DocWithMeta)) .Metadata.IsSoftDeleted.Member.Name.ShouldBe(nameof(DocWithMeta.Deleted)); theStore.Storage.MappingFor(typeof(DocWithMeta)) .Metadata.SoftDeletedAt.Member.Name.ShouldBe(nameof(DocWithMeta.DeletedAt)); } [Fact] public void set_the_metadata_projections_via_attributes() { theStore.Storage.MappingFor(typeof(DocWithAttributeMeta)) .Metadata.Version.Member.Name.ShouldBe(nameof(DocWithAttributeMeta.Version)); theStore.Storage.MappingFor(typeof(DocWithAttributeMeta)) .Metadata.LastModified.Member.Name.ShouldBe(nameof(DocWithAttributeMeta.LastModified)); } [Fact] public void doc_has_projected_data_after_storage() { StoreOptions(c => { c.Schema.For<DocWithMeta>() .Metadata(m => m.LastModified.MapTo(x => x.LastModified)); }); var doc = new DocWithMeta(); using (var session = theStore.OpenSession()) { session.Store(doc); session.MetadataFor(doc).ShouldBeNull(); session.SaveChanges(); } using (var session = theStore.OpenSession()) { var loaded = session.Load<DocWithMeta>(doc.Id); loaded.LastModified.ShouldNotBe(DateTimeOffset.MinValue); } } [Fact] public void doc_metadata_is_read_only_on_store() { var doc = new DocWithAttributeMeta(); using (var session = theStore.OpenSession()) { doc.LastModified = DateTime.UtcNow.AddYears(-1); doc.Version = Guid.Empty; session.Store(doc); session.MetadataFor(doc).ShouldBeNull(); session.SaveChanges(); } using (var session = theStore.OpenSession()) { var loaded = session.Load<DocWithAttributeMeta>(doc.Id); loaded.DocType.ShouldBeNull(); loaded.TenantId.ShouldBeNull(); (DateTime.UtcNow - loaded.LastModified.ToUniversalTime()).ShouldBeLessThan(TimeSpan.FromMinutes(1)); loaded.Deleted.ShouldBeFalse(); loaded.DeletedAt.ShouldBeNull(); loaded.Version.ShouldNotBe(Guid.Empty); } } [Fact] public void doc_metadata_is_mapped_for_query_includes() { StoreOptions(c => { c.Schema.For<DocWithMeta>().Metadata(m => m.LastModified.MapTo(x => x.LastModified)); }); var include = new IncludedDocWithMeta(); var doc = new DocWithMeta(); using (var session = theStore.OpenSession()) { session.Store(include); doc.IncludedDocId = include.Id; session.Store(doc); session.MetadataFor(include).ShouldBeNull(); session.MetadataFor(doc).ShouldBeNull(); session.SaveChanges(); } using (var session = theStore.OpenSession()) { IncludedDocWithMeta loadedInclude = null; var loaded = session.Query<DocWithMeta>().Include<IncludedDocWithMeta>(d => d.IncludedDocId, i => loadedInclude = i).Single(d => d.Id == doc.Id); loaded.ShouldNotBeNull(); loadedInclude.ShouldNotBeNull(); loadedInclude.Version.ShouldNotBe(Guid.Empty); } } [Fact] public void doc_metadata_is_updated_for_user_supplied_query() { StoreOptions(c => { c.Schema.For<DocWithMeta>().Metadata(m => m.LastModified.MapTo(x => x.LastModified)); }); var doc = new DocWithMeta(); DateTimeOffset lastMod = DateTime.UtcNow; using (var session = theStore.OpenSession()) { session.Store(doc); session.MetadataFor(doc).ShouldBeNull(); session.SaveChanges(); } using (var session = theStore.OpenSession()) { var userQuery = session.Query<DocWithMeta>($"where data ->> 'Id' = '{doc.Id.ToString()}'").Single(); userQuery.Description = "updated via a user SQL query"; userQuery.LastModified.ShouldNotBe(DateTimeOffset.MinValue); lastMod = userQuery.LastModified; session.Store(userQuery); session.SaveChanges(); } using (var session = theStore.OpenSession()) { var userQuery = session.Query<DocWithMeta>($"where data ->> 'Id' = '{doc.Id.ToString()}'").Single(); userQuery.LastModified.ShouldBeGreaterThanOrEqualTo(lastMod); } } [Fact] public async Task doc_metadata_is_mapped_for_conjoined_tenant() { StoreOptions(c => { c.Schema.For<DocWithMeta>() .MultiTenanted() .Metadata(m => { m.TenantId.MapTo(x => x.TenantId); m.LastModified.MapTo(x => x.LastModified); }); }); var doc = new DocWithMeta(); var tenant = "TENANT_A"; using (var session = theStore.OpenSession(tenant)) { doc.LastModified = DateTime.UtcNow.AddYears(-1); session.Store(doc); (await session.MetadataForAsync(doc)).ShouldBeNull(); await session.SaveChangesAsync(); } using (var session = theStore.OpenSession(tenant)) { session.Query<DocWithMeta>().Count(d => d.TenantId == tenant).ShouldBe(1); var loaded = await session.Query<DocWithMeta>().Where(d => d.Id == doc.Id).FirstOrDefaultAsync(); loaded.TenantId.ShouldBe(tenant); loaded.LastModified.ShouldNotBe(DateTimeOffset.MinValue); // it's pretty well impossible to compare timestamps } } [Fact] public async Task doc_metadata_is_mapped_for_bulk_inserted_conjoined_tenant() { StoreOptions(c => { c.Schema.For<DocWithMeta>() .MultiTenanted() .Metadata(m => { m.TenantId.MapTo(x => x.TenantId); m.LastModified.MapTo(x => x.LastModified); }); }); var doc = new DocWithMeta(); var tenant = "TENANT_A"; await theStore.BulkInsertAsync(tenant, new DocWithMeta[] { doc }); using var session = theStore.OpenSession(tenant); session.Query<DocWithMeta>().Count(d => d.TenantId == tenant).ShouldBe(1); var loaded = await session.Query<DocWithMeta>().Where(d => d.Id == doc.Id).FirstOrDefaultAsync(); loaded.TenantId.ShouldBe(tenant); (DateTime.UtcNow - loaded.LastModified.ToUniversalTime()).ShouldBeLessThan(TimeSpan.FromMinutes(1)); } public void doc_metadata_is_mapped_for_doc_hierarchies() { StoreOptions(c => { c.Schema.For<DocWithMeta>() .AddSubClassHierarchy(typeof(RedDocWithMeta), typeof(BlueDocWithMeta), typeof(GreenDocWithMeta), typeof(EmeraldGreenDocWithMeta)) .SoftDeleted() .Metadata(m => { m.IsSoftDeleted.MapTo(x => x.Deleted); m.SoftDeletedAt.MapTo(x => x.DeletedAt); m.DocumentType.MapTo(x => x.DocType); }); }); using (var session = theStore.OpenSession()) { var doc = new DocWithMeta { Description = "transparent" }; var red = new RedDocWithMeta { Description = "red doc" }; var green = new GreenDocWithMeta { Description = "green doc" }; var blue = new BlueDocWithMeta { Description = "blue doc" }; var emerald = new EmeraldGreenDocWithMeta { Description = "emerald doc" }; session.Store(doc, red, green, blue, emerald); session.SaveChanges(); } using (var session = theStore.OpenSession()) { session.Query<DocWithMeta>().Count(d => d.DocType == "BASE").ShouldBe(1); session.Query<DocWithMeta>().Count(d => d.DocType == "blue_doc_with_meta").ShouldBe(1); session.Query<DocWithMeta>().Count(d => d.DocType == "red_doc_with_meta").ShouldBe(1); session.Query<DocWithMeta>().Count(d => d.DocType == "green_doc_with_meta").ShouldBe(1); session.Query<DocWithMeta>().Count(d => d.DocType == "emerald_green_doc_with_meta").ShouldBe(1); var redDocs = session.Query<RedDocWithMeta>().ToList(); redDocs.Count.ShouldBe(1); redDocs.First().DocType.ShouldBe("red_doc_with_meta"); session.Delete(redDocs.First()); session.SaveChanges(); } } [Fact] public void versions_are_assigned_during_bulk_inserts_as_field() { var docs = new AttVersionedDoc[100]; for (var i = 0; i < docs.Length; i++) { docs[i] = new AttVersionedDoc(); } theStore.BulkInsert(docs); foreach (var doc in docs) { doc.Version.ShouldNotBe(Guid.Empty); } using (var session = theStore.OpenSession()) { session.Query<AttVersionedDoc>().Count(d => d.Version != Guid.Empty).ShouldBe(100); } } [Fact] public void versions_are_assigned_during_bulk_inserts_as_prop() { var docs = new PropVersionedDoc[100]; for (int i = 0; i < docs.Length; i++) { docs[i] = new PropVersionedDoc(); } theStore.BulkInsert(docs); foreach (var doc in docs) { doc.Version.ShouldNotBe(Guid.Empty); } using (var session = theStore.OpenSession()) { session.Query<PropVersionedDoc>().Count(d => d.Version != Guid.Empty).ShouldBe(100); } } } public class DocWithMeta { public Guid Id { get; set; } public string Description { get; set; } public Guid Version { get; set; } public DateTimeOffset LastModified { get; set; } public string TenantId { get; private set; } public bool Deleted { get; private set; } public DateTimeOffset? DeletedAt { get; private set; } public string DocType { get; private set; } public Guid IncludedDocId { get; set; } } internal class RedDocWithMeta: DocWithMeta { public int RedHue { get; set; } } internal class BlueDocWithMeta: DocWithMeta { public int BlueHue { get; set; } } internal class GreenDocWithMeta: DocWithMeta { public int GreenHue { get; set; } } internal class EmeraldGreenDocWithMeta: GreenDocWithMeta { public string Label { get; set; } } public class IncludedDocWithMeta { public Guid Id { get; set; } [Version] public Guid Version { get; private set; } public DateTimeOffset LastModified { get; private set; } } public class DocWithAttributeMeta { public Guid Id { get; set; } public string TenantId { get; private set; } public string DocType { get; private set; } public bool Deleted { get; private set; } public DateTime? DeletedAt { get; private set; } [Version] public Guid Version { get; set; } [LastModifiedMetadata] public DateTimeOffset LastModified { get; set; } } } namespace Marten.Testing.Acceptance.StructuralTypes { [StructuralTyped] public class DocWithMeta { public Guid Id { get; set; } public DateTime LastModified { get; set; } public string DocType { get; private set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using System.Xml.Serialization; using Castle.DynamicProxy; using XeroConnector.Interfaces; using XeroConnector.Model; using XeroConnector.Model.Interfaces; using XeroConnector.Model.Proxy; using XeroConnector.Util; namespace XeroConnector { public class XeroSession : IXeroSession { private readonly IXeroConnection _connection; private static readonly ProxyGenerator ProxyGenerator = new ProxyGenerator(); private static readonly Dictionary<Type, XmlSerializer> Serializers; static XeroSession() { Serializers = new Dictionary<Type, XmlSerializer>(); Serializers[typeof(Account)] = new XmlSerializer(typeof(Account)); Serializers[typeof(Contact)] = new XmlSerializer(typeof(Contact)); Serializers[typeof(CreditNote)] = new XmlSerializer(typeof(CreditNote)); Serializers[typeof(Currency)] = new XmlSerializer(typeof(Currency)); Serializers[typeof(Invoice)] = new XmlSerializer(typeof(Invoice)); Serializers[typeof(Organisation)] = new XmlSerializer(typeof(Organisation)); Serializers[typeof(Payment)] = new XmlSerializer(typeof(Payment)); Serializers[typeof(TaxRate)] = new XmlSerializer(typeof(TaxRate)); Serializers[typeof(TrackingCategory)] = new XmlSerializer(typeof(TrackingCategory)); } public XeroSession(IXeroConnection connection) { _connection = connection; } public void LoadContactDetails(IContact contact) { LazyLoadModel<Contact, IContact>(contact, () => _connection.MakeGetContactRequest(contact.ContactID), "Contacts"); } public void LoadCreditNoteDetails(ICreditNote creditNote) { LazyLoadModel<CreditNote, ICreditNote>(creditNote, () => _connection.MakeGetCreditNoteRequest(creditNote.CreditNoteID), "CreditNotes"); } public void GetInvoiceDetails(IInvoice invoice) { LazyLoadModel<Invoice, IInvoice>(invoice, () => _connection.MakeGetInvoiceRequest(invoice.InvoiceID), "Invoices"); } private void LazyLoadModel<TModel, TIModel>(TIModel existingModel, Func<XDocument> getModel, string elementToFind) where TModel : IModel, TIModel { var doc = getModel(); TIModel model = GetSingleModel<TModel>(GetFirstChild(doc, elementToFind)); PropertyCopier<TIModel, TIModel>.Copy(model, existingModel); } public IAccount GetAccount(Guid accountID) { var doc = _connection.MakeGetAccountRequest(accountID); return GetSingleModel<Account>(GetFirstChild(doc, "Accounts")); } public IEnumerable<IAccount> GetAccounts(DateTime? modifiedAfter = null, string whereClause = null, string orderBy = null) { var doc = _connection.MakeGetAccountsRequest(modifiedAfter, whereClause, orderBy); return GetMultipleModels<Account>(doc, "Accounts"); } public IContact GetContact(string contactIdentifier) { var doc = _connection.MakeGetContactRequest(contactIdentifier); return GetSingleModel<Contact>(GetFirstChild(doc, "Contacts")); } public IContact GetContact(Guid contactID) { var doc = _connection.MakeGetContactRequest(contactID); return GetSingleModel<Contact>(GetFirstChild(doc, "Contacts")); } public IEnumerable<IContact> GetContacts(DateTime? modifiedAfter = null, string whereClause = null, string orderBy = null) { var doc = _connection.MakeGetContactsRequest(modifiedAfter, whereClause, orderBy); return GetMultipleModels<Contact>(doc, "Contacts"); } public ICreditNote GetCreditNote(string creditNoteIdentifier) { var doc = _connection.MakeGetCreditNoteRequest(creditNoteIdentifier); return GetSingleModel<CreditNote>(GetFirstChild(doc, "CreditNotes")); } public ICreditNote GetCreditNote(Guid creditNoteID) { var doc = _connection.MakeGetCreditNoteRequest(creditNoteID); return GetSingleModel<CreditNote>(GetFirstChild(doc, "CreditNotes")); } public IEnumerable<ICreditNote> GetCreditNotes(DateTime? modifiedAfter = null, string whereClause = null, string orderBy = null) { var doc = _connection.MakeGetCreditNotesRequest(modifiedAfter, whereClause, orderBy); return GetMultipleWrappedModels<CreditNote, ICreditNote>(doc, "CreditNotes"); } public IEnumerable<Currency> GetCurrencies(DateTime? modifiedAfter = null, string whereClause = null, string orderBy = null) { var doc = _connection.MakeGetCurrenciesRequest(modifiedAfter, whereClause, orderBy); return GetMultipleModels<Currency>(doc, "Currencies"); } public IInvoice GetInvoice(Guid invoiceID) { var doc = _connection.MakeGetInvoiceRequest(invoiceID); IInvoice invoice = GetSingleWrappedModel<Invoice, IInvoice>(doc, "Invoices", true); return invoice; } public IEnumerable<IInvoice> GetInvoices(DateTime? modifiedAfter = null, string whereClause = null, string orderBy = null) { var doc = _connection.MakeGetInvoicesRequest(modifiedAfter, whereClause, orderBy); return GetMultipleWrappedModels<Invoice, IInvoice>(doc, "Invoices"); } public Organisation GetOrganisation() { var doc = _connection.MakeGetOrganisationRequest(); return GetSingleModel<Organisation>(GetFirstChild(doc, "Organisations")); } public IEnumerable<ITaxRate> GetTaxRates(string taxType = null, string whereClause = null, string orderBy = null) { var doc = _connection.MakeGetTaxRatesRequest(taxType, whereClause, orderBy); return GetMultipleModels<TaxRate>(doc, "TaxRates"); } public TrackingCategory GetTrackingCategory(Guid categoryID) { var doc = _connection.MakeGetTrackingCategoryRequest(categoryID); return GetSingleModel<TrackingCategory>(GetFirstChild(doc, "TrackingCategories")); } public IEnumerable<TrackingCategory> GetTrackingCategories(string whereClause = null, string orderBy = null) { var doc = _connection.MakeGetTrackingCategoriesRequest(whereClause, orderBy); return GetMultipleModels<TrackingCategory>(doc, "TrackingCategories"); } private static T GetWrappedModel<T>(T model) { var pgo = new ProxyGenerationOptions(new ModelHook()); return (T)ProxyGenerator.CreateInterfaceProxyWithTargetInterface(typeof(T), model, pgo, new ModelInterceptor()); } private IEnumerable<U> GetMultipleWrappedModels<T, U>(XContainer doc, string elementToFind) where T : U where U : IModel { var root = doc.Elements().First(); if (root == null) return new U[0]; var element = root.Element(elementToFind); if (element == null) return new U[0]; var elements = element.Elements(); IEnumerable<T> models = elements.Select(elm => (GetSingleModel<T>(elm))); return models.Select(model => { model.XeroSession = this; return GetWrappedModel<U>(model); }).ToList(); } private IEnumerable<T> GetMultipleModels<T>(XDocument doc, string elementToFind) where T : IModel { var root = doc.Elements().First(); if (root == null) return new T[0]; var element = root.Element(elementToFind); if (element == null) return new T[0]; var elements = element.Elements(); IEnumerable<T> models = elements.Select(elm => (GetSingleModel<T>(elm))); return models; } private U GetSingleWrappedModel<T, U>(XContainer doc, string elementToFind, bool isLoaded = false) where T : U where U : IModel { var model = GetSingleModel<T>(GetFirstChild(doc, elementToFind)); model.IsLoaded = isLoaded; return GetWrappedModel<U>(model); } private T GetSingleModel<T>(XElement element) where T : IModel { var model = (T)Serializers[typeof(T)].Deserialize(new StringReader(element.ToString())); model.XeroSession = this; return model; } private static XElement GetFirstChild(XContainer doc, string elementToFind) { var root = doc.Elements().FirstOrDefault(); if (root == null) return null; var element = root.Element(elementToFind); if (element == null) return null; return element.Elements().FirstOrDefault(); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel.Design.Serialization; using System.Windows.Forms; using Microsoft.MultiverseInterfaceStudio.FrameXml.Serialization; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Collections; using Microsoft.MultiverseInterfaceStudio.FrameXml.Controls; namespace Microsoft.MultiverseInterfaceStudio.FrameXml { public partial class FrameXmlDesignerLoader { /// <summary> /// Returns the type of the control corresponding to the serialization object passed /// </summary> /// <param name="serializationObject">The serialization object.</param> /// <returns></returns> private static Type GetControlType(SerializationObject serializationObject) { //LayoutFrameType layoutFrame = serializationObject as LayoutFrameType; //if (layoutFrame != null && layoutFrame.@virtual) // return typeof(VirtualComponent); // converts serialization object type name to control type name string typeName = serializationObject.GetType().Name; if (typeName.EndsWith("Type")) typeName = typeName.Substring(0, typeName.Length - 4); typeName = typeof(ISerializableControl).Namespace + '.' + typeName; return Type.GetType(typeName); } /// <summary> /// Creates a control corresponding to the serialization object passed. /// </summary> /// <param name="serializationObject">The serialization object.</param> /// <param name="parent">parent control</param> /// <returns></returns> private ISerializableControl CreateControl(SerializationObject serializationObject, Control parent) { return CreateControl(serializationObject, parent, false); } /// <summary> /// Creates a control corresponding to the serialization object passed. /// </summary> /// <param name="serializationObject">The serialization object.</param> /// <param name="parent">parent control</param> /// <param name="inherited">true if the control is inherited (should be locked)</param> /// <returns></returns> private ISerializableControl CreateControl(SerializationObject serializationObject, Control parent, bool inherited) { Type controlType = GetControlType(serializationObject); if (controlType == null) return null; IComponent component = LoaderHost.CreateComponent(controlType); ISerializableControl iControl = (ISerializableControl) component; iControl.DesignerLoader = this; iControl.SerializationObject = serializationObject; LayoutFrameType layoutFrameType = serializationObject as LayoutFrameType; if (layoutFrameType != null) { if (!inherited) component.Site.Name = layoutFrameType.ExpandedName; BaseControl control = iControl as BaseControl; if (control != null) { control.Inherited = inherited; Size size = layoutFrameType.SizeInPixels; if (!size.IsEmpty) control.Size = size; else { control.SetDefaultSize(); } if (parent != null) { control.Parent = parent; } } } return iControl; } public Controls.Ui RootControl { get { return LoaderHost.RootComponent as Controls.Ui; } } public BaseControlCollection BaseControls { get; private set; } public bool IsLoading { get; set; } private void CreateRootControl(Serialization.Ui ui) { this.IsLoading = true; try { // just create the root component this.CreateControl(ui, null); this.BaseControls = new BaseControlCollection(this.RootControl); } finally { this.IsLoading = false; } } /// <summary> /// holds the top level objects from the designer /// it is used during serialization (these objects will be removed from the hierarchy) /// </summary> private List<SerializationObject> objectsInView = new List<SerializationObject>(); public void ReloadControls() { this.IsLoading = true; try { // remove existing controls DestroyControls(); objectsInView.Clear(); RecreateFrameXmlPanes(); foreach (SerializationObject serializationObject in frameXmlHierarchy.Controls) { LayoutFrameType layoutFrame = serializationObject as LayoutFrameType; if (ShouldDisplayObject(layoutFrame)) { frameXmlPane.AddPane(VirtualControlName); Trace.WriteLine(String.Format("Create {0}", layoutFrame.name)); CreateControls(serializationObject, this.RootControl); objectsInView.Add(serializationObject); } } } finally { this.IsLoading = false; } RootControl.RepositionUi(); } private void RecreateFrameXmlPanes() { var virtualPaneNames = from layoutFrame in frameXmlHierarchy.Controls.OfType<LayoutFrameType>() where layoutFrame.@virtual select layoutFrame.name; frameXmlPane.RecreatePanes(virtualPaneNames, VirtualControlName); } private void DestroyControls() { var controls = this.RootControl.Controls.OfType<BaseControl>(); foreach (BaseControl control in controls.ToList<BaseControl>()) { Trace.WriteLine(String.Format("Destroy {0}", control.Name)); control.DesignerLoader.Host.DestroyComponent(control); } } private Control CreateControls(SerializationObject serializationObject, Control parent) { return CreateControls(serializationObject, parent, false); } /// <summary> /// Creates the controls from the hierarchy of Serialization object. /// </summary> /// <param name="serializationObject">The serialization object.</param> /// <param name="parent">The parent.</param> /// <remarks>Recursive</remarks> private Control CreateControls(SerializationObject serializationObject, Control parent, bool inherited) { Control control = this.CreateControl(serializationObject, parent, inherited) as Control; // bypass controls that cannot be created by the control factory (and the virtual ones) if (control == null) { Debug.WriteLine(String.Format("Bypassing object '{0}' during control creation.", serializationObject)); } else { parent = control; } CreateLayers(serializationObject, parent, false); foreach (SerializationObject childItem in serializationObject.Controls) { CreateControls(childItem, parent, inherited); } LayoutFrameType layoutFrame = serializationObject as LayoutFrameType; if (layoutFrame != null) { LayoutFrameType inheritedLayoutFrame = layoutFrame.InheritedObject; if (inheritedLayoutFrame != null) { CreateLayers(inheritedLayoutFrame, parent, true); foreach (SerializationObject childItem in inheritedLayoutFrame.Controls) { CreateControls(childItem, parent, true); } } } return control; } /// <summary> /// Determines whether the specified serialization object should be displayed in the designer /// </summary> /// <param name="serializationObject">The serialization object.</param> /// <returns> /// <c>true</c> if the object should be displayed; otherwise, <c>false</c>. /// </returns> private bool ShouldDisplayObject(LayoutFrameType layoutFrame) { if (layoutFrame == null) return false; return ((layoutFrame.@virtual && (VirtualControlName == layoutFrame.name)) || (!layoutFrame.@virtual && String.IsNullOrEmpty(VirtualControlName))); } private void CreateLayers(SerializationObject serializationObject, Control parent, bool inherited) { FrameType frameType = serializationObject as FrameType; if (frameType != null) { foreach (FrameTypeLayers layers in frameType.LayersList) { foreach (FrameTypeLayersLayer layer in layers.Layer) { foreach (SerializationObject so in layer.Layerables) { ILayerable layerable = CreateControl(so, parent, inherited) as ILayerable; layerable.LayerLevel = layer.level; } } } } } } }
using System; using System.Collections.Generic; using UnityEngine; namespace NGUI.Internal { public static class NGUITools { private static float mGlobalVolume = 1f; private static Color mInvisible = new Color(0f, 0f, 0f, 0f); private static AudioListener mListener; private static bool mLoaded; private static void Activate(Transform t) { SetActiveSelf(t.gameObject, true); int index = 0; int childCount = t.childCount; while (index < childCount) { if (t.GetChild(index).gameObject.activeSelf) { return; } index++; } int num3 = 0; int num4 = t.childCount; while (num3 < num4) { Activate(t.GetChild(num3)); num3++; } } public static GameObject AddChild(GameObject parent) { GameObject obj2 = new GameObject(); if (parent != null) { Transform transform = obj2.transform; transform.parent = parent.transform; transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; transform.localScale = Vector3.one; obj2.layer = parent.layer; } return obj2; } public static T AddChild<T>(GameObject parent) where T: Component { GameObject obj2 = AddChild(parent); obj2.name = GetName<T>(); return obj2.AddComponent<T>(); } public static GameObject AddChild(GameObject parent, GameObject prefab) { GameObject obj2 = UnityEngine.Object.Instantiate(prefab) as GameObject; if (obj2 != null && parent != null) { Transform transform = obj2.transform; transform.parent = parent.transform; transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; transform.localScale = Vector3.one; obj2.layer = parent.layer; } return obj2; } public static UISprite AddSprite(GameObject go, UIAtlas atlas, string spriteName) { UIAtlas.Sprite sprite = atlas == null ? null : atlas.GetSprite(spriteName); UISprite sprite2 = AddWidget<UISprite>(go); sprite2.type = sprite == null || sprite.inner == sprite.outer ? UISprite.Type.Simple : UISprite.Type.Sliced; sprite2.atlas = atlas; sprite2.spriteName = spriteName; return sprite2; } public static T AddWidget<T>(GameObject go) where T: UIWidget { int num = CalculateNextDepth(go); T local = AddChild<T>(go); local.depth = num; Transform transform = local.transform; transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; transform.localScale = new Vector3(100f, 100f, 1f); local.gameObject.layer = go.layer; return local; } public static BoxCollider AddWidgetCollider(GameObject go) { if (go == null) { return null; } Collider component = go.GetComponent<Collider>(); BoxCollider collider2 = component as BoxCollider; if (collider2 == null) { if (component != null) { if (Application.isPlaying) { UnityEngine.Object.Destroy(component); } else { UnityEngine.Object.DestroyImmediate(component); } } collider2 = go.AddComponent<BoxCollider>(); } int num = CalculateNextDepth(go); Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(go.transform); collider2.isTrigger = true; collider2.center = bounds.center + Vector3.back * (num * 0.25f); collider2.size = new Vector3(bounds.size.x, bounds.size.y, 0f); return collider2; } public static Color ApplyPMA(Color c) { if (c.a != 1f) { c.r *= c.a; c.g *= c.a; c.b *= c.a; } return c; } public static int CalculateNextDepth(GameObject go) { int a = -1; UIWidget[] componentsInChildren = go.GetComponentsInChildren<UIWidget>(); int index = 0; int length = componentsInChildren.Length; while (index < length) { a = Mathf.Max(a, componentsInChildren[index].depth); index++; } return a + 1; } private static void Deactivate(Transform t) { SetActiveSelf(t.gameObject, false); } public static void Destroy(UnityEngine.Object obj) { if (obj != null) { if (Application.isPlaying) { if (obj is GameObject) { GameObject obj2 = obj as GameObject; obj2.transform.parent = null; } UnityEngine.Object.Destroy(obj); } else { UnityEngine.Object.DestroyImmediate(obj); } } } public static void DestroyImmediate(UnityEngine.Object obj) { if (obj != null) { if (Application.isEditor) { UnityEngine.Object.DestroyImmediate(obj); } else { UnityEngine.Object.Destroy(obj); } } } public static string EncodeColor(Color c) { int num = 16777215 & (NGUIMath.ColorToInt(c) >> 8); return NGUIMath.DecimalToHex(num); } public static T[] FindActive<T>() where T: Component { return UnityEngine.Object.FindObjectsOfType(typeof(T)) as T[]; } public static Camera FindCameraForLayer(int layer) { int num = 1 << layer; Camera[] cameraArray = FindActive<Camera>(); int index = 0; int length = cameraArray.Length; while (index < length) { Camera camera = cameraArray[index]; if ((camera.cullingMask & num) != 0) { return camera; } index++; } return null; } public static T FindInParents<T>(GameObject go) where T: Component { if (go == null) { return null; } object component = go.GetComponent<T>(); if (component == null) { for (Transform transform = go.transform.parent; transform != null; transform = transform.parent) { if (component != null) { break; } component = transform.gameObject.GetComponent<T>(); } } return (T) component; } public static bool GetActive(GameObject go) { return go != null && go.activeInHierarchy; } public static string GetHierarchy(GameObject obj) { string name = obj.name; while (obj.transform.parent != null) { obj = obj.transform.parent.gameObject; name = obj.name + "/" + name; } return "\"" + name + "\""; } public static string GetName<T>() where T: Component { string str = typeof(T).ToString(); if (str.StartsWith("UI")) { return str.Substring(2); } if (str.StartsWith("UnityEngine.")) { str = str.Substring(12); } return str; } public static GameObject GetRoot(GameObject go) { Transform transform2; Transform transform = go.transform; Label_000B: transform2 = transform.parent; if (transform2 != null) { transform = transform2; goto Label_000B; } return transform.gameObject; } public static bool IsChild(Transform parent, Transform child) { if (parent != null && child != null) { while (child != null) { if (child == parent) { return true; } child = child.parent; } return false; } return false; } public static byte[] Load(string fileName) { return null; } public static void MakePixelPerfect(Transform t) { UIWidget component = t.GetComponent<UIWidget>(); if (component != null) { component.MakePixelPerfect(); } else { t.localPosition = Round(t.localPosition); t.localScale = Round(t.localScale); int index = 0; int childCount = t.childCount; while (index < childCount) { MakePixelPerfect(t.GetChild(index)); index++; } } } public static void MarkParentAsChanged(GameObject go) { UIWidget[] componentsInChildren = go.GetComponentsInChildren<UIWidget>(); int index = 0; int length = componentsInChildren.Length; while (index < length) { componentsInChildren[index].ParentHasChanged(); index++; } } public static WWW OpenURL(string url) { WWW www = null; try { www = new WWW(url); } catch (Exception exception) { Debug.LogError(exception.Message); } return www; } public static Color ParseColor(string text, int offset) { int num = (NGUIMath.HexToDecimal(text[offset]) << 4) | NGUIMath.HexToDecimal(text[offset + 1]); int num2 = (NGUIMath.HexToDecimal(text[offset + 2]) << 4) | NGUIMath.HexToDecimal(text[offset + 3]); int num3 = (NGUIMath.HexToDecimal(text[offset + 4]) << 4) | NGUIMath.HexToDecimal(text[offset + 5]); const float num4 = 0.003921569f; return new Color(num4 * num, num4 * num2, num4 * num3); } public static int ParseSymbol(string text, int index, List<Color> colors, bool premultiply) { int length = text.Length; if (index + 2 < length) { if (text[index + 1] == '-') { if (text[index + 2] == ']') { if (colors != null && colors.Count > 1) { colors.RemoveAt(colors.Count - 1); } return 3; } } else if (index + 7 < length && text[index + 7] == ']') { if (colors != null) { Color c = ParseColor(text, index + 1); if (EncodeColor(c) != text.Substring(index + 1, 6).ToUpper()) { return 0; } Color color2 = colors[colors.Count - 1]; c.a = color2.a; if (premultiply && c.a != 1f) { c = Color.Lerp(mInvisible, c, c.a); } colors.Add(c); } return 8; } } return 0; } public static AudioSource PlaySound(AudioClip clip) { return PlaySound(clip, 1f, 1f); } public static AudioSource PlaySound(AudioClip clip, float volume) { return PlaySound(clip, volume, 1f); } public static AudioSource PlaySound(AudioClip clip, float volume, float pitch) { volume *= soundVolume; if (clip != null && volume > 0.01f) { if (mListener == null) { mListener = UnityEngine.Object.FindObjectOfType(typeof(AudioListener)) as AudioListener; if (mListener == null) { Camera main = Camera.main; if (main == null) { main = UnityEngine.Object.FindObjectOfType(typeof(Camera)) as Camera; } if (main != null) { mListener = main.gameObject.AddComponent<AudioListener>(); } } } if (mListener != null && mListener.enabled && GetActive(mListener.gameObject)) { AudioSource audio = mListener.audio; if (audio == null) { audio = mListener.gameObject.AddComponent<AudioSource>(); } audio.pitch = pitch; audio.PlayOneShot(clip, volume); return audio; } } return null; } public static int RandomRange(int min, int max) { if (min == max) { return min; } return UnityEngine.Random.Range(min, max + 1); } public static Vector3 Round(Vector3 v) { v.x = Mathf.Round(v.x); v.y = Mathf.Round(v.y); v.z = Mathf.Round(v.z); return v; } public static bool Save(string fileName, byte[] bytes) { return false; } public static void SetActive(GameObject go, bool state) { if (state) { Activate(go.transform); } else { Deactivate(go.transform); } } public static void SetActiveChildren(GameObject go, bool state) { Transform transform = go.transform; if (state) { int index = 0; int childCount = transform.childCount; while (index < childCount) { Activate(transform.GetChild(index)); index++; } } else { int num3 = 0; int num4 = transform.childCount; while (num3 < num4) { Deactivate(transform.GetChild(num3)); num3++; } } } public static void SetActiveSelf(GameObject go, bool state) { go.SetActive(state); } public static void SetLayer(GameObject go, int layer) { go.layer = layer; Transform transform = go.transform; int index = 0; int childCount = transform.childCount; while (index < childCount) { SetLayer(transform.GetChild(index).gameObject, layer); index++; } } public static string StripSymbols(string text) { if (text != null) { int index = 0; int length = text.Length; while (index < length) { char ch = text[index]; if (ch == '[') { int count = ParseSymbol(text, index, null, false); if (count > 0) { text = text.Remove(index, count); length = text.Length; continue; } } index++; } } return text; } public static string clipboard => throw new NotImplementedException("Clipboard is not yet implemented"); public static float soundVolume { get { if (!mLoaded) { mLoaded = true; mGlobalVolume = PlayerPrefs.GetFloat("Sound", 1f); } return mGlobalVolume; } set { if (mGlobalVolume != value) { mLoaded = true; mGlobalVolume = value; PlayerPrefs.SetFloat("Sound", 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; using System.Globalization; using System.Runtime.Tests.Common; using Xunit; public static class SingleTests { [Fact] public static void TestCtorEmpty() { float i = new float(); Assert.Equal(0, i); } [Fact] public static void TestCtorValue() { float i = 41; Assert.Equal(41, i); } [Fact] public static void TestMaxValue() { Assert.Equal((float)3.40282346638528859e+38, float.MaxValue); } [Fact] public static void TestMinValue() { Assert.Equal((float)(-3.40282346638528859e+38), float.MinValue); } [Fact] public static void TestEpsilon() { Assert.Equal((float)1.4e-45, float.Epsilon); } [Fact] public static void TestIsInfinity() { Assert.True(float.IsInfinity(float.NegativeInfinity)); Assert.True(float.IsInfinity(float.PositiveInfinity)); } [Fact] public static void TestNaN() { Assert.Equal((float)0.0 / (float)0.0, float.NaN); } [Fact] public static void TestIsNaN() { Assert.True(float.IsNaN(float.NaN)); } [Fact] public static void TestNegativeInfinity() { Assert.Equal((float)(-1.0) / (float)0.0, float.NegativeInfinity); } [Fact] public static void TestIsNegativeInfinity() { Assert.True(float.IsNegativeInfinity(float.NegativeInfinity)); } [Fact] public static void TestPositiveInfinity() { Assert.Equal((float)1.0 / (float)0.0, float.PositiveInfinity); } [Fact] public static void TestIsPositiveInfinity() { Assert.True(float.IsPositiveInfinity(float.PositiveInfinity)); } [Theory] [InlineData((float)234, (float)234, 0)] [InlineData((float)234, float.MinValue, 1)] [InlineData((float)234, (float)(-123), 1)] [InlineData((float)234, (float)0, 1)] [InlineData((float)234, (float)123, 1)] [InlineData((float)234, (float)456, -1)] [InlineData((float)234, float.MaxValue, -1)] [InlineData((float)234, float.NaN, 1)] [InlineData(float.NaN, float.NaN, 0)] [InlineData(float.NaN, 0, -1)] public static void TestCompareTo(float i, float value, int expected) { int result = CompareHelper.NormalizeCompare(i.CompareTo(value)); Assert.Equal(expected, result); } [Theory] [InlineData(null, 1)] [InlineData((float)234, 0)] [InlineData(float.MinValue, 1)] [InlineData((float)(-123), 1)] [InlineData((float)0, 1)] [InlineData((float)123, 1)] [InlineData((float)456, -1)] [InlineData(float.MaxValue, -1)] public static void TestCompareToObject(object obj, int expected) { IComparable comparable = (float)234; int i = CompareHelper.NormalizeCompare(comparable.CompareTo(obj)); Assert.Equal(expected, i); } [Fact] public static void TestCompareToObjectInvalid() { IComparable comparable = (float)234; Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); //Obj is not a float } [Theory] [InlineData((float)789, true)] [InlineData((float)(-789), false)] [InlineData((float)0, false)] public static void TestEqualsObject(object obj, bool expected) { float i = 789; Assert.Equal(expected, i.Equals(obj)); } [Theory] [InlineData((float)789, (float)789, true)] [InlineData((float)789, (float)(-789), false)] [InlineData((float)789, (float)0, false)] [InlineData(float.NaN, float.NaN, true)] public static void TestEquals(float i1, float i2, bool expected) { Assert.Equal(expected, i1.Equals(i2)); } [Fact] public static void TestGetHashCode() { float i1 = 123; float i2 = 654; Assert.NotEqual(0, i1.GetHashCode()); Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode()); } [Fact] public static void TestToString() { float i1 = 6310; Assert.Equal("6310", i1.ToString()); float i2 = -8249; Assert.Equal("-8249", i2.ToString()); } [Fact] public static void TestToStringFormatProvider() { var numberFormat = new NumberFormatInfo(); float i1 = 6310; Assert.Equal("6310", i1.ToString(numberFormat)); float i2 = -8249; Assert.Equal("-8249", i2.ToString(numberFormat)); float i3 = -2468; // Changing the negative pattern doesn't do anything without also passing in a format string numberFormat.NumberNegativePattern = 0; Assert.Equal("-2468", i3.ToString(numberFormat)); Assert.Equal("NaN", float.NaN.ToString(NumberFormatInfo.InvariantInfo)); Assert.Equal("Infinity", float.PositiveInfinity.ToString(NumberFormatInfo.InvariantInfo)); Assert.Equal("-Infinity", float.NegativeInfinity.ToString(NumberFormatInfo.InvariantInfo)); } [Fact] public static void TestToStringFormat() { float i1 = 6310; Assert.Equal("6310", i1.ToString("G")); float i2 = -8249; Assert.Equal("-8249", i2.ToString("g")); float i3 = -2468; Assert.Equal(string.Format("{0:N}", -2468.00), i3.ToString("N")); } [Fact] public static void TestToStringFormatFormatProvider() { var numberFormat = new NumberFormatInfo(); float i1 = 6310; Assert.Equal("6310", i1.ToString("G", numberFormat)); float i2 = -8249; Assert.Equal("-8249", i2.ToString("g", numberFormat)); numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up numberFormat.NumberGroupSeparator = "*"; numberFormat.NumberNegativePattern = 0; float i3 = -2468; Assert.Equal("(2*468.00)", i3.ToString("N", numberFormat)); } [Fact] public static void TestParse() { Assert.Equal(123, float.Parse("123")); Assert.Equal(-123, float.Parse("-123")); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyle() { Assert.Equal(123.1f, float.Parse((123.1).ToString("F"), NumberStyles.AllowDecimalPoint)); Assert.Equal(1000, float.Parse((1000).ToString("N0"), NumberStyles.AllowThousands)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseFormatProvider() { var nfi = new NumberFormatInfo(); Assert.Equal(123, float.Parse("123", nfi)); Assert.Equal(-123, float.Parse("-123", nfi)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyleFormatProvider() { var nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; Assert.Equal(123.123f, float.Parse("123.123", NumberStyles.Float, nfi)); nfi.CurrencySymbol = "$"; nfi.CurrencyGroupSeparator = ","; Assert.Equal(1000, float.Parse("$1,000", NumberStyles.Currency, nfi)); //TODO: Negative tests once we get better exception support } [Fact] public static void TestTryParse() { // Defaults AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent | AllowThousands float i; Assert.True(float.TryParse("123", out i)); // Simple Assert.Equal(123, i); Assert.True(float.TryParse("-385", out i)); // LeadingSign Assert.Equal(-385, i); Assert.True(float.TryParse(" 678 ", out i)); // Leading/Trailing whitespace Assert.Equal(678, i); Assert.True(float.TryParse((678.90).ToString("F2"), out i)); // Decimal Assert.Equal((float)678.90, i); Assert.True(float.TryParse("1E23", out i)); // Exponent Assert.Equal((float)1E23, i); Assert.True(float.TryParse((1000).ToString("N0"), out i)); // Thousands Assert.Equal(1000, i); var nfi = new NumberFormatInfo() { CurrencyGroupSeparator = "" }; Assert.False(float.TryParse((1000).ToString("C0", nfi), out i)); // Currency Assert.False(float.TryParse("abc", out i)); // Hex digits Assert.False(float.TryParse("(135)", out i)); // Parentheses } [Fact] public static void TestTryParseNumberStyleFormatProvider() { float i; var nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; Assert.True(float.TryParse("123.123", NumberStyles.Any, nfi, out i)); // Simple positive Assert.Equal(123.123f, i); Assert.True(float.TryParse("123", NumberStyles.Float, nfi, out i)); // Simple Hex Assert.Equal(123, i); nfi.CurrencySymbol = "$"; nfi.CurrencyGroupSeparator = ","; Assert.True(float.TryParse("$1,000", NumberStyles.Currency, nfi, out i)); // Currency/Thousands postive Assert.Equal(1000, i); Assert.False(float.TryParse("abc", NumberStyles.None, nfi, out i)); // Hex Number negative Assert.False(float.TryParse("678.90", NumberStyles.Integer, nfi, out i)); // Decimal Assert.False(float.TryParse(" 678 ", NumberStyles.None, nfi, out i)); // Trailing/Leading whitespace negative Assert.True(float.TryParse("(135)", NumberStyles.AllowParentheses, nfi, out i)); // Parenthese postive Assert.Equal(-135, i); Assert.True(float.TryParse("Infinity", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(float.IsPositiveInfinity(i)); Assert.True(float.TryParse("-Infinity", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(float.IsNegativeInfinity(i)); Assert.True(float.TryParse("NaN", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(float.IsNaN(i)); } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Agent.Sdk; using BuildXL.Cache.ContentStore.Hashing; using Microsoft.VisualStudio.Services.BlobStore.WebApi; namespace Agent.Plugins.PipelineCache { public static class TarUtils { public const string TarLocationEnvironmentVariableName = "VSTS_TAR_EXECUTABLE"; private readonly static bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); private const string archive = "archive.tar"; /// <summary> /// Will archive files in the input path into a TAR file. /// </summary> /// <returns>The path to the TAR.</returns> public static async Task<string> ArchiveFilesToTarAsync( AgentTaskPluginExecutionContext context, string inputPath, CancellationToken cancellationToken) { if(File.Exists(inputPath)) { throw new DirectoryNotFoundException($"Please specify path to a directory, File path is not allowed. {inputPath} is a file."); } var archiveFileName = CreateArchiveFileName(); var archiveFile = Path.Combine(Path.GetTempPath(), archiveFileName); ProcessStartInfo processStartInfo = GetCreateTarProcessInfo(context, archiveFileName, inputPath); Action actionOnFailure = () => { // Delete archive file. TryDeleteFile(archiveFile); }; await RunProcessAsync( context, processStartInfo, // no additional tasks on create are required to run whilst running the TAR process (Process process, CancellationToken ct) => Task.CompletedTask, actionOnFailure, cancellationToken); return archiveFile; } /// <summary> /// This will download the dedup into stdin stream while extracting the TAR simulataneously (piped). This is done by /// starting the download through a Task and starting the TAR/7z process which is reading from STDIN. /// </summary> /// <remarks> /// Windows will use 7z to extract the TAR file (only if 7z is installed on the machine and is part of PATH variables). /// Non-Windows machines will extract TAR file using the 'tar' command'. /// </remarks> public static Task DownloadAndExtractTarAsync( AgentTaskPluginExecutionContext context, Manifest manifest, DedupManifestArtifactClient dedupManifestClient, string targetDirectory, CancellationToken cancellationToken) { ValidateTarManifest(manifest); Directory.CreateDirectory(targetDirectory); DedupIdentifier dedupId = DedupIdentifier.Create(manifest.Items.Single(i => i.Path.EndsWith(archive, StringComparison.OrdinalIgnoreCase)).Blob.Id); ProcessStartInfo processStartInfo = GetExtractStartProcessInfo(context, targetDirectory); Func<Process, CancellationToken, Task> downloadTaskFunc = (process, ct) => Task.Run(async () => { try { await dedupManifestClient.DownloadToStreamAsync(dedupId, process.StandardInput.BaseStream, proxyUri: null, cancellationToken: ct); process.StandardInput.BaseStream.Close(); } catch (Exception e) { try { process.Kill(); } catch {} ExceptionDispatchInfo.Capture(e).Throw(); } }); return RunProcessAsync( context, processStartInfo, downloadTaskFunc, () => { }, cancellationToken); } internal static async Task RunProcessAsync( AgentTaskPluginExecutionContext context, ProcessStartInfo processStartInfo, Func<Process, CancellationToken, Task> additionalTaskToExecuteWhilstRunningProcess, Action actionOnFailure, CancellationToken cancellationToken) { using (var process = new Process()) { process.StartInfo = processStartInfo; process.EnableRaisingEvents = true; try { context.Debug($"Starting '{process.StartInfo.FileName}' with arguments '{process.StartInfo.Arguments}'..."); process.Start(); } catch (Exception e) { // couldn't start the process, so throw a slightly nicer message about required dependencies: throw new InvalidOperationException($"Failed to start the required dependency '{process.StartInfo.FileName}'. Please verify the correct version is installed and available on the path.", e); } // Our goal is to always have the process ended or killed by the time we exit the function. try { await additionalTaskToExecuteWhilstRunningProcess(process, cancellationToken); process.WaitForExit(); int exitCode = process.ExitCode; if (exitCode == 0) { context.Output($"Process exit code: {exitCode}"); } else { throw new Exception($"Process returned non-zero exit code: {exitCode}"); } } catch (Exception e) { actionOnFailure(); ExceptionDispatchInfo.Capture(e).Throw(); } } } private static void CreateProcessStartInfo(ProcessStartInfo processStartInfo, string processFileName, string processArguments, string processWorkingDirectory) { processStartInfo.FileName = processFileName; processStartInfo.Arguments = processArguments; processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardInput = true; processStartInfo.WorkingDirectory = processWorkingDirectory; } private static ProcessStartInfo GetCreateTarProcessInfo(AgentTaskPluginExecutionContext context, string archiveFileName, string inputPath) { var processFileName = GetTar(context); inputPath = inputPath.TrimEnd(Path.DirectorySeparatorChar).TrimEnd(Path.AltDirectorySeparatorChar); var processArguments = $"-cf \"{archiveFileName}\" -C \"{inputPath}\" ."; // If given the absolute path for the '-cf' option, the GNU tar fails. The workaround is to start the tarring process in the temp directory, and simply speficy 'archive.tar' for that option. if (context.IsSystemDebugTrue()) { processArguments = "-v " + processArguments; } if (isWindows) { processArguments = "-h " + processArguments; } ProcessStartInfo processStartInfo = new ProcessStartInfo(); CreateProcessStartInfo(processStartInfo, processFileName, processArguments, processWorkingDirectory: Path.GetTempPath()); // We want to create the archiveFile in temp folder, and hence starting the tar process from TEMP to avoid absolute paths in tar cmd line. return processStartInfo; } private static string GetTar(AgentTaskPluginExecutionContext context) { // check if the user specified the tar executable to use: string location = Environment.GetEnvironmentVariable(TarLocationEnvironmentVariableName); return String.IsNullOrWhiteSpace(location) ? "tar" : location; } private static ProcessStartInfo GetExtractStartProcessInfo(AgentTaskPluginExecutionContext context, string targetDirectory) { string processFileName, processArguments; if (isWindows && CheckIf7ZExists()) { processFileName = "7z"; processArguments = $"x -si -aoa -o\"{targetDirectory}\" -ttar"; if (context.IsSystemDebugTrue()) { processArguments = "-bb1 " + processArguments; } } else { processFileName = GetTar(context); processArguments = $"-xf - -C ."; // Instead of targetDirectory, we are providing . to tar, because the tar process is being started from targetDirectory. if (context.IsSystemDebugTrue()) { processArguments = "-v " + processArguments; } } ProcessStartInfo processStartInfo = new ProcessStartInfo(); CreateProcessStartInfo(processStartInfo, processFileName, processArguments, processWorkingDirectory: targetDirectory); return processStartInfo; } private static void ValidateTarManifest(Manifest manifest) { if (manifest == null || manifest.Items.Count() != 1 || !manifest.Items.Single().Path.EndsWith(archive, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException($"Manifest containing a tar cannot have more than one item."); } } private static void TryDeleteFile(string fileName) { try { if (File.Exists(fileName)) { File.Delete(fileName); } } catch {} } private static string CreateArchiveFileName() { return $"{Guid.NewGuid().ToString("N")}_{archive}"; } private static bool CheckIf7ZExists() { using (var process = new Process()) { process.StartInfo.FileName = "7z"; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; try { process.Start(); } catch { return false; } return true; } } } }
/*************************************************************************** * Track.cs * * Copyright (C) 2006-2007 Alan McGovern * Authors: * Alan McGovern (alan.mcgovern@gmail.com) ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * 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.Runtime.InteropServices; namespace Mtp { public class Track { internal TrackStruct trackStruct; private MtpDevice device; public uint FileId { get { return trackStruct.item_id; } } public string Album { get { return trackStruct.album; } set { trackStruct.album = value;} } public string Artist { get { return trackStruct.artist; } set { trackStruct.artist = value; } } public uint Bitrate { get { return trackStruct.bitrate; } } public ushort BitrateType { get { return trackStruct.bitratetype; } } public string ReleaseDate { get { return trackStruct.date; } set { trackStruct.date = value; } } public int Year { get { return ReleaseDate == null || ReleaseDate.Length < 4 ? 0 : Int32.Parse (ReleaseDate.Substring(0, 4)); } set { ReleaseDate = String.Format ("{0:0000}0101T0000.00", value); } } public uint Duration { get { return trackStruct.duration; } set { trackStruct.duration = value; } } public string FileName { get { return trackStruct.filename; } set { trackStruct.filename = value; } } public ulong FileSize { get { return trackStruct.filesize; } set { trackStruct.filesize = value; } } public FileType FileType { get { return trackStruct.filetype; } set { trackStruct.filetype = value; } } public string Genre { get { return trackStruct.genre; } set { trackStruct.genre = value; } } public ushort NoChannels { get { return trackStruct.nochannels; } set { trackStruct.nochannels = value; } } // 0 to 100 public ushort Rating { get { return trackStruct.rating; } set { if (value < 0 || value > 100) throw new ArgumentOutOfRangeException ("Rating", "Rating must be between zero and 100"); trackStruct.rating = value; } } public uint SampleRate { get { return trackStruct.samplerate; } set { trackStruct.samplerate = value; } } public string Title { get { return trackStruct.title; } set { trackStruct.title = value; } } public ushort TrackNumber { get { return trackStruct.tracknumber; } set { trackStruct.tracknumber = value; } } public uint WaveCodec { get { return trackStruct.wavecodec; } } public uint UseCount { get { return trackStruct.usecount; } set { trackStruct.usecount = value; } } #if LIBMTP8 public string Composer { get { return trackStruct.composer; } set { trackStruct.composer = value; } } #endif public Track (string filename, ulong filesize) : this (new TrackStruct (), null) { this.trackStruct.filename = filename; this.trackStruct.filesize = filesize; this.trackStruct.filetype = DetectFileType (this); } internal Track (TrackStruct track, MtpDevice device) { this.device = device; this.trackStruct = track; } public bool InFolder (Folder folder) { return folder != null && trackStruct.parent_id == folder.FolderId; } public void Download (string path) { Download (path, null); } public void Download (string path, ProgressFunction callback) { if (String.IsNullOrEmpty (path)) throw new ArgumentException ("Cannot be null or empty", "path"); GetTrack (device.Handle, trackStruct.item_id, path, callback, IntPtr.Zero); } public void UpdateMetadata () { UpdateTrackMetadata (device.Handle, ref trackStruct); } private static FileType DetectFileType (Track track) { string ext = System.IO.Path.GetExtension (track.FileName); // Strip leading . if (ext.Length > 0) ext = ext.Substring (1, ext.Length - 1); // this is a hack; catch all m4(a|b|v|p) if (ext != null && ext.ToLower ().StartsWith ("m4")) ext = "mp4"; FileType type = (FileType) Enum.Parse (typeof(FileType), ext, true); //if (type == null) // return FileType.UNKNOWN; return type; } internal static void DestroyTrack (IntPtr track) { LIBMTP_destroy_track_t (track); } internal static void GetTrack (MtpDeviceHandle handle, uint trackId, string destPath, ProgressFunction callback, IntPtr data) { if (LIBMTP_Get_Track_To_File (handle, trackId, destPath, callback, data) != 0) { LibMtpException.CheckErrorStack (handle); throw new LibMtpException (ErrorCode.General, "Could not download track from the device"); } } internal static IntPtr GetTrackListing (MtpDeviceHandle handle, ProgressFunction function, IntPtr data) { return LIBMTP_Get_Tracklisting_With_Callback (handle, function, data); } internal static void SendTrack (MtpDeviceHandle handle, string path, ref TrackStruct metadata, ProgressFunction callback, IntPtr data) { #if LIBMTP8 if (LIBMTP_Send_Track_From_File (handle, path, ref metadata, callback, data) != 0) #else if (LIBMTP_Send_Track_From_File (handle, path, ref metadata, callback, data, metadata.parent_id) != 0) #endif { LibMtpException.CheckErrorStack (handle); throw new LibMtpException (ErrorCode.General, "Could not upload the track"); } } internal static void UpdateTrackMetadata (MtpDeviceHandle handle, ref TrackStruct metadata) { if (LIBMTP_Update_Track_Metadata (handle, ref metadata) != 0) throw new LibMtpException (ErrorCode.General); } //[DllImport("libmtp.dll")] //private static extern IntPtr LIBMTP_new_track_t (); // LIBMTP_track_t * [DllImport("libmtp.dll")] private static extern void LIBMTP_destroy_track_t (IntPtr track); // LIBMTP_track_t * //[DllImport("libmtp.dll")] //private static extern IntPtr LIBMTP_Get_Tracklisting (MtpDeviceHandle handle); //LIBMTP_track_t * [DllImport("libmtp.dll")] private static extern IntPtr LIBMTP_Get_Tracklisting_With_Callback (MtpDeviceHandle handle, ProgressFunction callback, IntPtr data); // LIBMTP_track_t * //[DllImport("libmtp.dll")] //private static extern IntPtr LIBMTP_Get_Trackmetadata (MtpDeviceHandle handle, uint trackId); // LIBMTP_track_t * [DllImport("libmtp.dll")] private static extern int LIBMTP_Get_Track_To_File (MtpDeviceHandle handle, uint trackId, string path, ProgressFunction callback, IntPtr data); #if LIBMTP8 [DllImport("libmtp.dll")] private static extern int LIBMTP_Send_Track_From_File (MtpDeviceHandle handle, string path, ref TrackStruct track, ProgressFunction callback, IntPtr data); #else [DllImport("libmtp.dll")] private static extern int LIBMTP_Send_Track_From_File (MtpDeviceHandle handle, string path, ref TrackStruct track, ProgressFunction callback, IntPtr data, uint parentHandle); #endif [DllImport("libmtp.dll")] private static extern int LIBMTP_Update_Track_Metadata (MtpDeviceHandle handle, ref TrackStruct metadata); //[DllImport("libmtp.dll")] //private static extern int LIBMTP_Track_Exists (MtpDeviceHandle handle, uint trackId); //int LIBMTP_Get_Track_To_File_Descriptor (MtpDeviceHandle handle, uint trackId, int const, LIBMTP_progressfunc_t const, void const *const) //int LIBMTP_Send_Track_From_File_Descriptor (MtpDeviceHandle handle, int const, LIBMTP_track_t *const, LIBMTP_progressfunc_t const, void const *const, uint32_t const) } [StructLayout(LayoutKind.Sequential)] internal struct TrackStruct { public uint item_id; public uint parent_id; #if LIBMTP8 public uint storage_id; #endif [MarshalAs(UnmanagedType.LPStr)] public string title; [MarshalAs(UnmanagedType.LPStr)] public string artist; #if LIBMTP8 [MarshalAs(UnmanagedType.LPStr)] public string composer; #endif [MarshalAs(UnmanagedType.LPStr)] public string genre; [MarshalAs(UnmanagedType.LPStr)] public string album; [MarshalAs(UnmanagedType.LPStr)] public string date; [MarshalAs(UnmanagedType.LPStr)] public string filename; public ushort tracknumber; public uint duration; public uint samplerate; public ushort nochannels; public uint wavecodec; public uint bitrate; public ushort bitratetype; public ushort rating; // 0 -> 100 public uint usecount; public ulong filesize; #if LIBMTP_TRACK_HAS_MODDATE #if LIBMTP_SIZEOF_TIME_T_64 public ulong modificationdate; #else public uint modificationdate; #endif #endif public FileType filetype; public IntPtr next; // Track Null if last /* public Track? Next { get { if (next == IntPtr.Zero) return null; return (Track)Marshal.PtrToStructure(next, typeof(Track)); } }*/ } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski 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. // namespace NLog.Targets { using System; using System.Reflection; using NLog.Common; using NLog.Internal; /// <summary> /// Calls the specified static method on each log message and passes contextual parameters to it. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/MethodCall-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/MethodCall-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/MethodCall/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/MethodCall/Simple/Example.cs" /> /// </example> [Target("MethodCall")] public sealed class MethodCallTarget : MethodCallTargetBase { /// <summary> /// Gets or sets the class name. /// </summary> /// <docgen category='Invocation Options' order='10' /> public string ClassName { get; set; } /// <summary> /// Gets or sets the method name. The method must be public and static. /// /// Use the AssemblyQualifiedName , https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx /// e.g. /// </summary> /// <docgen category='Invocation Options' order='10' /> public string MethodName { get; set; } Action<LogEventInfo, object[]> _logEventAction; /// <summary> /// Initializes a new instance of the <see cref="MethodCallTarget" /> class. /// </summary> public MethodCallTarget() : base() { } /// <summary> /// Initializes a new instance of the <see cref="MethodCallTarget" /> class. /// </summary> /// <param name="name">Name of the target.</param> public MethodCallTarget(string name) : this(name, null) { } /// <summary> /// Initializes a new instance of the <see cref="MethodCallTarget" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="logEventAction">Method to call on logevent.</param> public MethodCallTarget(string name, Action<LogEventInfo, object[]> logEventAction) : this() { Name = name; _logEventAction = logEventAction; } /// <inheritdoc/> protected override void InitializeTarget() { base.InitializeTarget(); if (ClassName != null && MethodName != null) { _logEventAction = null; var targetType = Type.GetType(ClassName); if (targetType != null) { var methodInfo = targetType.GetMethod(MethodName); if (methodInfo is null) { throw new NLogConfigurationException($"MethodCallTarget: MethodName={MethodName} not found in ClassName={ClassName} - it should be static"); } else { _logEventAction = BuildLogEventAction(methodInfo); } } else { throw new NLogConfigurationException($"MethodCallTarget: failed to get type from ClassName={ClassName}"); } } else if (_logEventAction is null) { throw new NLogConfigurationException($"MethodCallTarget: Missing configuration of ClassName and MethodName"); } } private static Action<LogEventInfo, object[]> BuildLogEventAction(MethodInfo methodInfo) { var neededParameters = methodInfo.GetParameters().Length; return (logEvent, parameters) => { var missingParameters = neededParameters - parameters.Length; if (missingParameters > 0) { //fill missing parameters with Type.Missing var newParams = new object[neededParameters]; for (int i = 0; i < parameters.Length; ++i) newParams[i] = parameters[i]; for (int i = parameters.Length; i < neededParameters; ++i) newParams[i] = Type.Missing; parameters = newParams; } methodInfo.Invoke(null, parameters); }; } /// <summary> /// Calls the specified Method. /// </summary> /// <param name="parameters">Method parameters.</param> /// <param name="logEvent">The logging event.</param> protected override void DoInvoke(object[] parameters, AsyncLogEventInfo logEvent) { try { ExecuteLogMethod(parameters, logEvent.LogEvent); logEvent.Continuation(null); } catch (Exception ex) { if (ExceptionMustBeRethrown(ex)) { throw; } logEvent.Continuation(ex); } } /// <summary> /// Calls the specified Method. /// </summary> /// <param name="parameters">Method parameters.</param> protected override void DoInvoke(object[] parameters) { ExecuteLogMethod(parameters, null); } private void ExecuteLogMethod(object[] parameters, LogEventInfo logEvent) { if (_logEventAction != null) { _logEventAction.Invoke(logEvent, parameters); } else { InternalLogger.Trace("{0}: No invoke because class/method was not found or set", this); } } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; namespace Aurora.BotManager { public class BotManager : ISharedRegionModule, IBotManager { private readonly Dictionary<UUID, Bot> m_bots = new Dictionary<UUID, Bot>(); #region ISharedRegionModule Members public void Initialise(IConfigSource source) { } public void AddRegion(IScene scene) { scene.RegisterModuleInterface<IBotManager>(this); scene.RegisterModuleInterface(this); } public void RemoveRegion(IScene scene) { } public void RegionLoaded(IScene scene) { } public void PostInitialise() { } public void Close() { m_bots.Clear(); } public Type ReplaceableInterface { get { return null; } } public string Name { get { return GetType().AssemblyQualifiedName; } } #endregion #region IBotManager /// <summary> /// Creates a new bot inworld /// </summary> /// <param name = "FirstName"></param> /// <param name = "LastName"></param> /// <param name = "cloneAppearanceFrom">UUID of the avatar whos appearance will be copied to give this bot an appearance</param> /// <returns>ID of the bot</returns> public UUID CreateAvatar(string FirstName, string LastName, IScene scene, UUID cloneAppearanceFrom, UUID creatorID, Vector3 startPos) { AgentCircuitData m_aCircuitData = new AgentCircuitData { child = false, circuitcode = (uint) Util.RandomClass.Next(), Appearance = GetAppearance(cloneAppearanceFrom, scene) }; //Add the circuit data so they can login //Sets up appearance if (m_aCircuitData.Appearance == null) { m_aCircuitData.Appearance = new AvatarAppearance {Wearables = AvatarWearable.DefaultWearables}; } //Create the new bot data BotClientAPI m_character = new BotClientAPI(scene, m_aCircuitData) { FirstName = FirstName, LastName = LastName }; m_aCircuitData.AgentID = m_character.AgentId; m_aCircuitData.Appearance.Owner = m_character.AgentId; List<AvatarAttachment> attachments = m_aCircuitData.Appearance.GetAttachments(); m_aCircuitData.Appearance.ClearAttachments(); foreach (AvatarAttachment t in attachments) { InventoryItemBase item = scene.InventoryService.GetItem(new InventoryItemBase(t.ItemID)); if (item != null) { item.ID = UUID.Random(); item.Owner = m_character.AgentId; item.Folder = UUID.Zero; scene.InventoryService.AddItem(item); //Now fix the ItemID m_aCircuitData.Appearance.SetAttachment(t.AttachPoint, item.ID, t.AssetID); } } scene.AuthenticateHandler.AgentCircuits.Add(m_character.CircuitCode, m_aCircuitData); //This adds them to the scene and sets them inworld AddAndWaitUntilAgentIsAdded(scene, m_character); IScenePresence SP = scene.GetScenePresence(m_character.AgentId); if (SP == null) return UUID.Zero; //Failed! Bot bot = new Bot(); bot.Initialize(SP, creatorID); SP.MakeRootAgent(m_character.StartPos, false, true); //Move them SP.Teleport(startPos); IAttachmentsModule attModule = SP.Scene.RequestModuleInterface<IAttachmentsModule>(); if (attModule != null) foreach (AvatarAttachment att in attachments) attModule.RezSingleAttachmentFromInventory(SP.ControllingClient, att.ItemID, att.AssetID, 0, true); IAvatarAppearanceModule appearance = SP.RequestModuleInterface<IAvatarAppearanceModule>(); appearance.InitialHasWearablesBeenSent = true; //Save them in the bots list m_bots.Add(m_character.AgentId, bot); AddTagToBot(m_character.AgentId, "AllBots", bot.AvatarCreatorID); MainConsole.Instance.Info("[RexBotManager]: Added bot " + m_character.Name + " to scene."); //Return their UUID return m_character.AgentId; } private static void AddAndWaitUntilAgentIsAdded(IScene scene, BotClientAPI m_character) { bool done = false; scene.AddNewClient(m_character, delegate { done = true; }); while (!done) Thread.Sleep(3); } public void RemoveAvatar(UUID avatarID, IScene scene, UUID userAttempting) { IEntity sp = scene.GetScenePresence(avatarID); if (sp == null) { sp = scene.GetSceneObjectPart(avatarID); if (sp == null) return; sp = ((ISceneChildEntity)sp).ParentEntity; } if (!CheckPermission(sp, userAttempting)) return; RemoveAllTagsFromBot(avatarID, userAttempting); if (!m_bots.Remove(avatarID)) return; //Kill the agent IEntityTransferModule module = scene.RequestModuleInterface<IEntityTransferModule>(); module.IncomingCloseAgent(scene, avatarID); } public void PauseMovement(UUID botID, UUID userAttempting) { Bot bot; //Find the bot if (m_bots.TryGetValue(botID, out bot)) { if (!CheckPermission(bot, userAttempting)) return; bot.PauseMovement(); } } public void ResumeMovement(UUID botID, UUID userAttempting) { Bot bot; //Find the bot if (m_bots.TryGetValue(botID, out bot)) { if (!CheckPermission(bot, userAttempting)) return; bot.ResumeMovement(); } } /// <summary> /// Sets up where the bot should be walking /// </summary> /// <param name = "Bot">ID of the bot</param> /// <param name = "Positions">List of positions the bot will move to</param> /// <param name = "mode">List of what the bot should be doing inbetween the positions</param> public void SetBotMap(UUID Bot, List<Vector3> Positions, List<TravelMode> mode, int flags, UUID userAttempting) { Bot bot; //Find the bot if (m_bots.TryGetValue(Bot, out bot)) { if (!CheckPermission(bot, userAttempting)) return; bot.SetPath(Positions, mode, flags); } } /// <summary> /// Speed up or slow down the bot /// </summary> /// <param name = "Bot"></param> /// <param name = "modifier"></param> public void SetMovementSpeedMod(UUID Bot, float modifier, UUID userAttempting) { Bot bot; if (m_bots.TryGetValue(Bot, out bot)) { if (!CheckPermission(bot, userAttempting)) return; bot.SetMovementSpeedMod(modifier); } } public void SetBotShouldFly(UUID botID, bool shouldFly, UUID userAttempting) { Bot bot; if (m_bots.TryGetValue(botID, out bot)) { if (!CheckPermission(bot, userAttempting)) return; if (shouldFly) bot.DisableWalk(); else bot.EnableWalk(); } } #region Tag/Remove bots private readonly Dictionary<string, List<UUID>> m_botTags = new Dictionary<string, List<UUID>>(); public void AddTagToBot(UUID Bot, string tag, UUID userAttempting) { Bot bot; if (m_bots.TryGetValue(Bot, out bot)) { if (!CheckPermission(bot, userAttempting)) return; } if (!m_botTags.ContainsKey(tag)) m_botTags.Add(tag, new List<UUID>()); m_botTags[tag].Add(Bot); } public List<UUID> GetBotsWithTag(string tag) { if (!m_botTags.ContainsKey(tag)) return new List<UUID>(); return new List<UUID>(m_botTags[tag]); } public void RemoveBots(string tag, UUID userAttempting) { List<UUID> bots = GetBotsWithTag(tag); foreach (UUID bot in bots) { Bot Bot; if (m_bots.TryGetValue(bot, out Bot)) { if (!CheckPermission(Bot, userAttempting)) continue; RemoveTagFromBot(bot, tag, userAttempting); RemoveAvatar(bot, Bot.Controller.GetScene(), userAttempting); } } } public void RemoveTagFromBot(UUID Bot, string tag, UUID userAttempting) { Bot bot; if (m_bots.TryGetValue(Bot, out bot)) { if (!CheckPermission(bot, userAttempting)) return; } if (m_botTags.ContainsKey(tag)) m_botTags[tag].Remove(Bot); } public void RemoveAllTagsFromBot(UUID Bot, UUID userAttempting) { Bot bot; if (m_bots.TryGetValue(Bot, out bot)) { if (!CheckPermission(bot, userAttempting)) return; } List<string> tagsToRemove = new List<string>(); foreach(KeyValuePair<string, List<UUID>> kvp in m_botTags) { if (kvp.Value.Contains(Bot)) tagsToRemove.Add(kvp.Key); } foreach(string tag in tagsToRemove) m_botTags[tag].Remove(Bot); } #endregion /// <summary> /// Finds the given users appearance /// </summary> /// <param name = "target"></param> /// <param name = "scene"></param> /// <returns></returns> private AvatarAppearance GetAppearance(UUID target, IScene scene) { IScenePresence sp = scene.GetScenePresence(target); if (sp != null) { IAvatarAppearanceModule aa = sp.RequestModuleInterface<IAvatarAppearanceModule>(); if (aa != null) return new AvatarAppearance(aa.Appearance); } return scene.AvatarService.GetAppearance(target); } private bool CheckPermission(IEntity sp, UUID userAttempting) { foreach (Bot bot in m_bots.Values) { if (bot.Controller.UUID == sp.UUID) return bot.AvatarCreatorID == userAttempting; } return false; } private bool CheckPermission(Bot bot, UUID userAttempting) { if (userAttempting == UUID.Zero) return true; //Forced override if (bot != null) return bot.AvatarCreatorID == userAttempting; return false; } #endregion #region IBotManager /// <summary> /// Begins to follow the given user /// </summary> /// <param name = "Bot"></param> /// <param name = "modifier"></param> public void FollowAvatar(UUID botID, string avatarName, float startFollowDistance, float endFollowDistance, bool requireLOS, Vector3 offsetFromAvatar, UUID userAttempting) { Bot bot; if (m_bots.TryGetValue(botID, out bot)) { if (!CheckPermission(bot, userAttempting)) return; bot.FollowAvatar(avatarName, startFollowDistance, endFollowDistance, offsetFromAvatar, requireLOS); } } /// <summary> /// Stops following the given user /// </summary> /// <param name = "Bot"></param> /// <param name = "modifier"></param> public void StopFollowAvatar(UUID botID, UUID userAttempting) { Bot bot; if (m_bots.TryGetValue(botID, out bot)) { if (!CheckPermission(bot, userAttempting)) return; bot.StopFollowAvatar(); } } /// <summary> /// Sends a chat message to all clients /// </summary> /// <param name = "Bot"></param> /// <param name = "modifier"></param> public void SendChatMessage(UUID botID, string message, int sayType, int channel, UUID userAttempting) { Bot bot; if (m_bots.TryGetValue(botID, out bot)) { if (!CheckPermission(bot, userAttempting)) return; bot.SendChatMessage(sayType, message, channel); } } /// <summary> /// Sends a chat message to all clients /// </summary> /// <param name = "Bot"></param> /// <param name = "modifier"></param> public void SendIM(UUID botID, UUID toUser, string message, UUID userAttempting) { Bot bot; if (m_bots.TryGetValue(botID, out bot)) { if (!CheckPermission(bot, userAttempting)) return; bot.SendInstantMessage(new GridInstantMessage() { binaryBucket = new byte[0], dialog = (byte)InstantMessageDialog.MessageFromAgent, message = message, fromAgentID = botID, fromAgentName = bot.Controller.Name, fromGroup = false, imSessionID = UUID.Random(), offline = 0, ParentEstateID = 0, RegionID = bot.Controller.GetScene().RegionInfo.RegionID, timestamp = (uint)Util.UnixTimeSinceEpoch(), toAgentID = toUser }); } } #endregion #region Character Management public void CreateCharacter(UUID primID, IScene scene) { RemoveCharacter(primID); ISceneEntity entity = scene.GetSceneObjectPart(primID).ParentEntity; Bot bot = new Bot(); bot.Initialize(entity); m_bots.Add(primID, bot); AddTagToBot(primID, "AllBots", bot.AvatarCreatorID); } public IBotController GetCharacterManager(UUID primID) { foreach (Bot bot in m_bots.Values) { if (bot.Controller.UUID == primID) return bot.Controller; } return null; } public void RemoveCharacter(UUID primID) { if (m_bots.ContainsKey(primID)) { Bot b = m_bots[primID]; b.Close(true); RemoveAllTagsFromBot(primID, UUID.Zero); m_bots.Remove(primID); } } #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. namespace Microsoft.Xml.Serialization { using System; using Microsoft.Xml; internal class XmlSerializationPrimitiveWriter : Microsoft.Xml.Serialization.XmlSerializationWriter { internal void Write_string(object o) { WriteStartDocument(); if (o == null) { WriteNullTagLiteral(@"string", @""); return; } TopLevelElement(); WriteNullableStringLiteral(@"string", @"", ((System.String)o)); } internal void Write_int(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"int", @""); return; } WriteElementStringRaw(@"int", @"", Microsoft.Xml.XmlConvert.ToString((System.Int32)((System.Int32)o))); } internal void Write_boolean(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"boolean", @""); return; } WriteElementStringRaw(@"boolean", @"", Microsoft.Xml.XmlConvert.ToString((System.Boolean)((System.Boolean)o))); } internal void Write_short(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"short", @""); return; } WriteElementStringRaw(@"short", @"", Microsoft.Xml.XmlConvert.ToString((System.Int16)((System.Int16)o))); } internal void Write_long(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"long", @""); return; } WriteElementStringRaw(@"long", @"", Microsoft.Xml.XmlConvert.ToString((System.Int64)((System.Int64)o))); } internal void Write_float(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"float", @""); return; } WriteElementStringRaw(@"float", @"", Microsoft.Xml.XmlConvert.ToString((System.Single)((System.Single)o))); } internal void Write_double(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"double", @""); return; } WriteElementStringRaw(@"double", @"", Microsoft.Xml.XmlConvert.ToString((System.Double)((System.Double)o))); } internal void Write_decimal(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"decimal", @""); return; } WriteElementStringRaw(@"decimal", @"", Microsoft.Xml.XmlConvert.ToString((System.Decimal)((System.Decimal)o))); } internal void Write_dateTime(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"dateTime", @""); return; } WriteElementStringRaw(@"dateTime", @"", FromDateTime(((System.DateTime)o))); } internal void Write_unsignedByte(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"unsignedByte", @""); return; } WriteElementStringRaw(@"unsignedByte", @"", Microsoft.Xml.XmlConvert.ToString((System.Byte)((System.Byte)o))); } internal void Write_byte(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"byte", @""); return; } WriteElementStringRaw(@"byte", @"", Microsoft.Xml.XmlConvert.ToString((System.SByte)((System.SByte)o))); } internal void Write_unsignedShort(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"unsignedShort", @""); return; } WriteElementStringRaw(@"unsignedShort", @"", Microsoft.Xml.XmlConvert.ToString((System.UInt16)((System.UInt16)o))); } internal void Write_unsignedInt(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"unsignedInt", @""); return; } WriteElementStringRaw(@"unsignedInt", @"", Microsoft.Xml.XmlConvert.ToString((System.UInt32)((System.UInt32)o))); } internal void Write_unsignedLong(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"unsignedLong", @""); return; } WriteElementStringRaw(@"unsignedLong", @"", Microsoft.Xml.XmlConvert.ToString((System.UInt64)((System.UInt64)o))); } internal void Write_base64Binary(object o) { WriteStartDocument(); if (o == null) { WriteNullTagLiteral(@"base64Binary", @""); return; } TopLevelElement(); WriteNullableStringLiteralRaw(@"base64Binary", @"", FromByteArrayBase64(((System.Byte[])o))); } internal void Write_guid(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"guid", @""); return; } WriteElementStringRaw(@"guid", @"", Microsoft.Xml.XmlConvert.ToString((System.Guid)((System.Guid)o))); } internal void Write_char(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"char", @""); return; } WriteElementString(@"char", @"", FromChar(((System.Char)o))); } internal void Write_QName(object o) { WriteStartDocument(); if (o == null) { WriteNullTagLiteral(@"QName", @""); return; } TopLevelElement(); WriteNullableQualifiedNameLiteral(@"QName", @"", ((global::Microsoft.Xml.XmlQualifiedName)o)); } protected override void InitCallbacks() { } } internal class XmlSerializationPrimitiveReader : Microsoft.Xml.Serialization.XmlSerializationReader { internal object Read_string() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id1_string && (object)Reader.NamespaceURI == (object)_id2_Item)) { if (ReadNull()) { o = null; } else { o = Reader.ReadElementString(); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_int() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id3_int && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToInt32(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_boolean() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id4_boolean && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToBoolean(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_short() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id5_short && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToInt16(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_long() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id6_long && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToInt64(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_float() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id7_float && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToSingle(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_double() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id8_double && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToDouble(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_decimal() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id9_decimal && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToDecimal(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_dateTime() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id10_dateTime && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = ToDateTime(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_unsignedByte() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id11_unsignedByte && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToByte(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_byte() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id12_byte && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToSByte(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_unsignedShort() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id13_unsignedShort && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToUInt16(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_unsignedInt() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id14_unsignedInt && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToUInt32(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_unsignedLong() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id15_unsignedLong && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToUInt64(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_base64Binary() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id16_base64Binary && (object)Reader.NamespaceURI == (object)_id2_Item)) { if (ReadNull()) { o = null; } else { o = ToByteArrayBase64(false); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_guid() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id17_guid && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = Microsoft.Xml.XmlConvert.ToGuid(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_char() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id18_char && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = ToChar(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_QName() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == Microsoft.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id1_QName && (object)Reader.NamespaceURI == (object)_id2_Item)) { if (ReadNull()) { o = null; } else { o = ReadElementQualifiedName(); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } protected override void InitCallbacks() { } private System.String _id4_boolean; private System.String _id14_unsignedInt; private System.String _id15_unsignedLong; private System.String _id7_float; private System.String _id10_dateTime; private System.String _id6_long; private System.String _id9_decimal; private System.String _id8_double; private System.String _id17_guid; private System.String _id2_Item; private System.String _id13_unsignedShort; private System.String _id18_char; private System.String _id3_int; private System.String _id12_byte; private System.String _id16_base64Binary; private System.String _id11_unsignedByte; private System.String _id5_short; private System.String _id1_string; private System.String _id1_QName; protected override void InitIDs() { _id4_boolean = Reader.NameTable.Add(@"boolean"); _id14_unsignedInt = Reader.NameTable.Add(@"unsignedInt"); _id15_unsignedLong = Reader.NameTable.Add(@"unsignedLong"); _id7_float = Reader.NameTable.Add(@"float"); _id10_dateTime = Reader.NameTable.Add(@"dateTime"); _id6_long = Reader.NameTable.Add(@"long"); _id9_decimal = Reader.NameTable.Add(@"decimal"); _id8_double = Reader.NameTable.Add(@"double"); _id17_guid = Reader.NameTable.Add(@"guid"); _id2_Item = Reader.NameTable.Add(@""); _id13_unsignedShort = Reader.NameTable.Add(@"unsignedShort"); _id18_char = Reader.NameTable.Add(@"char"); _id3_int = Reader.NameTable.Add(@"int"); _id12_byte = Reader.NameTable.Add(@"byte"); _id16_base64Binary = Reader.NameTable.Add(@"base64Binary"); _id11_unsignedByte = Reader.NameTable.Add(@"unsignedByte"); _id5_short = Reader.NameTable.Add(@"short"); _id1_string = Reader.NameTable.Add(@"string"); _id1_QName = Reader.NameTable.Add(@"QName"); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; // Require a character controller to be attached to the same game object [RequireComponent(typeof(CharacterController))] [AddComponentMenu("Character/Character Motor")] public class CharacterMotor : MonoBehaviour { // Does this script currently respond to input? bool canControl = true; bool useFixedUpdate = true; // For the next variables, [System.NonSerialized] tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // The current global direction we want the character to move in. [System.NonSerialized] public Vector3 inputMoveDirection = Vector3.zero; // Is the jump button held down? We use this interface instead of checking // for the jump button directly so this script can also be used by AIs. [System.NonSerialized] public bool inputJump = false; [System.Serializable] public class CharacterMotorMovement { // The maximum horizontal speed when moving public float maxForwardSpeed = 6.0f; public float maxSidewaysSpeed = 6.0f; public float maxBackwardsSpeed = 6.0f; // Curve for multiplying speed based on slope(negative = downwards) public AnimationCurve slopeSpeedMultiplier = new AnimationCurve(new Keyframe(-90, 1), new Keyframe(0, 1), new Keyframe(90, 0)); // How fast does the character change speeds? Higher is faster. public float maxGroundAcceleration = 30.0f; public float maxAirAcceleration = 20.0f; // The gravity for the character public float gravity = 20f; public float maxFallSpeed = 20.0f; // For the next variables, [System.NonSerialized] tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // The last collision flags returned from controller.Move [System.NonSerialized] public CollisionFlags collisionFlags; // We will keep track of the character's current velocity, [System.NonSerialized] public Vector3 velocity; // This keeps track of our current velocity while we're not grounded [System.NonSerialized] public Vector3 frameVelocity = Vector3.zero; [System.NonSerialized] public Vector3 hitPoint = Vector3.zero; [System.NonSerialized] public Vector3 lastHitPoint = new Vector3(Mathf.Infinity, 0, 0); } public CharacterMotorMovement movement = new CharacterMotorMovement(); public enum MovementTransferOnJump { None, // The jump is not affected by velocity of floor at all. InitTransfer, // Jump gets its initial velocity from the floor, then gradualy comes to a stop. PermaTransfer, // Jump gets its initial velocity from the floor, and keeps that velocity until landing. PermaLocked // Jump is relative to the movement of the last touched floor and will move together with that floor. } // We will contain all the jumping related variables in one helper class for clarity. [System.Serializable] public class CharacterMotorJumping { // Can the character jump? public bool enabled = true; // How high do we jump when pressing jump and letting go immediately public float baseHeight = 1.0f; // We add extraHeight units(meters) on top when holding the button down longer while jumping public float extraHeight = 1f; // How much does the character jump out perpendicular to the surface on walkable surfaces? // 0 means a fully vertical jump and 1 means fully perpendicular. public float perpAmount = 0.0f; // How much does the character jump out perpendicular to the surface on too steep surfaces? // 0 means a fully vertical jump and 1 means fully perpendicular. public float steepPerpAmount = 0.5f; // For the next variables, [System.NonSerialized] tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // Are we jumping?(Initiated with jump button and not grounded yet) // To see ifwe are just in the air(initiated by jumping OR falling) see the grounded variable. [System.NonSerialized] public bool jumping = false; [System.NonSerialized] public bool holdingJumpButton = false; // the time we jumped at(Used to determine for how long to apply extra jump power after jumping.) [System.NonSerialized] public float lastStartTime = 0.0f; [System.NonSerialized] public float lastButtonDownTime = -100.0f; [System.NonSerialized] public Vector3 jumpDir = Vector3.up; } public CharacterMotorJumping jumping = new CharacterMotorJumping(); [System.Serializable] public class CharacterMotorMovingPlatform { public bool enabled = true; public MovementTransferOnJump movementTransfer = MovementTransferOnJump.PermaTransfer; [System.NonSerialized] public Transform hitPlatform; [System.NonSerialized] public Transform activePlatform; [System.NonSerialized] public Vector3 activeLocalPoint; [System.NonSerialized] public Vector3 activeGlobalPoint; [System.NonSerialized] public Quaternion activeLocalRotation; [System.NonSerialized] public Quaternion activeGlobalRotation; [System.NonSerialized] public Matrix4x4 lastMatrix; [System.NonSerialized] public Vector3 platformVelocity; [System.NonSerialized] public bool newPlatform; } public CharacterMotorMovingPlatform movingPlatform = new CharacterMotorMovingPlatform(); [System.Serializable] public class CharacterMotorSliding { // Does the character slide on too steep surfaces? public bool enabled = true; // How fast does the character slide on steep surfaces? public float slidingSpeed = 15.0f; // How much can the player control the sliding direction? // ifthe value is 0.5 the player can slide sideways with half the speed of the downwards sliding speed. public float sidewaysControl = 1.0f; // How much can the player influence the sliding speed? // ifthe value is 0.5 the player can speed the sliding up to 150% or slow it down to 50%. public float speedControl = 0.4f; } public CharacterMotorSliding sliding = new CharacterMotorSliding(); [System.NonSerialized] public bool grounded = true; [System.NonSerialized] public Vector3 groundNormal = Vector3.zero; private Vector3 lastGroundNormal = Vector3.zero; private Transform tr; private CharacterController controller; void Awake() { controller = GetComponent<CharacterController>(); tr = transform; } private void UpdateFunction() { // We copy the actual velocity into a temporary variable that we can manipulate. Vector3 velocity = movement.velocity; // Update velocity based on input velocity = ApplyInputVelocityChange(velocity); // Apply gravity and jumping force velocity = ApplyGravityAndJumping(velocity); // Moving platform support Vector3 moveDistance = Vector3.zero; if(MoveWithPlatform()) { Vector3 newGlobalPoint = movingPlatform.activePlatform.TransformPoint(movingPlatform.activeLocalPoint); moveDistance = (newGlobalPoint - movingPlatform.activeGlobalPoint); if(moveDistance != Vector3.zero) controller.Move(moveDistance); // Support moving platform rotation as well: Quaternion newGlobalRotation = movingPlatform.activePlatform.rotation * movingPlatform.activeLocalRotation; Quaternion rotationDiff = newGlobalRotation * Quaternion.Inverse(movingPlatform.activeGlobalRotation); var yRotation = rotationDiff.eulerAngles.y; if(yRotation != 0) { // Prevent rotation of the local up vector tr.Rotate(0, yRotation, 0); } } // Save lastPosition for velocity calculation. Vector3 lastPosition = tr.position; // We always want the movement to be framerate independent. Multiplying by Time.deltaTime does this. Vector3 currentMovementOffset = velocity * Time.deltaTime; // Find out how much we need to push towards the ground to avoid loosing grouning // when walking down a step or over a sharp change in slope. float pushDownOffset = Mathf.Max(controller.stepOffset, new Vector3(currentMovementOffset.x, 0, currentMovementOffset.z).magnitude); if(grounded) currentMovementOffset -= pushDownOffset * Vector3.up; // Reset variables that will be set by collision function movingPlatform.hitPlatform = null; groundNormal = Vector3.zero; // Move our character! movement.collisionFlags = controller.Move(currentMovementOffset); movement.lastHitPoint = movement.hitPoint; lastGroundNormal = groundNormal; if(movingPlatform.enabled && movingPlatform.activePlatform != movingPlatform.hitPlatform) { if(movingPlatform.hitPlatform != null) { movingPlatform.activePlatform = movingPlatform.hitPlatform; movingPlatform.lastMatrix = movingPlatform.hitPlatform.localToWorldMatrix; movingPlatform.newPlatform = true; } } // Calculate the velocity based on the current and previous position. // This means our velocity will only be the amount the character actually moved as a result of collisions. Vector3 oldHVelocity = new Vector3(velocity.x, 0, velocity.z); movement.velocity = (tr.position - lastPosition) / Time.deltaTime; Vector3 newHVelocity = new Vector3(movement.velocity.x, 0, movement.velocity.z); // The CharacterController can be moved in unwanted directions when colliding with things. // We want to prevent this from influencing the recorded velocity. if(oldHVelocity == Vector3.zero) { movement.velocity = new Vector3(0, movement.velocity.y, 0); } else { float projectedNewVelocity = Vector3.Dot(newHVelocity, oldHVelocity) / oldHVelocity.sqrMagnitude; movement.velocity = oldHVelocity * Mathf.Clamp01(projectedNewVelocity) + movement.velocity.y * Vector3.up; } if(movement.velocity.y < velocity.y - 0.001) { if(movement.velocity.y < 0) { // Something is forcing the CharacterController down faster than it should. // Ignore this movement.velocity.y = velocity.y; } else { // The upwards movement of the CharacterController has been blocked. // This is treated like a ceiling collision - stop further jumping here. jumping.holdingJumpButton = false; } } // We were grounded but just loosed grounding if(grounded && !IsGroundedTest()) { grounded = false; // Apply inertia from platform if(movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) ) { movement.frameVelocity = movingPlatform.platformVelocity; movement.velocity += movingPlatform.platformVelocity; } SendMessage("OnFall", SendMessageOptions.DontRequireReceiver); // We pushed the character down to ensure it would stay on the ground ifthere was any. // But there wasn't so now we cancel the downwards offset to make the fall smoother. tr.position += pushDownOffset * Vector3.up; } // We were not grounded but just landed on something else if(!grounded && IsGroundedTest()) { grounded = true; jumping.jumping = false; SubtractNewPlatformVelocity(); SendMessage("OnLand", SendMessageOptions.DontRequireReceiver); } // Moving platforms support if(MoveWithPlatform()) { // Use the center of the lower half sphere of the capsule as reference point. // This works best when the character is standing on moving tilting platforms. movingPlatform.activeGlobalPoint = tr.position + Vector3.up * (controller.center.y - controller.height * 0.5f + controller.radius); movingPlatform.activeLocalPoint = movingPlatform.activePlatform.InverseTransformPoint(movingPlatform.activeGlobalPoint); // Support moving platform rotation as well: movingPlatform.activeGlobalRotation = tr.rotation; movingPlatform.activeLocalRotation = Quaternion.Inverse(movingPlatform.activePlatform.rotation) * movingPlatform.activeGlobalRotation; } } void FixedUpdate() { if(movingPlatform.enabled) { if(movingPlatform.activePlatform != null) { if(!movingPlatform.newPlatform) { // unused: Vector3 lastVelocity = movingPlatform.platformVelocity; movingPlatform.platformVelocity = ( movingPlatform.activePlatform.localToWorldMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint) - movingPlatform.lastMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint) ) / Time.deltaTime; } movingPlatform.lastMatrix = movingPlatform.activePlatform.localToWorldMatrix; movingPlatform.newPlatform = false; } else { movingPlatform.platformVelocity = Vector3.zero; } } if(useFixedUpdate) UpdateFunction(); } void Update() { if(!useFixedUpdate) UpdateFunction(); } private Vector3 ApplyInputVelocityChange(Vector3 velocity) { if(!canControl) inputMoveDirection = Vector3.zero; // Find desired velocity Vector3 desiredVelocity; if(grounded && TooSteep()) { // The direction we're sliding in desiredVelocity = new Vector3(groundNormal.x, 0, groundNormal.z).normalized; // Find the input movement direction projected onto the sliding direction var projectedMoveDir = Vector3.Project(inputMoveDirection, desiredVelocity); // Add the sliding direction, the spped control, and the sideways control vectors desiredVelocity = desiredVelocity + projectedMoveDir * sliding.speedControl + (inputMoveDirection - projectedMoveDir) * sliding.sidewaysControl; // Multiply with the sliding speed desiredVelocity *= sliding.slidingSpeed; } else desiredVelocity = GetDesiredHorizontalVelocity(); if(movingPlatform.enabled && movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) { desiredVelocity += movement.frameVelocity; desiredVelocity.y = 0; } if(grounded) desiredVelocity = AdjustGroundVelocityToNormal(desiredVelocity, groundNormal); else velocity.y = 0; // Enforce max velocity change float maxVelocityChange = GetMaxAcceleration(grounded) * Time.deltaTime; Vector3 velocityChangeVector = (desiredVelocity - velocity); if(velocityChangeVector.sqrMagnitude > maxVelocityChange * maxVelocityChange) { velocityChangeVector = velocityChangeVector.normalized * maxVelocityChange; } // ifwe're in the air and don't have control, don't apply any velocity change at all. // ifwe're on the ground and don't have control we do apply it - it will correspond to friction. if(grounded || canControl) velocity += velocityChangeVector; if(grounded) { // When going uphill, the CharacterController will automatically move up by the needed amount. // Not moving it upwards manually prevent risk of lifting off from the ground. // When going downhill, DO move down manually, as gravity is not enough on steep hills. velocity.y = Mathf.Min(velocity.y, 0); } return velocity; } private Vector3 ApplyGravityAndJumping(Vector3 velocity) { if(!inputJump || !canControl) { jumping.holdingJumpButton = false; jumping.lastButtonDownTime = -100; } if(inputJump && jumping.lastButtonDownTime < 0 && canControl) jumping.lastButtonDownTime = Time.time; if(grounded) velocity.y = Mathf.Min(0, velocity.y) - movement.gravity * Time.deltaTime; else { velocity.y = movement.velocity.y - movement.gravity * Time.deltaTime; // When jumping up we don't apply gravity for some time when the user is holding the jump button. // This gives more control over jump height by pressing the button longer. if(jumping.jumping && jumping.holdingJumpButton) { // Calculate the duration that the extra jump force should have effect. // ifwe're still less than that duration after the jumping time, apply the force. if(Time.time < jumping.lastStartTime + jumping.extraHeight / CalculateJumpVerticalSpeed(jumping.baseHeight)) { // Negate the gravity we just applied, except we push in jumpDir rather than jump upwards. velocity += jumping.jumpDir * movement.gravity * Time.deltaTime; } } // Make sure we don't fall any faster than maxFallSpeed. This gives our character a terminal velocity. velocity.y = Mathf.Max(velocity.y, -movement.maxFallSpeed); } if(grounded) { // Jump only ifthe jump button was pressed down in the last 0.2 seconds. // We use this check instead of checking ifit's pressed down right now // because players will often try to jump in the exact moment when hitting the ground after a jump // and ifthey hit the button a fraction of a second too soon and no new jump happens as a consequence, // it's confusing and it feels like the game is buggy. if(jumping.enabled && canControl && (Time.time - jumping.lastButtonDownTime < 0.2)) { grounded = false; jumping.jumping = true; jumping.lastStartTime = Time.time; jumping.lastButtonDownTime = -100; jumping.holdingJumpButton = true; // Calculate the jumping direction if(TooSteep()) jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.steepPerpAmount); else jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.perpAmount); // Apply the jumping force to the velocity. Cancel any vertical velocity first. velocity.y = 0; velocity += jumping.jumpDir * CalculateJumpVerticalSpeed(jumping.baseHeight); // Apply inertia from platform if(movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) ) { movement.frameVelocity = movingPlatform.platformVelocity; velocity += movingPlatform.platformVelocity; } SendMessage("OnJump", SendMessageOptions.DontRequireReceiver); } else { jumping.holdingJumpButton = false; } } return velocity; } void OnControllerColliderHit(ControllerColliderHit hit) { if(hit.normal.y > 0 && hit.normal.y > groundNormal.y && hit.moveDirection.y < 0) { if((hit.point - movement.lastHitPoint).sqrMagnitude > 0.001 || lastGroundNormal == Vector3.zero) groundNormal = hit.normal; else groundNormal = lastGroundNormal; movingPlatform.hitPlatform = hit.collider.transform; movement.hitPoint = hit.point; movement.frameVelocity = Vector3.zero; } } private IEnumerator SubtractNewPlatformVelocity() { // When landing, subtract the velocity of the new ground from the character's velocity // since movement in ground is relative to the movement of the ground. if(movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer)) { // if we landed on a new platform, we have to wait for two FixedUpdates // before we know the velocity of the platform under the character if(movingPlatform.newPlatform) { Transform platform = movingPlatform.activePlatform; yield return new WaitForFixedUpdate(); yield return new WaitForFixedUpdate(); if(grounded && platform == movingPlatform.activePlatform) yield break; } movement.velocity -= movingPlatform.platformVelocity; } } private bool MoveWithPlatform() { return (movingPlatform.enabled && (grounded || movingPlatform.movementTransfer == MovementTransferOnJump.PermaLocked) && movingPlatform.activePlatform != null ); } private Vector3 GetDesiredHorizontalVelocity() { // Find desired velocity Vector3 desiredLocalDirection = tr.InverseTransformDirection(inputMoveDirection); float maxSpeed = MaxSpeedInDirection(desiredLocalDirection); if(grounded) { // Modify max speed on slopes based on slope speed multiplier curve var movementSlopeAngle = Mathf.Asin(movement.velocity.normalized.y) * Mathf.Rad2Deg; maxSpeed *= movement.slopeSpeedMultiplier.Evaluate(movementSlopeAngle); } return tr.TransformDirection(desiredLocalDirection * maxSpeed); } private Vector3 AdjustGroundVelocityToNormal(Vector3 hVelocity, Vector3 groundNormal) { Vector3 sideways = Vector3.Cross(Vector3.up, hVelocity); return Vector3.Cross(sideways, groundNormal).normalized * hVelocity.magnitude; } private bool IsGroundedTest() { return (groundNormal.y > 0.01); } float GetMaxAcceleration(bool grounded) { // Maximum acceleration on ground and in air if(grounded) return movement.maxGroundAcceleration; else return movement.maxAirAcceleration; } float CalculateJumpVerticalSpeed(float targetJumpHeight) { // From the jump height and gravity we deduce the upwards speed // for the character to reach at the apex. return Mathf.Sqrt(2 * targetJumpHeight * movement.gravity); } bool IsJumping() { return jumping.jumping; } bool IsSliding() { return (grounded && sliding.enabled && TooSteep()); } bool IsTouchingCeiling() { return (movement.collisionFlags & CollisionFlags.CollidedAbove) != 0; } bool IsGrounded() { return grounded; } bool TooSteep() { return (groundNormal.y <= Mathf.Cos(controller.slopeLimit * Mathf.Deg2Rad)); } Vector3 GetDirection() { return inputMoveDirection; } void SetControllable(bool controllable) { canControl = controllable; } // Project a direction onto elliptical quater segments based on forward, sideways, and backwards speed. // The function returns the length of the resulting vector. float MaxSpeedInDirection(Vector3 desiredMovementDirection) { if(desiredMovementDirection == Vector3.zero) return 0; else { float zAxisEllipseMultiplier = (desiredMovementDirection.z > 0 ? movement.maxForwardSpeed : movement.maxBackwardsSpeed) / movement.maxSidewaysSpeed; Vector3 temp = new Vector3(desiredMovementDirection.x, 0, desiredMovementDirection.z / zAxisEllipseMultiplier).normalized; float length = new Vector3(temp.x, 0, temp.z * zAxisEllipseMultiplier).magnitude * movement.maxSidewaysSpeed; return length; } } void SetVelocity(Vector3 velocity) { grounded = false; movement.velocity = velocity; movement.frameVelocity = Vector3.zero; SendMessage("OnExternalVelocity"); } }
// // ContentValues.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.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. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, 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 System; using System.Collections.Generic; using System.Text; using Couchbase.Lite.Util; using Sharpen; namespace Couchbase.Lite.Storage { public sealed class ContentValues { public const string Tag = "ContentValues"; /// <summary>Holds the actual values</summary> private readonly Dictionary<string, object> mValues; /// <summary>Creates an empty set of values using the default initial size</summary> public ContentValues() { // COPY: Copied from android.content.ContentValues // Choosing a default size of 8 based on analysis of typical // consumption by applications. mValues = new Dictionary<string, object>(8); } /// <summary>Creates an empty set of values using the given initial size</summary> /// <param name="size">the initial size of the set of values</param> public ContentValues(int size) { mValues = new Dictionary<String, Object>(size); } /// <summary>Creates a set of values copied from the given set</summary> /// <param name="from">the values to copy</param> public ContentValues(ContentValues from) { mValues = new Dictionary<string, object>(from.mValues); } public override bool Equals(object obj) { if (!(obj is ContentValues)) { return false; } return mValues.Equals(((ContentValues)obj).mValues); } public override int GetHashCode() { return mValues.GetHashCode(); } internal Object this[String key] { get { return mValues[key]; } set { mValues[key] = value; } } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, string value) { mValues[key] = value; } /// <summary>Adds all values from the passed in ContentValues.</summary> /// <remarks>Adds all values from the passed in ContentValues.</remarks> /// <param name="other">the ContentValues from which to copy</param> public void PutAll(Couchbase.Lite.Storage.ContentValues other) { mValues.PutAll(other.mValues); } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, byte value) { mValues[key] = value; } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, short value) { mValues[key] = value; } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, int value) { mValues[key] = value; } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, long value) { mValues[key] = value; } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, float value) { mValues[key] = value; } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, double value) { mValues[key] = value; } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, bool value) { mValues[key] = value; } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, IEnumerable<Byte> value) { mValues[key] = value; } /// <summary>Adds a null value to the set.</summary> /// <remarks>Adds a null value to the set.</remarks> /// <param name="key">the name of the value to make null</param> public void PutNull(string key) { mValues[key] = null; } /// <summary>Returns the number of values.</summary> /// <remarks>Returns the number of values.</remarks> /// <returns>the number of values</returns> public int Size() { return mValues.Count; } /// <summary>Remove a single value.</summary> /// <remarks>Remove a single value.</remarks> /// <param name="key">the name of the value to remove</param> public void Remove(string key) { Sharpen.Collections.Remove(mValues, key); } /// <summary>Removes all values.</summary> /// <remarks>Removes all values.</remarks> public void Clear() { mValues.Clear(); } /// <summary>Returns true if this object has the named value.</summary> /// <remarks>Returns true if this object has the named value.</remarks> /// <param name="key">the value to check for</param> /// <returns> /// /// <code>true</code> /// if the value is present, /// <code>false</code> /// otherwise /// </returns> public bool ContainsKey(string key) { return mValues.ContainsKey(key); } /// <summary>Gets a value.</summary> /// <remarks> /// Gets a value. Valid value types are /// <see cref="string">string</see> /// , /// <see cref="bool">bool</see> /// , and /// <see cref="Sharpen.Number">Sharpen.Number</see> /// implementations. /// </remarks> /// <param name="key">the value to get</param> /// <returns>the data for the value</returns> public object Get(string key) { return mValues.Get(key); } /// <summary>Gets a value and converts it to a String.</summary> /// <remarks>Gets a value and converts it to a String.</remarks> /// <param name="key">the value to get</param> /// <returns>the String for the value</returns> public string GetAsString(string key) { object value = mValues.Get(key); return value != null ? value.ToString() : null; } /// <summary>Gets a value and converts it to a Long.</summary> /// <remarks>Gets a value and converts it to a Long.</remarks> /// <param name="key">the value to get</param> /// <returns>the Long value, or null if the value is missing or cannot be converted</returns> public Nullable<Int64> GetAsLong(string key) { object value = mValues.Get(key); try { return value != null ? ((Int64?)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return Int64.Parse(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Long value for " + value + " at key " + key); return null; } } else { Log.E(Tag, "Cannot cast value for " + key + " to a Long: " + value, e); return null; } } } /// <summary>Gets a value and converts it to an Integer.</summary> /// <remarks>Gets a value and converts it to an Integer.</remarks> /// <param name="key">the value to get</param> /// <returns>the Integer value, or null if the value is missing or cannot be converted /// </returns> public Nullable<Int32> GetAsInteger(string key) { object value = mValues.Get(key); try { return value != null ? ((Int32?)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return Int32.Parse(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Integer value for " + value + " at key " + key); return null; } } else { Log.E(Tag, "Cannot cast value for " + key + " to a Integer: " + value, e); return null; } } } /// <summary>Gets a value and converts it to a Short.</summary> /// <remarks>Gets a value and converts it to a Short.</remarks> /// <param name="key">the value to get</param> /// <returns>the Short value, or null if the value is missing or cannot be converted</returns> public Nullable<Int16> GetAsShort(string key) { object value = mValues.Get(key); try { return value != null ? ((Int16?)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return Int16.Parse(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Short value for " + value + " at key " + key); return null; } } else { Log.E(Tag, "Cannot cast value for " + key + " to a Short: " + value, e); return null; } } } /// <summary>Gets a value and converts it to a Byte.</summary> /// <remarks>Gets a value and converts it to a Byte.</remarks> /// <param name="key">the value to get</param> /// <returns>the Byte value, or null if the value is missing or cannot be converted</returns> public Nullable<Byte> GetAsByte(string key) { object value = mValues.Get(key); try { return value != null ? ((Byte?)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return Byte.Parse(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Byte value for " + value + " at key " + key); return null; } } else { Log.E(Tag, "Cannot cast value for " + key + " to a Byte: " + value, e); return null; } } } /// <summary>Gets a value and converts it to a Double.</summary> /// <remarks>Gets a value and converts it to a Double.</remarks> /// <param name="key">the value to get</param> /// <returns>the Double value, or null if the value is missing or cannot be converted /// </returns> public Nullable<Double> GetAsDouble(string key) { object value = mValues.Get(key); try { return value != null ? ((Double?)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return Double.Parse(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Double value for " + value + " at key " + key); return null; } } else { Log.E(Tag, "Cannot cast value for " + key + " to a Double: " + value, e); return null; } } } /// <summary>Gets a value and converts it to a Float.</summary> /// <remarks>Gets a value and converts it to a Float.</remarks> /// <param name="key">the value to get</param> /// <returns>the Float value, or null if the value is missing or cannot be converted</returns> public Nullable<Single> GetAsFloat(string key) { object value = mValues.Get(key); try { return value != null ? ((Single?)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return Single.Parse(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Float value for " + value + " at key " + key); return null; } } else { Log.E(Tag, "Cannot cast value for " + key + " to a Float: " + value, e); return null; } } } /// <summary>Gets a value and converts it to a Boolean.</summary> /// <remarks>Gets a value and converts it to a Boolean.</remarks> /// <param name="key">the value to get</param> /// <returns>the Boolean value, or null if the value is missing or cannot be converted /// </returns> public Nullable<Boolean> GetAsBoolean(string key) { object value = mValues.Get(key); try { return (Boolean)value; } catch (InvalidCastException e) { if (value is CharSequence) { return Boolean.Parse(value.ToString()); } else { if (value is IConvertible) { return Convert.ToBoolean(value); } else { Log.E(Tag, "Cannot cast value for " + key + " to a Boolean: " + value, e); return null; } } } } /// <summary>Gets a value that is a byte array.</summary> /// <remarks> /// Gets a value that is a byte array. Note that this method will not convert /// any other types to byte arrays. /// </remarks> /// <param name="key">the value to get</param> /// <returns>the byte[] value, or null is the value is missing or not a byte[]</returns> public byte[] GetAsByteArray(string key) { object value = mValues.Get(key); if (value is byte[]) { return (byte[])value; } else { return null; } } /// <summary>Returns a set of all of the keys and values</summary> /// <returns>a set of all of the keys and values</returns> public ICollection<KeyValuePair<string, object>> ValueSet() { return mValues.EntrySet(); } /// <summary>Returns a set of all of the keys</summary> /// <returns>a set of all of the keys</returns> public ICollection<string> KeySet() { return mValues.Keys; } /// <summary>Returns a string containing a concise, human-readable description of this object. /// </summary> /// <remarks>Returns a string containing a concise, human-readable description of this object. /// </remarks> /// <returns>a printable representation of this object.</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (string name in mValues.Keys) { string value = GetAsString(name); if (sb.Length > 0) { sb.Append(" "); } sb.Append(name + "=" + value); } return sb.ToString(); } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace HostWebEventsWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reactive.Disposables; using System.Runtime.InteropServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Win32.Input; using Avalonia.Win32.Interop; using static Avalonia.Win32.Interop.UnmanagedMethods; namespace Avalonia.Win32 { public class WindowImpl : IWindowImpl { private static readonly List<WindowImpl> s_instances = new List<WindowImpl>(); private static readonly IntPtr DefaultCursor = UnmanagedMethods.LoadCursor( IntPtr.Zero, new IntPtr((int)UnmanagedMethods.Cursor.IDC_ARROW)); private UnmanagedMethods.WndProc _wndProcDelegate; private string _className; private IntPtr _hwnd; private IInputRoot _owner; private bool _trackingMouse; private bool _decorated = true; private bool _resizable = true; private double _scaling = 1; private WindowState _showWindowState; private FramebufferManager _framebuffer; private OleDropTarget _dropTarget; private Size _minSize; private Size _maxSize; #if USE_MANAGED_DRAG private readonly ManagedWindowResizeDragHelper _managedDrag; #endif public WindowImpl() { #if USE_MANAGED_DRAG _managedDrag = new ManagedWindowResizeDragHelper(this, capture => { if (capture) UnmanagedMethods.SetCapture(Handle.Handle); else UnmanagedMethods.ReleaseCapture(); }); #endif CreateWindow(); _framebuffer = new FramebufferManager(_hwnd); s_instances.Add(this); } public Action Activated { get; set; } public Func<bool> Closing { get; set; } public Action Closed { get; set; } public Action Deactivated { get; set; } public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size> Resized { get; set; } public Action<double> ScalingChanged { get; set; } public Action<Point> PositionChanged { get; set; } public Thickness BorderThickness { get { var style = UnmanagedMethods.GetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_STYLE); var exStyle = UnmanagedMethods.GetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_EXSTYLE); var padding = new UnmanagedMethods.RECT(); if (UnmanagedMethods.AdjustWindowRectEx(ref padding, style, false, exStyle)) { return new Thickness(-padding.left, -padding.top, padding.right, padding.bottom); } else { throw new Win32Exception(); } } } public Size ClientSize { get { UnmanagedMethods.RECT rect; UnmanagedMethods.GetClientRect(_hwnd, out rect); return new Size(rect.right, rect.bottom) / Scaling; } } public void SetMinMaxSize(Size minSize, Size maxSize) { _minSize = minSize; _maxSize = maxSize; } public IScreenImpl Screen { get; } = new ScreenImpl(); public IRenderer CreateRenderer(IRenderRoot root) { var loop = AvaloniaLocator.Current.GetService<IRenderLoop>(); return Win32Platform.UseDeferredRendering ? (IRenderer)new DeferredRenderer(root, loop) : new ImmediateRenderer(root); } public void Resize(Size value) { if (value != ClientSize) { value *= Scaling; value += BorderThickness; UnmanagedMethods.SetWindowPos( _hwnd, IntPtr.Zero, 0, 0, (int)value.Width, (int)value.Height, UnmanagedMethods.SetWindowPosFlags.SWP_RESIZE); } } public double Scaling => _scaling; public IPlatformHandle Handle { get; private set; } public bool IsEnabled { get { return UnmanagedMethods.IsWindowEnabled(_hwnd); } set { UnmanagedMethods.EnableWindow(_hwnd, value); } } public Size MaxClientSize { get { return (new Size( UnmanagedMethods.GetSystemMetrics(UnmanagedMethods.SystemMetric.SM_CXMAXTRACK), UnmanagedMethods.GetSystemMetrics(UnmanagedMethods.SystemMetric.SM_CYMAXTRACK)) - BorderThickness) / Scaling; } } public IMouseDevice MouseDevice => WindowsMouseDevice.Instance; public WindowState WindowState { get { var placement = default(UnmanagedMethods.WINDOWPLACEMENT); UnmanagedMethods.GetWindowPlacement(_hwnd, ref placement); switch (placement.ShowCmd) { case UnmanagedMethods.ShowWindowCommand.Maximize: return WindowState.Maximized; case UnmanagedMethods.ShowWindowCommand.Minimize: return WindowState.Minimized; default: return WindowState.Normal; } } set { if (UnmanagedMethods.IsWindowVisible(_hwnd)) { ShowWindow(value); } else { _showWindowState = value; } } } public IEnumerable<object> Surfaces => new object[] { Handle, _framebuffer }; public void Activate() { UnmanagedMethods.SetActiveWindow(_hwnd); } public IPopupImpl CreatePopup() { return new PopupImpl(); } public void Dispose() { _framebuffer?.Dispose(); _framebuffer = null; if (_hwnd != IntPtr.Zero) { UnmanagedMethods.DestroyWindow(_hwnd); _hwnd = IntPtr.Zero; } if (_className != null) { UnmanagedMethods.UnregisterClass(_className, UnmanagedMethods.GetModuleHandle(null)); _className = null; } } public void Hide() { UnmanagedMethods.ShowWindow(_hwnd, UnmanagedMethods.ShowWindowCommand.Hide); } public void SetSystemDecorations(bool value) { if (value == _decorated) { return; } var style = (UnmanagedMethods.WindowStyles)UnmanagedMethods.GetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_STYLE); var systemDecorationStyles = UnmanagedMethods.WindowStyles.WS_OVERLAPPED | UnmanagedMethods.WindowStyles.WS_CAPTION | UnmanagedMethods.WindowStyles.WS_SYSMENU | UnmanagedMethods.WindowStyles.WS_MINIMIZEBOX | UnmanagedMethods.WindowStyles.WS_MAXIMIZEBOX; style |= systemDecorationStyles; if (!value) { style ^= systemDecorationStyles; } UnmanagedMethods.RECT windowRect; UnmanagedMethods.GetWindowRect(_hwnd, out windowRect); Rect newRect; var oldThickness = BorderThickness; UnmanagedMethods.SetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_STYLE, (uint)style); if (value) { var thickness = BorderThickness; newRect = new Rect( windowRect.left - thickness.Left, windowRect.top - thickness.Top, (windowRect.right - windowRect.left) + (thickness.Left + thickness.Right), (windowRect.bottom - windowRect.top) + (thickness.Top + thickness.Bottom)); } else { newRect = new Rect( windowRect.left + oldThickness.Left, windowRect.top + oldThickness.Top, (windowRect.right - windowRect.left) - (oldThickness.Left + oldThickness.Right), (windowRect.bottom - windowRect.top) - (oldThickness.Top + oldThickness.Bottom)); } UnmanagedMethods.SetWindowPos(_hwnd, IntPtr.Zero, (int)newRect.X, (int)newRect.Y, (int)newRect.Width, (int)newRect.Height, UnmanagedMethods.SetWindowPosFlags.SWP_NOZORDER | UnmanagedMethods.SetWindowPosFlags.SWP_NOACTIVATE); _decorated = value; } public void Invalidate(Rect rect) { var f = Scaling; var r = new UnmanagedMethods.RECT { left = (int)(rect.X * f), top = (int)(rect.Y * f), right = (int)(rect.Right * f), bottom = (int)(rect.Bottom * f), }; UnmanagedMethods.InvalidateRect(_hwnd, ref r, false); } public Point PointToClient(Point point) { var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ScreenToClient(_hwnd, ref p); return new Point(p.X, p.Y) / Scaling; } public Point PointToScreen(Point point) { point *= Scaling; var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ClientToScreen(_hwnd, ref p); return new Point(p.X, p.Y); } public void SetInputRoot(IInputRoot inputRoot) { _owner = inputRoot; CreateDropTarget(); } public void SetTitle(string title) { UnmanagedMethods.SetWindowText(_hwnd, title); } public virtual void Show() { ShowWindow(_showWindowState); } public void BeginMoveDrag() { UnmanagedMethods.DefWindowProc(_hwnd, (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN, new IntPtr((int)UnmanagedMethods.HitTestValues.HTCAPTION), IntPtr.Zero); } static readonly Dictionary<WindowEdge, UnmanagedMethods.HitTestValues> EdgeDic = new Dictionary<WindowEdge, UnmanagedMethods.HitTestValues> { {WindowEdge.East, UnmanagedMethods.HitTestValues.HTRIGHT}, {WindowEdge.North, UnmanagedMethods.HitTestValues.HTTOP }, {WindowEdge.NorthEast, UnmanagedMethods.HitTestValues.HTTOPRIGHT }, {WindowEdge.NorthWest, UnmanagedMethods.HitTestValues.HTTOPLEFT }, {WindowEdge.South, UnmanagedMethods.HitTestValues.HTBOTTOM }, {WindowEdge.SouthEast, UnmanagedMethods.HitTestValues.HTBOTTOMRIGHT }, {WindowEdge.SouthWest, UnmanagedMethods.HitTestValues.HTBOTTOMLEFT }, {WindowEdge.West, UnmanagedMethods.HitTestValues.HTLEFT} }; public void BeginResizeDrag(WindowEdge edge) { #if USE_MANAGED_DRAG _managedDrag.BeginResizeDrag(edge, ScreenToClient(MouseDevice.Position)); #else UnmanagedMethods.DefWindowProc(_hwnd, (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN, new IntPtr((int)EdgeDic[edge]), IntPtr.Zero); #endif } public Point Position { get { UnmanagedMethods.RECT rc; UnmanagedMethods.GetWindowRect(_hwnd, out rc); return new Point(rc.left, rc.top); } set { UnmanagedMethods.SetWindowPos( Handle.Handle, IntPtr.Zero, (int)value.X, (int)value.Y, 0, 0, UnmanagedMethods.SetWindowPosFlags.SWP_NOSIZE | UnmanagedMethods.SetWindowPosFlags.SWP_NOACTIVATE); } } public virtual IDisposable ShowDialog() { Show(); return Disposable.Empty; } public void SetCursor(IPlatformHandle cursor) { var hCursor = cursor?.Handle ?? DefaultCursor; UnmanagedMethods.SetClassLong(_hwnd, UnmanagedMethods.ClassLongIndex.GCL_HCURSOR, hCursor); if (_owner.IsPointerOver) UnmanagedMethods.SetCursor(hCursor); } protected virtual IntPtr CreateWindowOverride(ushort atom) { return UnmanagedMethods.CreateWindowEx( 0, atom, null, (int)UnmanagedMethods.WindowStyles.WS_OVERLAPPEDWINDOW, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Using Win32 naming for consistency.")] protected virtual IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) { bool unicode = UnmanagedMethods.IsWindowUnicode(hWnd); const double wheelDelta = 120.0; uint timestamp = unchecked((uint)UnmanagedMethods.GetMessageTime()); RawInputEventArgs e = null; WindowsMouseDevice.Instance.CurrentWindow = this; switch ((UnmanagedMethods.WindowsMessage)msg) { case UnmanagedMethods.WindowsMessage.WM_ACTIVATE: var wa = (UnmanagedMethods.WindowActivate)(ToInt32(wParam) & 0xffff); switch (wa) { case UnmanagedMethods.WindowActivate.WA_ACTIVE: case UnmanagedMethods.WindowActivate.WA_CLICKACTIVE: Activated?.Invoke(); break; case UnmanagedMethods.WindowActivate.WA_INACTIVE: Deactivated?.Invoke(); break; } return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_CLOSE: bool? preventClosing = Closing?.Invoke(); if (preventClosing == true) { return IntPtr.Zero; } break; case UnmanagedMethods.WindowsMessage.WM_DESTROY: //Window doesn't exist anymore _hwnd = IntPtr.Zero; //Remove root reference to this class, so unmanaged delegate can be collected s_instances.Remove(this); Closed?.Invoke(); //Free other resources Dispose(); return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_DPICHANGED: var dpi = ToInt32(wParam) & 0xffff; var newDisplayRect = Marshal.PtrToStructure<UnmanagedMethods.RECT>(lParam); Position = new Point(newDisplayRect.left, newDisplayRect.top); _scaling = dpi / 96.0; ScalingChanged?.Invoke(_scaling); return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_KEYDOWN: case UnmanagedMethods.WindowsMessage.WM_SYSKEYDOWN: e = new RawKeyEventArgs( WindowsKeyboardDevice.Instance, timestamp, RawKeyEventType.KeyDown, KeyInterop.KeyFromVirtualKey(ToInt32(wParam)), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_KEYUP: case UnmanagedMethods.WindowsMessage.WM_SYSKEYUP: e = new RawKeyEventArgs( WindowsKeyboardDevice.Instance, timestamp, RawKeyEventType.KeyUp, KeyInterop.KeyFromVirtualKey(ToInt32(wParam)), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_CHAR: // Ignore control chars if (ToInt32(wParam) >= 32) { e = new RawTextInputEventArgs(WindowsKeyboardDevice.Instance, timestamp, new string((char)ToInt32(wParam), 1)); } break; case UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_MBUTTONDOWN: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int)UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN ? RawMouseEventType.LeftButtonDown : msg == (int)UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN ? RawMouseEventType.RightButtonDown : RawMouseEventType.MiddleButtonDown, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_LBUTTONUP: case UnmanagedMethods.WindowsMessage.WM_RBUTTONUP: case UnmanagedMethods.WindowsMessage.WM_MBUTTONUP: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int)UnmanagedMethods.WindowsMessage.WM_LBUTTONUP ? RawMouseEventType.LeftButtonUp : msg == (int)UnmanagedMethods.WindowsMessage.WM_RBUTTONUP ? RawMouseEventType.RightButtonUp : RawMouseEventType.MiddleButtonUp, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSEMOVE: if (!_trackingMouse) { var tm = new UnmanagedMethods.TRACKMOUSEEVENT { cbSize = Marshal.SizeOf<UnmanagedMethods.TRACKMOUSEEVENT>(), dwFlags = 2, hwndTrack = _hwnd, dwHoverTime = 0, }; UnmanagedMethods.TrackMouseEvent(ref tm); } e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, RawMouseEventType.Move, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSEWHEEL: e = new RawMouseWheelEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, PointToClient(PointFromLParam(lParam)), new Vector(0, (ToInt32(wParam) >> 16) / wheelDelta), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSEHWHEEL: e = new RawMouseWheelEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, PointToClient(PointFromLParam(lParam)), new Vector(-(ToInt32(wParam) >> 16) / wheelDelta, 0), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSELEAVE: _trackingMouse = false; e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, RawMouseEventType.LeaveWindow, new Point(), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_NCMBUTTONDOWN: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN ? RawMouseEventType.NonClientLeftButtonDown : msg == (int)UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN ? RawMouseEventType.RightButtonDown : RawMouseEventType.MiddleButtonDown, new Point(0, 0), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_PAINT: UnmanagedMethods.PAINTSTRUCT ps; if (UnmanagedMethods.BeginPaint(_hwnd, out ps) != IntPtr.Zero) { var f = Scaling; var r = ps.rcPaint; Paint?.Invoke(new Rect(r.left / f, r.top / f, (r.right - r.left) / f, (r.bottom - r.top) / f)); UnmanagedMethods.EndPaint(_hwnd, ref ps); } return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_SIZE: if (Resized != null && (wParam == (IntPtr)UnmanagedMethods.SizeCommand.Restored || wParam == (IntPtr)UnmanagedMethods.SizeCommand.Maximized)) { var clientSize = new Size(ToInt32(lParam) & 0xffff, ToInt32(lParam) >> 16); Resized(clientSize / Scaling); } return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_MOVE: PositionChanged?.Invoke(new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16))); return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_GETMINMAXINFO: MINMAXINFO mmi = Marshal.PtrToStructure<UnmanagedMethods.MINMAXINFO>(lParam); if (_minSize.Width > 0) mmi.ptMinTrackSize.X = (int)((_minSize.Width * Scaling) + BorderThickness.Left + BorderThickness.Right); if (_minSize.Height > 0) mmi.ptMinTrackSize.Y = (int)((_minSize.Height * Scaling) + BorderThickness.Top + BorderThickness.Bottom); if (!Double.IsInfinity(_maxSize.Width) && _maxSize.Width > 0) mmi.ptMaxTrackSize.X = (int)((_maxSize.Width * Scaling) + BorderThickness.Left + BorderThickness.Right); if (!Double.IsInfinity(_maxSize.Height) && _maxSize.Height > 0) mmi.ptMaxTrackSize.Y = (int)((_maxSize.Height * Scaling) + BorderThickness.Top + BorderThickness.Bottom); Marshal.StructureToPtr(mmi, lParam, true); return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_DISPLAYCHANGE: (Screen as ScreenImpl)?.InvalidateScreensCache(); return IntPtr.Zero; } #if USE_MANAGED_DRAG if (_managedDrag.PreprocessInputEvent(ref e)) return UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam); #endif if (e != null && Input != null) { Input(e); if (e.Handled) { return IntPtr.Zero; } } return UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam); } static InputModifiers GetMouseModifiers(IntPtr wParam) { var keys = (UnmanagedMethods.ModifierKeys)ToInt32(wParam); var modifiers = WindowsKeyboardDevice.Instance.Modifiers; if (keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_LBUTTON)) modifiers |= InputModifiers.LeftMouseButton; if (keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_RBUTTON)) modifiers |= InputModifiers.RightMouseButton; if (keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_MBUTTON)) modifiers |= InputModifiers.MiddleMouseButton; return modifiers; } private void CreateWindow() { // Ensure that the delegate doesn't get garbage collected by storing it as a field. _wndProcDelegate = new UnmanagedMethods.WndProc(WndProc); _className = "Avalonia-" + Guid.NewGuid(); UnmanagedMethods.WNDCLASSEX wndClassEx = new UnmanagedMethods.WNDCLASSEX { cbSize = Marshal.SizeOf<UnmanagedMethods.WNDCLASSEX>(), style = 0, lpfnWndProc = _wndProcDelegate, hInstance = UnmanagedMethods.GetModuleHandle(null), hCursor = DefaultCursor, hbrBackground = IntPtr.Zero, lpszClassName = _className }; ushort atom = UnmanagedMethods.RegisterClassEx(ref wndClassEx); if (atom == 0) { throw new Win32Exception(); } _hwnd = CreateWindowOverride(atom); if (_hwnd == IntPtr.Zero) { throw new Win32Exception(); } Handle = new PlatformHandle(_hwnd, PlatformConstants.WindowHandleType); if (UnmanagedMethods.ShCoreAvailable) { uint dpix, dpiy; var monitor = UnmanagedMethods.MonitorFromWindow( _hwnd, UnmanagedMethods.MONITOR.MONITOR_DEFAULTTONEAREST); if (UnmanagedMethods.GetDpiForMonitor( monitor, UnmanagedMethods.MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI, out dpix, out dpiy) == 0) { _scaling = dpix / 96.0; } } } private void CreateDropTarget() { OleDropTarget odt = new OleDropTarget(this, _owner); if (OleContext.Current?.RegisterDragDrop(Handle, odt) ?? false) _dropTarget = odt; } private Point DipFromLParam(IntPtr lParam) { return new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16)) / Scaling; } private Point PointFromLParam(IntPtr lParam) { return new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16)); } private Point ScreenToClient(Point point) { var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ScreenToClient(_hwnd, ref p); return new Point(p.X, p.Y); } private void ShowWindow(WindowState state) { UnmanagedMethods.ShowWindowCommand command; switch (state) { case WindowState.Minimized: command = ShowWindowCommand.Minimize; break; case WindowState.Maximized: command = ShowWindowCommand.Maximize; break; case WindowState.Normal: command = ShowWindowCommand.Restore; break; default: throw new ArgumentException("Invalid WindowState."); } UnmanagedMethods.ShowWindow(_hwnd, command); if (state == WindowState.Maximized) { MaximizeWithoutCoveringTaskbar(); } if (!Design.IsDesignMode) { SetFocus(_hwnd); } } private void MaximizeWithoutCoveringTaskbar() { IntPtr monitor = MonitorFromWindow(_hwnd, MONITOR.MONITOR_DEFAULTTONEAREST); if (monitor != IntPtr.Zero) { MONITORINFO monitorInfo = new MONITORINFO(); if (GetMonitorInfo(monitor, monitorInfo)) { RECT rcMonitorArea = monitorInfo.rcMonitor; var x = monitorInfo.rcWork.left; var y = monitorInfo.rcWork.top; var cx = Math.Abs(monitorInfo.rcWork.right - x); var cy = Math.Abs(monitorInfo.rcWork.bottom - y); SetWindowPos(_hwnd, new IntPtr(-2), x, y, cx, cy, SetWindowPosFlags.SWP_SHOWWINDOW); } } } public void SetIcon(IWindowIconImpl icon) { var impl = (IconImpl)icon; var hIcon = impl.HIcon; UnmanagedMethods.PostMessage(_hwnd, (int)UnmanagedMethods.WindowsMessage.WM_SETICON, new IntPtr((int)UnmanagedMethods.Icons.ICON_BIG), hIcon); } private static int ToInt32(IntPtr ptr) { if (IntPtr.Size == 4) return ptr.ToInt32(); return (int)(ptr.ToInt64() & 0xffffffff); } public void ShowTaskbarIcon(bool value) { var style = (UnmanagedMethods.WindowStyles)UnmanagedMethods.GetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_EXSTYLE); style &= ~(UnmanagedMethods.WindowStyles.WS_VISIBLE); style |= UnmanagedMethods.WindowStyles.WS_EX_TOOLWINDOW; if (value) style |= UnmanagedMethods.WindowStyles.WS_EX_APPWINDOW; else style &= ~(UnmanagedMethods.WindowStyles.WS_EX_APPWINDOW); WINDOWPLACEMENT windowPlacement = UnmanagedMethods.WINDOWPLACEMENT.Default; if (UnmanagedMethods.GetWindowPlacement(_hwnd, ref windowPlacement)) { //Toggle to make the styles stick UnmanagedMethods.ShowWindow(_hwnd, ShowWindowCommand.Hide); UnmanagedMethods.SetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_EXSTYLE, (uint)style); UnmanagedMethods.ShowWindow(_hwnd, windowPlacement.ShowCmd); } } public void CanResize(bool value) { if (value == _resizable) { return; } var style = (UnmanagedMethods.WindowStyles)UnmanagedMethods.GetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_STYLE); if (value) style |= UnmanagedMethods.WindowStyles.WS_SIZEFRAME; else style &= ~(UnmanagedMethods.WindowStyles.WS_SIZEFRAME); UnmanagedMethods.SetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_STYLE, (uint)style); _resizable = value; } } }
// * ************************************************************************** // * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C. // * This source code is subject to terms and conditions of the MIT License. // * A copy of the license can be found in the License.txt file // * at the root of this distribution. // * By using this source code in any fashion, you are agreeing to be bound by // * the terms of the MIT License. // * You must not remove this notice from this software. // * ************************************************************************** using System.ComponentModel; using FluentAssert; using FluentWebControls.Extensions; using FluentWebControls.Interfaces; using NUnit.Framework; using Rhino.Mocks; namespace FluentWebControls.Tests.Extensions { public class PagedListExtensionsTest { public class PagedListExtensionsTestBase<TPagedListInterface> where TPagedListInterface : class { protected TPagedListInterface _pagedList; [TearDown] public void AfterEachTest() { _pagedList.VerifyAllExpectations(); } [SetUp] public void BeforeEachTest() { _pagedList = MockRepository.GenerateMock<TPagedListInterface>(); } } [TestFixture] public class When_asked_to_OrderBy_with_a_sort_property : PagedListExtensionsTestBase<IPagedList> { [Test] public void Should_set_the_SortProperty_property_on_the_PagedList() { const string sortProperty = "Name"; _pagedList.Expect(x => x.SortProperty = sortProperty); var result = _pagedList.OrderBy(sortProperty); result.ShouldNotBeNull(); } } [TestFixture] public class When_asked_to_OrderBy_with_a_sort_property_and_sort_direction : PagedListExtensionsTestBase<IPagedList> { [Test] public void Should_set_the_SortDirection_property_on_the_PagedList() { const string sortProperty = "Name"; const string sortDirection = "Desc"; _pagedList.Expect(x => x.SortDirection = ListSortDirection.Descending); var result = _pagedList.OrderBy(sortProperty, sortDirection); result.ShouldNotBeNull(); } [Test] public void Should_set_the_SortProperty_property_on_the_PagedList() { const string sortProperty = "Name"; const string sortDirection = "Desc"; _pagedList.Expect(x => x.SortProperty = sortProperty); var result = _pagedList.OrderBy(sortProperty, sortDirection); result.ShouldNotBeNull(); } } [TestFixture] public class When_asked_to_OrderBy_with_a_sort_property_and_sort_direction_TFilter1_TFilter2_TFilter3_TReturn : PagedListExtensionsTestBase<IPagedList<int, int, int, int>> { [Test] public void Should_set_the_SortDirection_property_on_the_PagedList() { const string sortProperty = "Name"; const string sortDirection = "Desc"; _pagedList.Expect(x => x.SortDirection = ListSortDirection.Descending); IPagedList result = _pagedList.OrderBy(sortProperty, sortDirection); result.ShouldNotBeNull(); } [Test] public void Should_set_the_SortProperty_property_on_the_PagedList() { const string sortProperty = "Name"; const string sortDirection = "Desc"; _pagedList.Expect(x => x.SortProperty = sortProperty); IPagedList result = _pagedList.OrderBy(sortProperty, sortDirection); result.ShouldNotBeNull(); } } [TestFixture] public class When_asked_to_OrderBy_with_a_sort_property_and_sort_direction_TFilter1_TFilter2_TReturn : PagedListExtensionsTestBase<IPagedList<int, int, int>> { [Test] public void Should_set_the_SortDirection_property_on_the_PagedList() { const string sortProperty = "Name"; const string sortDirection = "Desc"; _pagedList.Expect(x => x.SortDirection = ListSortDirection.Descending); IPagedList result = _pagedList.OrderBy(sortProperty, sortDirection); result.ShouldNotBeNull(); } [Test] public void Should_set_the_SortProperty_property_on_the_PagedList() { const string sortProperty = "Name"; const string sortDirection = "Desc"; _pagedList.Expect(x => x.SortProperty = sortProperty); IPagedList result = _pagedList.OrderBy(sortProperty, sortDirection); result.ShouldNotBeNull(); } } [TestFixture] public class When_asked_to_OrderBy_with_a_sort_property_and_sort_direction_TFilter_TReturn : PagedListExtensionsTestBase<IPagedList<int, int>> { [Test] public void Should_set_the_SortDirection_property_on_the_PagedList() { const string sortProperty = "Name"; const string sortDirection = "Desc"; _pagedList.Expect(x => x.SortDirection = ListSortDirection.Descending); IPagedList result = _pagedList.OrderBy(sortProperty, sortDirection); result.ShouldNotBeNull(); } [Test] public void Should_set_the_SortProperty_property_on_the_PagedList() { const string sortProperty = "Name"; const string sortDirection = "Desc"; _pagedList.Expect(x => x.SortProperty = sortProperty); IPagedList result = _pagedList.OrderBy(sortProperty, sortDirection); result.ShouldNotBeNull(); } } [TestFixture] public class When_asked_to_OrderBy_with_a_sort_property_and_sort_direction_TReturn : PagedListExtensionsTestBase<IPagedList<int>> { [Test] public void Should_set_the_SortDirection_property_on_the_PagedList() { const string sortProperty = "Name"; const string sortDirection = "Desc"; _pagedList.Expect(x => x.SortDirection = ListSortDirection.Descending); IPagedList result = _pagedList.OrderBy(sortProperty, sortDirection); result.ShouldNotBeNull(); } [Test] public void Should_set_the_SortProperty_property_on_the_PagedList() { const string sortProperty = "Name"; const string sortDirection = "Desc"; _pagedList.Expect(x => x.SortProperty = sortProperty); IPagedList result = _pagedList.OrderBy(sortProperty, sortDirection); result.ShouldNotBeNull(); } } [TestFixture] public class When_asked_to_make_the_sort_direction_Ascending : PagedListExtensionsTestBase<IPagedList> { [Test] public void Should_set_the_SortDirection_property_on_the_PagedList() { _pagedList.Expect(x => x.SortDirection = ListSortDirection.Ascending); var result = _pagedList.Ascending(); result.ShouldNotBeNull(); } } [TestFixture] public class When_asked_to_make_the_sort_direction_Descending : PagedListExtensionsTestBase<IPagedList> { [Test] public void Should_set_the_SortDirection_property_on_the_PagedList() { _pagedList.Expect(x => x.SortDirection = ListSortDirection.Descending); var result = _pagedList.Descending(); result.ShouldNotBeNull(); } } [TestFixture] public class When_asked_to_set_the_page_number : PagedListExtensionsTestBase<IPagedList> { [Test] public void Should_set_the_PageNumber_property_on_the_PagedList() { const int pageNumber = 4; _pagedList.Expect(x => x.PageNumber = pageNumber); var result = _pagedList.PageNumber(pageNumber); result.ShouldNotBeNull(); } } [TestFixture] public class When_asked_to_set_the_page_number_and_page_size : PagedListExtensionsTestBase<IPagedList> { [Test] public void Should_set_the_PageNumber_property_on_the_PagedList() { const int pageNumber = 4; const int pageSize = 5; _pagedList.Expect(x => x.PageNumber = pageNumber); var result = _pagedList.Page(pageNumber, pageSize); result.ShouldNotBeNull(); } [Test] public void Should_set_the_PageSize_property_on_the_PagedList() { const int pageNumber = 4; const int pageSize = 5; _pagedList.Expect(x => x.PageSize = pageSize); var result = _pagedList.Page(pageNumber, pageSize); result.ShouldNotBeNull(); } } [TestFixture] public class When_asked_to_set_the_page_size : PagedListExtensionsTestBase<IPagedList> { [Test] public void Should_set_the_PageSize_property_on_the_PagedList() { const int pageSize = 5; _pagedList.Expect(x => x.PageSize = pageSize); var result = _pagedList.PageSize(pageSize); result.ShouldNotBeNull(); } } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; /* * AvaTax API Client Library * * (c) 2004-2019 Avalara, Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Genevieve Conty * @author Greg Hester * Swagger name: AvaTaxClient */ namespace Avalara.AvaTax.RestClient { /// <summary> /// Represents a declaration of nexus within a particular taxing jurisdiction. /// /// To create a nexus declaration for your company, you must first call the Definitions API `ListNexus` to obtain a /// list of Avalara-defined nexus. Once you have determined which nexus you wish to declare, you should customize /// only the user-selectable fields in this object. /// /// The user selectable fields for the nexus object are `companyId`, `effectiveDate`, `endDate`, `localNexusTypeId`, /// `taxId`, `nexusTypeId`, `hasPermanentEstablishment`, and `isSellerImporterOfRecord`. /// /// When calling `CreateNexus` or `UpdateNexus`, all values in your nexus object except for the user-selectable fields /// must match an Avalara-defined system nexus object. You can retrieve a list of Avalara-defined system nexus objects /// by calling `ListNexus`. If any data does not match, AvaTax may not recognize your nexus declaration. /// </summary> public class NexusModel { /// <summary> /// The unique ID number of this declaration of nexus. /// /// This field is defined automatically when you declare nexus. You do not need to provide a value for this field. /// </summary> public Int32? id { get; set; } /// <summary> /// The unique ID number of the company that declared nexus. /// /// This field is user-selectable and should be provided when creating or updating a nexus object. /// </summary> public Int32? companyId { get; set; } /// <summary> /// Name or ISO 3166 code identifying the country in which this company declared nexus. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public String country { get; set; } /// <summary> /// Name or ISO 3166 code identifying the region within the country. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public String region { get; set; } /// <summary> /// DEPRECATED - Date: 12/20/2017, Version: 18.1, Message: Please use jurisdictionTypeId instead. /// The jurisdiction type of the jurisdiction in which this company declared nexus. /// </summary> public JurisTypeId? jurisTypeId { get; set; } /// <summary> /// The type of the jurisdiction in which this company declared nexus. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public JurisdictionType? jurisdictionTypeId { get; set; } /// <summary> /// The code identifying the jurisdiction in which this company declared nexus. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public String jurisCode { get; set; } /// <summary> /// The common name of the jurisdiction in which this company declared nexus. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public String jurisName { get; set; } /// <summary> /// The date when this nexus began. If not known, set to null. /// /// This field is user-selectable and should be provided when creating or updating a nexus object. /// </summary> public DateTime? effectiveDate { get; set; } /// <summary> /// If this nexus will end or has ended on a specific date, set this to the date when this nexus ends. /// /// This field is user-selectable and should be provided when creating or updating a nexus object. /// </summary> public DateTime? endDate { get; set; } /// <summary> /// The short name of the jurisdiction. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public String shortName { get; set; } /// <summary> /// The signature code of the boundary region as defined by Avalara. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public String signatureCode { get; set; } /// <summary> /// The state assigned number of this jurisdiction. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public String stateAssignedNo { get; set; } /// <summary> /// The type of nexus that this company is declaring. /// /// If you are voluntarily declaring nexus in a jurisdiction, you should select `SalesOrSellersUseTax` for your /// nexus type option. This option allows you to calculate tax correctly whether you are selling in-state or /// shipping from an out-of-state location. /// /// If you are legally obligated to declare nexus due to physical presence or other sufficient nexus, you /// should select `SalesTax`. This indicates that, as a legal requirement, your company must always collect /// and remit full sales tax in this jurisdiction. /// /// If you are participating in the Streamlined Sales Tax program, your SST administrator will select nexus /// settings for you in all SST jurisdictions. Do not select any SST options by yourself. /// /// This field is user-selectable and should be provided when creating or updating a nexus object. /// </summary> public NexusTypeId? nexusTypeId { get; set; } /// <summary> /// Indicates whether this nexus is defined as origin or destination nexus. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public Sourcing? sourcing { get; set; } /// <summary> /// True if you are also declaring local nexus within this jurisdiction. /// Many U.S. states have options for declaring nexus in local jurisdictions as well as within the state. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public Boolean? hasLocalNexus { get; set; } /// <summary> /// If you are declaring local nexus within this jurisdiction, this indicates whether you are declaring only /// a specified list of local jurisdictions, all state-administered local jurisdictions, or all local jurisdictions. /// /// This field is user-selectable and should be provided when creating or updating a nexus object. /// </summary> public LocalNexusTypeId? localNexusTypeId { get; set; } /// <summary> /// Set this value to true if your company has a permanent establishment within this jurisdiction. /// /// This field is user-selectable and should be provided when creating or updating a nexus object. /// </summary> public Boolean? hasPermanentEstablishment { get; set; } /// <summary> /// Optional - the tax identification number under which you declared nexus. /// /// This field is user-selectable and should be provided when creating or updating a nexus object. /// </summary> public String taxId { get; set; } /// <summary> /// DEPRECATED - Date: 4/29/2017, Version: 19.4, Message: Please use isSSTActive instead. /// For the United States, this flag indicates whether this particular nexus falls within a U.S. State that participates /// in the Streamlined Sales Tax program. For countries other than the US, this flag is null. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public Boolean? streamlinedSalesTax { get; set; } /// <summary> /// For the United States, this flag indicates whether this particular nexus falls within a U.S. State that participates /// in the Streamlined Sales Tax program and if the account associated with the Nexus has an active AvaTaxCsp subscription. /// For countries other than the US, this flag is null. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public Boolean? isSSTActive { get; set; } /// <summary> /// The date when this record was created. /// /// This field is defined automatically when you declare nexus. You do not need to provide a value for this field. /// </summary> public DateTime? createdDate { get; set; } /// <summary> /// The User ID of the user who created this record. /// /// This field is defined automatically when you declare nexus. You do not need to provide a value for this field. /// </summary> public Int32? createdUserId { get; set; } /// <summary> /// The date/time when this record was last modified. /// /// This field is defined automatically when you declare nexus. You do not need to provide a value for this field. /// </summary> public DateTime? modifiedDate { get; set; } /// <summary> /// The user ID of the user who last modified this record. /// /// This field is defined automatically when you declare nexus. You do not need to provide a value for this field. /// </summary> public Int32? modifiedUserId { get; set; } /// <summary> /// The type group of nexus that this company is declaring /// Use [ListTaxTypeGroups](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListTaxTypeGroups/) API for a list of nexus tax type groups. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// NOTE: This optional field will trigger nexus subtype lookup when populated. When using make sure TaxTypeGroup matches corresponding NexusTaxTypeGroup /// </summary> public String taxTypeGroup { get; set; } /// <summary> /// The type of nexus that this company is declaring.Replaces NexusTypeId. /// Use [ListNexusTaxTypeGroups](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListNexusTaxTypeGroups/) API for a list of nexus tax type groups. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public String nexusTaxTypeGroup { get; set; } /// <summary> /// A unique ID number of the tax authority that is associated with this nexus. /// /// This field is defined by Avalara. All Avalara-defined fields must match an Avalara-defined nexus object found by calling `ListNexus`. /// </summary> public Int64? taxAuthorityId { get; set; } /// <summary> /// For nexus declarations at the country level, specifies whether this company is considered the importer of record in this nexus region. /// /// Some taxes only apply if the seller is the importer of record for a product. In cases where companies are working together to /// ship products, there may be mutual agreement as to which company is the entity designated as importer of record. The importer /// of record will then be the company designated to pay taxes marked as being obligated to the importer of record. /// /// Set this value to `true` to consider your company as the importer of record and collect these taxes. Leave this value as false /// or null and taxes will be calculated as if your company is not the importer of record. /// /// This value may also be set during each transaction API call. See `CreateTransaction()` for more information. /// /// This field is user-selectable and should be provided when creating or updating a nexus object. /// </summary> public Boolean? isSellerImporterOfRecord { get; set; } /// <summary> /// A description of corresponding tax type applied to the nexus. /// /// When a custom nexus is created, it'll have to be matched to a system nexus to be validated successfully. The matched system nexus has a /// field to describe the tax type applied to it, that field will be copied over to the nexus that is being created. /// /// This field is defined by Avalara. Its main purpose is to give a simple description of the tax type associated with the nexus so /// users have a better understanding of the nexus when it is displayed. /// </summary> public String taxName { get; set; } /// <summary> /// List of nexus parameters. /// </summary> public List<NexusParameterDetailModel> parameters { get; set; } /// <summary> /// Shows if system nexus records are associated with tax collection /// </summary> public Boolean? taxableNexus { get; set; } /// <summary> /// Convert this object to a JSON string of itself /// </summary> /// <returns>A JSON string of this object</returns> public override string ToString() { return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented }); } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonView.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- using System; using UnityEngine; using System.Reflection; using System.Collections.Generic; using ExitGames.Client.Photon; #if UNITY_EDITOR using UnityEditor; #endif public enum ViewSynchronization { Off, ReliableDeltaCompressed, Unreliable, UnreliableOnChange } public enum OnSerializeTransform { OnlyPosition, OnlyRotation, OnlyScale, PositionAndRotation, All } public enum OnSerializeRigidBody { OnlyVelocity, OnlyAngularVelocity, All } /// <summary> /// Options to define how Ownership Transfer is handled per PhotonView. /// </summary> /// <remarks> /// This setting affects how RequestOwnership and TransferOwnership work at runtime. /// </remarks> public enum OwnershipOption { /// <summary> /// Ownership is fixed. Instantiated objects stick with their creator, scene objects always belong to the Master Client. /// </summary> Fixed, /// <summary> /// Ownership can be taken away from the current owner who can't object. /// </summary> Takeover, /// <summary> /// Ownership can be requested with PhotonView.RequestOwnership but the current owner has to agree to give up ownership. /// </summary> /// <remarks>The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.</remarks> Request } /// <summary> /// PUN's NetworkView replacement class for networking. Use it like a NetworkView. /// </summary> /// \ingroup publicApi [AddComponentMenu("Photon Networking/Photon View &v")] public class PhotonView : Photon.MonoBehaviour { #if UNITY_EDITOR [ContextMenu("Open PUN Wizard")] void OpenPunWizard() { EditorApplication.ExecuteMenuItem("Window/Photon Unity Networking"); } #endif public int ownerId; public int group = 0; protected internal bool mixedModeIsReliable = false; /// <summary> /// Flag to check if ownership of this photonView was set during the lifecycle. Used for checking when joining late if event with mismatched owner and sender needs addressing. /// </summary> /// <value><c>true</c> if owner ship was transfered; otherwise, <c>false</c>.</value> public bool OwnerShipWasTransfered; // NOTE: this is now an integer because unity won't serialize short (needed for instantiation). we SEND only a short though! // NOTE: prefabs have a prefixBackup of -1. this is replaced with any currentLevelPrefix that's used at runtime. instantiated GOs get their prefix set pre-instantiation (so those are not -1 anymore) public int prefix { get { if (this.prefixBackup == -1 && PhotonNetwork.networkingPeer != null) { this.prefixBackup = PhotonNetwork.networkingPeer.currentLevelPrefix; } return this.prefixBackup; } set { this.prefixBackup = value; } } // this field is serialized by unity. that means it is copied when instantiating a persistent obj into the scene public int prefixBackup = -1; /// <summary> /// This is the instantiationData that was passed when calling PhotonNetwork.Instantiate* (if that was used to spawn this prefab) /// </summary> public object[] instantiationData { get { if (!this.didAwake) { // even though viewID and instantiationID are setup before the GO goes live, this data can't be set. as workaround: fetch it if needed this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId); } return this.instantiationDataField; } set { this.instantiationDataField = value; } } internal object[] instantiationDataField; /// <summary> /// For internal use only, don't use /// </summary> protected internal object[] lastOnSerializeDataSent = null; /// <summary> /// For internal use only, don't use /// </summary> protected internal object[] lastOnSerializeDataReceived = null; public Component observed; public ViewSynchronization synchronization; public OnSerializeTransform onSerializeTransformOption = OnSerializeTransform.PositionAndRotation; public OnSerializeRigidBody onSerializeRigidBodyOption = OnSerializeRigidBody.All; /// <summary>Defines if ownership of this PhotonView is fixed, can be requested or simply taken.</summary> /// <remarks> /// Note that you can't edit this value at runtime. /// The options are described in enum OwnershipOption. /// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request. /// </remarks> public OwnershipOption ownershipTransfer = OwnershipOption.Fixed; public List<Component> ObservedComponents; Dictionary<Component, MethodInfo> m_OnSerializeMethodInfos = new Dictionary<Component, MethodInfo>(3); #if UNITY_EDITOR // Suppressing compiler warning "this variable is never used". Only used in the CustomEditor, only in Editor #pragma warning disable 0414 [SerializeField] bool ObservedComponentsFoldoutOpen = true; #pragma warning restore 0414 #endif [SerializeField] private int viewIdField = 0; /// <summary> /// The ID of the PhotonView. Identifies it in a networked game (per room). /// </summary> /// <remarks>See: [Network Instantiation](@ref instantiateManual)</remarks> public int viewID { get { return this.viewIdField; } set { // if ID was 0 for an awakened PhotonView, the view should add itself into the networkingPeer.photonViewList after setup bool viewMustRegister = this.didAwake && this.viewIdField == 0; // TODO: decide if a viewID can be changed once it wasn't 0. most likely that is not a good idea // check if this view is in networkingPeer.photonViewList and UPDATE said list (so we don't keep the old viewID with a reference to this object) // PhotonNetwork.networkingPeer.RemovePhotonView(this, true); this.ownerId = value / PhotonNetwork.MAX_VIEW_IDS; this.viewIdField = value; if (viewMustRegister) { PhotonNetwork.networkingPeer.RegisterPhotonView(this); } //Debug.Log("Set viewID: " + value + " -> owner: " + this.ownerId + " subId: " + this.subId); } } public int instantiationId; // if the view was instantiated with a GO, this GO has a instantiationID (first view's viewID) /// <summary>True if the PhotonView was loaded with the scene (game object) or instantiated with InstantiateSceneObject.</summary> /// <remarks> /// Scene objects are not owned by a particular player but belong to the scene. Thus they don't get destroyed when their /// creator leaves the game and the current Master Client can control them (whoever that is). /// The ownerId is 0 (player IDs are 1 and up). /// </remarks> public bool isSceneView { get { return this.CreatorActorNr == 0; } } /// <summary> /// The owner of a PhotonView is the player who created the GameObject with that view. Objects in the scene don't have an owner. /// </summary> /// <remarks> /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// /// Ownership can be transferred to another player with PhotonView.TransferOwnership or any player can request /// ownership by calling the PhotonView's RequestOwnership method. /// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request. /// </remarks> public PhotonPlayer owner { get { return PhotonPlayer.Find(this.ownerId); } } public int OwnerActorNr { get { return this.ownerId; } } public bool isOwnerActive { get { return this.ownerId != 0 && PhotonNetwork.networkingPeer.mActors.ContainsKey(this.ownerId); } } public int CreatorActorNr { get { return this.viewIdField / PhotonNetwork.MAX_VIEW_IDS; } } /// <summary> /// True if the PhotonView is "mine" and can be controlled by this client. /// </summary> /// <remarks> /// PUN has an ownership concept that defines who can control and destroy each PhotonView. /// True in case the owner matches the local PhotonPlayer. /// True if this is a scene photonview on the Master client. /// </remarks> public bool isMine { get { return (this.ownerId == PhotonNetwork.player.ID) || (!this.isOwnerActive && PhotonNetwork.isMasterClient); } } protected internal bool didAwake; [SerializeField] protected internal bool isRuntimeInstantiated; protected internal bool removedFromLocalViewList; internal MonoBehaviour[] RpcMonoBehaviours; private MethodInfo OnSerializeMethodInfo; private bool failedToFindOnSerialize; /// <summary>Called by Unity on start of the application and does a setup the PhotonView.</summary> protected internal void Awake() { if (this.viewID != 0) { // registration might be too late when some script (on this GO) searches this view BUT GetPhotonView() can search ALL in that case PhotonNetwork.networkingPeer.RegisterPhotonView(this); this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId); } this.didAwake = true; } /// <summary> /// Depending on the PhotonView's ownershipTransfer setting, any client can request to become owner of the PhotonView. /// </summary> /// <remarks> /// Requesting ownership can give you control over a PhotonView, if the ownershipTransfer setting allows that. /// The current owner might have to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request. /// /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// </remarks> public void RequestOwnership() { PhotonNetwork.networkingPeer.RequestOwnership(this.viewID, this.ownerId); } /// <summary> /// Transfers the ownership of this PhotonView (and GameObject) to another player. /// </summary> /// <remarks> /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// </remarks> public void TransferOwnership(PhotonPlayer newOwner) { this.TransferOwnership(newOwner.ID); } /// <summary> /// Transfers the ownership of this PhotonView (and GameObject) to another player. /// </summary> /// <remarks> /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// </remarks> public void TransferOwnership(int newOwnerId) { PhotonNetwork.networkingPeer.TransferOwnership(this.viewID, newOwnerId); this.ownerId = newOwnerId; // immediately switch ownership locally, to avoid more updates sent from this client. } protected internal void OnDestroy() { if (!this.removedFromLocalViewList) { bool wasInList = PhotonNetwork.networkingPeer.LocalCleanPhotonView(this); bool loading = false; #if !UNITY_5 || UNITY_5_0 || UNITY_5_1 loading = Application.isLoadingLevel; #endif if (wasInList && !loading && this.instantiationId > 0 && !PhotonHandler.AppQuits && PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log("PUN-instantiated '" + this.gameObject.name + "' got destroyed by engine. This is OK when loading levels. Otherwise use: PhotonNetwork.Destroy()."); } } } public void SerializeView(PhotonStream stream, PhotonMessageInfo info) { SerializeComponent(this.observed, stream, info); if (this.ObservedComponents != null && this.ObservedComponents.Count > 0) { for (int i = 0; i < this.ObservedComponents.Count; ++i) { SerializeComponent(this.ObservedComponents[i], stream, info); } } } public void DeserializeView(PhotonStream stream, PhotonMessageInfo info) { DeserializeComponent(this.observed, stream, info); if (this.ObservedComponents != null && this.ObservedComponents.Count > 0) { for (int i = 0; i < this.ObservedComponents.Count; ++i) { DeserializeComponent(this.ObservedComponents[i], stream, info); } } } protected internal void DeserializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info) { if (component == null) { return; } // Use incoming data according to observed type if (component is MonoBehaviour) { ExecuteComponentOnSerialize(component, stream, info); } else if (component is Transform) { Transform trans = (Transform) component; switch (this.onSerializeTransformOption) { case OnSerializeTransform.All: trans.localPosition = (Vector3) stream.ReceiveNext(); trans.localRotation = (Quaternion) stream.ReceiveNext(); trans.localScale = (Vector3) stream.ReceiveNext(); break; case OnSerializeTransform.OnlyPosition: trans.localPosition = (Vector3) stream.ReceiveNext(); break; case OnSerializeTransform.OnlyRotation: trans.localRotation = (Quaternion) stream.ReceiveNext(); break; case OnSerializeTransform.OnlyScale: trans.localScale = (Vector3) stream.ReceiveNext(); break; case OnSerializeTransform.PositionAndRotation: trans.localPosition = (Vector3) stream.ReceiveNext(); trans.localRotation = (Quaternion) stream.ReceiveNext(); break; } } else if (component is Rigidbody) { Rigidbody rigidB = (Rigidbody) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: rigidB.velocity = (Vector3) stream.ReceiveNext(); rigidB.angularVelocity = (Vector3) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyAngularVelocity: rigidB.angularVelocity = (Vector3) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyVelocity: rigidB.velocity = (Vector3) stream.ReceiveNext(); break; } } else if (component is Rigidbody2D) { Rigidbody2D rigidB = (Rigidbody2D) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: rigidB.velocity = (Vector2) stream.ReceiveNext(); rigidB.angularVelocity = (float) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyAngularVelocity: rigidB.angularVelocity = (float) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyVelocity: rigidB.velocity = (Vector2) stream.ReceiveNext(); break; } } else { Debug.LogError("Type of observed is unknown when receiving."); } } protected internal void SerializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info) { if (component == null) { return; } if (component is MonoBehaviour) { ExecuteComponentOnSerialize(component, stream, info); } else if (component is Transform) { Transform trans = (Transform) component; switch (this.onSerializeTransformOption) { case OnSerializeTransform.All: stream.SendNext(trans.localPosition); stream.SendNext(trans.localRotation); stream.SendNext(trans.localScale); break; case OnSerializeTransform.OnlyPosition: stream.SendNext(trans.localPosition); break; case OnSerializeTransform.OnlyRotation: stream.SendNext(trans.localRotation); break; case OnSerializeTransform.OnlyScale: stream.SendNext(trans.localScale); break; case OnSerializeTransform.PositionAndRotation: stream.SendNext(trans.localPosition); stream.SendNext(trans.localRotation); break; } } else if (component is Rigidbody) { Rigidbody rigidB = (Rigidbody) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: stream.SendNext(rigidB.velocity); stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyAngularVelocity: stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyVelocity: stream.SendNext(rigidB.velocity); break; } } else if (component is Rigidbody2D) { Rigidbody2D rigidB = (Rigidbody2D) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: stream.SendNext(rigidB.velocity); stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyAngularVelocity: stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyVelocity: stream.SendNext(rigidB.velocity); break; } } else { Debug.LogError("Observed type is not serializable: " + component.GetType()); } } protected internal void ExecuteComponentOnSerialize(Component component, PhotonStream stream, PhotonMessageInfo info) { IPunObservable observable = component as IPunObservable; if (observable != null) { observable.OnPhotonSerializeView(stream, info); } else if (component != null) { MethodInfo method = null; bool found = this.m_OnSerializeMethodInfos.TryGetValue(component, out method); if (!found) { bool foundMethod = NetworkingPeer.GetMethod(component as MonoBehaviour, PhotonNetworkingMessage.OnPhotonSerializeView.ToString(), out method); if (foundMethod == false) { Debug.LogError("The observed monobehaviour (" + component.name + ") of this PhotonView does not implement OnPhotonSerializeView()!"); method = null; } this.m_OnSerializeMethodInfos.Add(component, method); } if (method != null) { method.Invoke(component, new object[] {stream, info}); } } } /// <summary> /// Can be used to refesh the list of MonoBehaviours on this GameObject while PhotonNetwork.UseRpcMonoBehaviourCache is true. /// </summary> /// <remarks> /// Set PhotonNetwork.UseRpcMonoBehaviourCache to true to enable the caching. /// Uses this.GetComponents<MonoBehaviour>() to get a list of MonoBehaviours to call RPCs on (potentially). /// /// While PhotonNetwork.UseRpcMonoBehaviourCache is false, this method has no effect, /// because the list is refreshed when a RPC gets called. /// </remarks> public void RefreshRpcMonoBehaviourCache() { this.RpcMonoBehaviours = this.GetComponents<MonoBehaviour>(); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// RPC calls can target "All" or the "Others". /// Usually, the target "All" gets executed locally immediately after sending the RPC. /// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> /// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param> /// <param name="target">The group of targets and the way the RPC gets sent.</param> /// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RPC(string methodName, PhotonTargets target, params object[] parameters) { PhotonNetwork.RPC(this, methodName, target, false, parameters); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// RPC calls can target "All" or the "Others". /// Usually, the target "All" gets executed locally immediately after sending the RPC. /// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> ///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param> ///<param name="target">The group of targets and the way the RPC gets sent.</param> ///<param name="encrypt"> </param> ///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RpcSecure(string methodName, PhotonTargets target, bool encrypt, params object[] parameters) { PhotonNetwork.RPC(this, methodName, target, encrypt, parameters); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// This method allows you to make an RPC calls on a specific player's client. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> /// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param> /// <param name="targetPlayer">The group of targets and the way the RPC gets sent.</param> /// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RPC(string methodName, PhotonPlayer targetPlayer, params object[] parameters) { PhotonNetwork.RPC(this, methodName, targetPlayer, false, parameters); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// This method allows you to make an RPC calls on a specific player's client. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> ///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param> ///<param name="targetPlayer">The group of targets and the way the RPC gets sent.</param> ///<param name="encrypt"> </param> ///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RpcSecure(string methodName, PhotonPlayer targetPlayer, bool encrypt, params object[] parameters) { PhotonNetwork.RPC(this, methodName, targetPlayer, encrypt, parameters); } public static PhotonView Get(Component component) { return component.GetComponent<PhotonView>(); } public static PhotonView Get(GameObject gameObj) { return gameObj.GetComponent<PhotonView>(); } public static PhotonView Find(int viewID) { return PhotonNetwork.networkingPeer.GetPhotonView(viewID); } public override string ToString() { return string.Format("View ({3}){0} on {1} {2}", this.viewID, (this.gameObject != null) ? this.gameObject.name : "GO==null", (this.isSceneView) ? "(scene)" : string.Empty, this.prefix); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Security.Permissions; using System.Diagnostics; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// A hashtable wrapper that defers copying until the data is written. /// </summary> internal sealed class CopyOnWriteHashtable : IDictionary, ICloneable { // Either of these can act as the true backing writeableData. private Hashtable writeableData = null; // These are references to someone else's backing writeableData. private Hashtable readonlyData = null; // This is used to synchronize access to the readonlyData and writeableData fields. private object sharedLock; // Carry around the StringComparer when possible to make Clear less expensive. StringComparer stringComparer = null; #region Construct /// <summary> /// Construct as a traditional data-backed hashtable. /// </summary> /// <param name="stringComparer"></param> internal CopyOnWriteHashtable(StringComparer stringComparer) : this(0, stringComparer) { this.sharedLock = new object(); } /// <summary> /// Construct with specified initial capacity. If the capacity is known /// up front, specifying it avoids unnecessary rehashing operations /// </summary> internal CopyOnWriteHashtable(int capacity, StringComparer stringComparer) { ErrorUtilities.VerifyThrowArgumentNull(stringComparer, "stringComparer"); this.sharedLock = new object(); if (capacity == 0) { // Actually 0 tells the Hashtable to use its default, but let's not rely on that writeableData = new Hashtable(stringComparer); } else { writeableData = new Hashtable(capacity, stringComparer); } readonlyData = null; this.stringComparer = stringComparer; } /// <summary> /// Construct over an IDictionary instance. /// </summary> /// <param name="dictionary"></param> /// <param name="stringComparer">The string comparer to use.</param> internal CopyOnWriteHashtable(IDictionary dictionary, StringComparer stringComparer) { ErrorUtilities.VerifyThrowArgumentNull(dictionary, "dictionary"); ErrorUtilities.VerifyThrowArgumentNull(stringComparer, "stringComparer"); this.sharedLock = new object(); CopyOnWriteHashtable source = dictionary as CopyOnWriteHashtable; if (source != null) { if (source.stringComparer.GetHashCode() == stringComparer.GetHashCode()) { // If we're copying another CopyOnWriteHashtable then we can defer the clone until later. ConstructFrom(source); return; } else { // Technically, it would be legal to fall through here and let a new hashtable be constructed. // However, Engine is supposed to use consistent case comparisons everywhere and so, for us, // this means a bug in the engine code somewhere. throw new InternalErrorException("Bug: Changing the case-sensitiveness of a copied hash-table."); } } // Can't defer this because we don't control what gets written to the dictionary exogenously. writeableData = new Hashtable(dictionary, stringComparer); readonlyData = null; this.stringComparer = stringComparer; } /// <summary> /// Construct a shallow copy over another instance of this class. /// </summary> /// <param name="that"></param> private CopyOnWriteHashtable(CopyOnWriteHashtable that) { this.sharedLock = new object(); ConstructFrom(that); } /// <summary> /// Implementation of construction logic. /// </summary> /// <param name="that"></param> private void ConstructFrom(CopyOnWriteHashtable that) { lock (that.sharedLock) { this.writeableData = null; // If the source it was writeable, need to transform it into // read-only because we don't want subsequent writes to bleed through. if (that.writeableData != null) { that.readonlyData = that.writeableData; that.writeableData = null; } this.readonlyData = that.readonlyData; this.stringComparer = that.stringComparer; } } /// <summary> /// Whether or not this CopyOnWriteHashtable is currently a shallow or deep copy. /// This state can change from true->false when this hashtable is written to. /// </summary> internal bool IsShallowCopy { get { return this.readonlyData != null; } } #endregion #region Pass-through Hashtable methods. public bool Contains(Object key) {return ReadOperation.Contains(key);} public void Add(Object key, Object value) {WriteOperation.Add(key, value);} public void Clear() { lock (sharedLock) { ErrorUtilities.VerifyThrow(stringComparer != null, "Should have a valid string comparer."); writeableData = new Hashtable(stringComparer); readonlyData = null; } } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)ReadOperation).GetEnumerator(); } public IDictionaryEnumerator GetEnumerator() {return ReadOperation.GetEnumerator();} public void Remove(Object key) {WriteOperation.Remove(key);} public bool IsFixedSize { get { return ReadOperation.IsFixedSize; }} public bool IsReadOnly {get {return ReadOperation.IsFixedSize;}} public ICollection Keys {get {return ReadOperation.Keys;}} public ICollection Values {get {return ReadOperation.Values;}} public void CopyTo(Array array, int arrayIndex) { ReadOperation.CopyTo(array, arrayIndex); } public int Count{get { return ReadOperation.Count; }} public bool IsSynchronized {get { return ReadOperation.IsSynchronized; }} public Object SyncRoot {get { return ReadOperation.SyncRoot; }} public bool ContainsKey(Object key) {return ReadOperation.Contains(key);} public Object this[Object key] { get { return ReadOperation[key]; } set { lock (sharedLock) { if(writeableData != null) { writeableData[key] = value; } else { // Setting to exactly the same value? Skip the the Clone in this case. if (readonlyData[key] != value || (!readonlyData.ContainsKey(key))) { WriteOperation[key] = value; } } } } } #endregion /// <summary> /// Clone this. /// </summary> /// <returns></returns> public Object Clone() { return new CopyOnWriteHashtable(this); } /// <summary> /// Returns a hashtable instance for reading from. /// </summary> private Hashtable ReadOperation { get { lock (sharedLock) { if (readonlyData != null) { return readonlyData; } return writeableData; } } } /// <summary> /// Returns a hashtable instance for writting to. /// Clones the readonly hashtable if necessary to create a writeable version. /// </summary> private Hashtable WriteOperation { get { lock (sharedLock) { if (writeableData == null) { writeableData = (Hashtable)readonlyData.Clone(); readonlyData = null; } return writeableData; } } } } }
////////////////////////////////////////////////////////////////////// // // WordXmlSerializer.cs // // Provides a class to support reading and writing Word 2003 XML // files. // ////////////////////////////////////////////////////////////////////// namespace DocumentSerialization { #region Namespaces. using System; using System.IO; using System.Diagnostics; using System.Reflection; using System.Security.Policy; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; using System.Windows; using System.Windows.Documents; using System.Windows.Controls; using System.Windows.Media; #endregion Namespaces. /// <summary> /// Reads and writes WordXML files, interoperating with TextContainer /// instances. /// </summary> static class WordXmlSerializer { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public methods. /// <summary> /// Determines whether the specified file is a WordML file. /// </summary> /// <param name='filename'>Name of file to inspect.</param> /// <returns>true if the specified file name is WordML; false otherwise.</returns> /// <remarks> /// This method identifies WordML files as XML files that have /// a Word.Document prog-id in a mso-application processing /// instruction in its leading nodes. /// </remarks> public static bool IsFileWordML(string filename) { const bool detectEncodingTrue = true; if (filename == null) { throw new ArgumentNullException(nameof(filename)); } try { using (TextReader textReader = new StreamReader(filename, detectEncodingTrue)) using (XmlTextReader xmlReader = new XmlTextReader(textReader)) { while (xmlReader.Read()) { switch (xmlReader.NodeType) { case XmlNodeType.ProcessingInstruction: if (xmlReader.Name == "mso-application") { return xmlReader.Value.Contains("Word.Document"); } break; case XmlNodeType.Comment: case XmlNodeType.DocumentType: case XmlNodeType.Notation: case XmlNodeType.XmlDeclaration: case XmlNodeType.Whitespace: continue; default: return false; } } return false; } } catch(XmlException) { return false; } } /// <summary> /// Saves the container of the specified range into the given /// file. /// </summary> /// <param name='filename'>Name of file to save to.</param> /// <param name='range'>Range from container to save.</param> public static void SaveToFile(string filename, TextPointer start, TextPointer end) { if (filename == null) { throw new ArgumentNullException(nameof(filename)); } if (start == null) { throw new ArgumentNullException(nameof(start)); } if (end == null) { throw new ArgumentNullException(nameof(end)); } // Do a programmatic serialization of the container. using (XmlTextWriter writer = new XmlTextWriter(filename, System.Text.Encoding.Unicode)) { // Set up formatting options for debugability. writer.Formatting = Formatting.Indented; writer.Indentation = 2; writer.IndentChar = ' '; new WordXmlWriter().Write(start, end, writer); } } /// <summary> /// Loads the specified file into the given container. /// </summary> /// <param name='filename'>Name of file to load content from..</param> /// <param name='position'>Position to load content into.</param> public static void LoadFromFile(string filename, TextPointer position) { const bool detectEncodingTrue = true; if (filename == null) { throw new ArgumentNullException(nameof(filename)); } if (position == null) { throw new ArgumentNullException(nameof(position)); } using (TextReader textReader = new StreamReader(filename, detectEncodingTrue)) using (XmlTextReader xmlReader = new XmlTextReader(textReader)) { new WordXmlReader().Read(xmlReader, position); } } #endregion Public methods. //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ //------------------------------------------------------ // // Internal Constants // //------------------------------------------------------ #region Internal constants. #region WordXML element constants. /// <summary> /// WordXML element name to indicate the font used by Word to /// display text. This saves consumers from having to select /// one of of ascii, fareast, h-ansi or cs. /// </summary> internal const string WordAuxiliaryFontTag = "wx:font"; /// <summary>WordXML element name to indicate bold formatting.</summary> internal const string WordBoldTag = "w:b"; /// <summary> /// WordXML element name to indicate a break in the document (eg: /// a line break). /// </summary> internal const string WordBreakTag = "w:br"; /// <summary>WordXML element name to indicate text color.</summary> internal const string WordColorTag = "w:color"; /// <summary>WordXML element name to indicate font size usage.</summary> internal const string WordFontSizeTag = "w:sz"; /// <summary>WordXML element name to indicate italic formatting.</summary> internal const string WordItalicTag = "w:i"; /// <summary>WordXML element name to indicate paragraph justification.</summary> internal const string WordJustificationTag = "w:jc"; /// <summary>WordXML element name to indicate a resource name (eg: style name).</summary> internal const string WordNameTag = "w:name"; /// <summary> /// WordXML element name to indicate a set of paragraph properties. /// </summary> internal const string WordParagraphPropertiesTag = "w:pPr"; /// <summary>WordXML element name to indicate a paragraph.</summary> internal const string WordParagraphTag = "w:p"; /// <summary> /// WordXML element name to indicate a set of range properties. /// </summary> internal const string WordRangePropertiesTag = "w:rPr"; /// <summary>WordXML element name to indicate a range.</summary> internal const string WordRangeTag = "w:r"; /// <summary>WordXML element name to indicate a style definition.</summary> internal const string WordStyleTag = "w:style"; /// <summary> /// WordXML element name to indicate text with similar formatting. /// </summary> internal const string WordTextTag = "w:t"; #endregion WordXML element constants. #region WordXML attribute constants. /// <summary>WordXML attribute value to indicate a default value.</summary> internal const string WordAuto = "auto"; /// <summary>WordXML attribute name to indicate the value for an element.</summary> internal const string WordAuxiliaryValue = "wx:val"; /// <summary>WordXML attribute value to indicate centered content.</summary> internal const string WordCenter = "center"; /// <summary>WordXML attribute value to indicate a style of character type.</summary> internal const string WordCharacter = "character"; /// <summary>WordXML attribute name to indicate whether an element is the default.</summary> internal const string WordDefault = "w:default"; /// <summary>WordXML attribute value to indicate left-aligned content.</summary> internal const string WordLeft = "left"; /// <summary>WordXML attribute value to indicate a style of list type.</summary> internal const string WordList = "list"; /// <summary>WordXML attribute value to indicate a property is unused.</summary> internal const string WordOff = "off"; /// <summary>WordXML attribute value to indicate a property is used.</summary> internal const string WordOn = "on"; /// <summary>WordXML attribute value to indicate a style o fparagraph type.</summary> internal const string WordParagraph = "paragraph"; /// <summary>WordXML attribute value to indicate right-aligned content.</summary> internal const string WordRight = "right"; /// <summary>WordXML attribute name to indicate the style ID for an style.</summary> internal const string WordStyleId = "w:styleId"; /// <summary>WordXML attribute value to indicate a style of table type.</summary> internal const string WordTable = "table"; /// <summary>WordXML attribute name to indicate the type of a style.</summary> internal const string WordType = "w:type"; /// <summary>WordXML attribute name to indicate the value for an element.</summary> internal const string WordValue = "w:val"; #endregion WordXML attribute constants. #endregion Internal constants. //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ } }
using Common; using Common.fx; using fxcore2; using System; using System.Collections.Generic; using System.Threading; namespace fxCoreLink { enum Action { DeleteOrder, SetStopLimit, EditOrder } public class OCOTrade : IOCOTrade { Logger log = Logger.LogManager("OCOTrade"); public OCOTrade(O2GSession session, Display display) { this.session = session; this.display = display; } private Display display; private O2GSession session; double bidRate; double askRate; int trailStepStop = 1; private Dictionary<string, Action> mActions = new Dictionary<string, Action>(); ELSResponseListener responseListener; public string tradeOCO(string accountId, string offerId, double pointSize, string uniqueId, string pair, int amount, int entryPips, int stopPips, int limitPips, double bid, double ask) { getOfferRate(session, pair, entryPips, bid, ask, pointSize); responseListener = new ELSResponseListener(session, display); session.subscribeResponse(responseListener); int mAmount = amount * 1000; createOCO(accountId, pair, mAmount, entryPips, stopPips, limitPips, uniqueId, offerId); session.unsubscribeResponse(responseListener); return "";// orderId; } /** Create OCO orders. */ public void createOCO(string accountId, string pair, int amount, int entryPips, int stopPips, int limitPips, string uniqueId, string offerId) { string orderId = ""; O2GRequestFactory factory = session.getRequestFactory(); O2GValueMap mainValueMap = factory.createValueMap(); mainValueMap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOCO); { // buy entry O2GValueMap valuemap = factory.createValueMap(); valuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.StopEntry); valuemap.setString(O2GRequestParamsEnum.AccountID, accountId); // The identifier of the account the order should be placed for. valuemap.setString(O2GRequestParamsEnum.OfferID, offerId); // The identifier of the instrument the order should be placed for. valuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Buy); // The order direction (Constants.Buy for buy, Constants.Sell for sell) valuemap.setDouble(O2GRequestParamsEnum.Rate, askRate); // The dRate at which the order must be filled (below current dRate for Buy, above current dRate for Sell) valuemap.setInt(O2GRequestParamsEnum.Amount, amount); // The quantity of the instrument to be bought or sold. valuemap.setString(O2GRequestParamsEnum.CustomID, "OCOBuy" + uniqueId); valuemap.setString(O2GRequestParamsEnum.PegTypeStop, Constants.Peg.FromClose); valuemap.setInt(O2GRequestParamsEnum.PegOffsetStop, -stopPips); valuemap.setInt(O2GRequestParamsEnum.TrailStepStop, trailStepStop); if (limitPips > 0) { valuemap.setString(O2GRequestParamsEnum.PegTypeLimit, Constants.Peg.FromClose); valuemap.setInt(O2GRequestParamsEnum.PegOffsetLimit, limitPips); } mainValueMap.appendChild(valuemap); } { // sell entry O2GValueMap valuemap = factory.createValueMap(); valuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.StopEntry); valuemap.setString(O2GRequestParamsEnum.AccountID, accountId); // The identifier of the account the order should be placed for. valuemap.setString(O2GRequestParamsEnum.OfferID, offerId); // The identifier of the instrument the order should be placed for. valuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Sell); // The order direction (Constants.Buy for buy, Constants.Sell for sell) valuemap.setDouble(O2GRequestParamsEnum.Rate, bidRate); // The dRate at which the order must be filled (below current dRate for Buy, above current dRate for Sell) valuemap.setInt(O2GRequestParamsEnum.Amount, amount); // The quantity of the instrument to be bought or sold. valuemap.setString(O2GRequestParamsEnum.CustomID, "OCOSell"+uniqueId); valuemap.setString(O2GRequestParamsEnum.PegTypeStop, Constants.Peg.FromClose); valuemap.setInt(O2GRequestParamsEnum.PegOffsetStop, stopPips); valuemap.setInt(O2GRequestParamsEnum.TrailStepStop, trailStepStop); if (limitPips > 0) { valuemap.setString(O2GRequestParamsEnum.PegTypeLimit, Constants.Peg.FromClose); valuemap.setInt(O2GRequestParamsEnum.PegOffsetLimit, -limitPips); } mainValueMap.appendChild(valuemap); } O2GRequest request = factory.createOrderRequest(mainValueMap); session.sendRequest(request); responseListener.manualEvent.WaitOne(); if (!responseListener.Error) { log.debug("Created OCO, OrderID={0} at {1}", responseListener.OrderId, Util.getTimeNowFormatted()); orderId = responseListener.OrderId; } else log.debug("Failed to create OCO" + responseListener.ErrorDescription + "; " + factory.getLastError() ); } // Get current prices and calculate order price private void getOfferRate(O2GSession session, string sInstrument, int entryPips, double bid, double ask, double pointSize) { double dBid = bid; double dAsk = ask; double dPointSize = pointSize; try { bidRate = dBid - entryPips * dPointSize; askRate = dAsk + entryPips * dPointSize; } catch (Exception e) { log.debug("Exception in GetOfferRate().\n\t " + e.Message); } } } class OCOResponseListener : IO2GResponseListener, IDisposable { Logger log = Logger.LogManager("OCOResponseListener"); public OCOResponseListener(O2GSession session, Display display) { this.session = session; this.display = display; manualEvent = new ManualResetEvent(true); } private Display display; private O2GSession session; //private object mEvent = new object(); public ManualResetEvent manualEvent; private int iNewOCOOrders = 0; // number of unprocessed requests (add order to new OCO). Continue after all requests are responded. private string sContingencyID = "n/a"; // Contingency ID for the new order we just created //request IDs private List<string> lstCreateNewOCORequestID = new List<string>(); // RequestIDs to create new OCO - in this example several orders added to form new OCO private string sJoinExistingOCORequestID = ""; // RequestID to join existing OCO - in this example just one order joins existing OCO private string sRemoveFromOCORequestID = ""; // RequestID to remove order from OCO - in this example just one order is removed from OCO private string sOrdersTableRefreshRequestID = ""; // requestID to refresh Orders table private List<string> lstOrdersInNewOCO; // order IDs of orders added to new OCO order #region IO2GResponseListener Members public string getOrderId() { return sContingencyID; } public void onRequestCompleted(string requestId, O2GResponse response) { bool bLetGo = false; // do not have to wait if this value is true if (iNewOCOOrders > 0) { foreach (string sCreateNewOCORequestID in lstCreateNewOCORequestID) { if (requestId.Equals(sCreateNewOCORequestID)) { display.logger("Order added to new OCO"); iNewOCOOrders--; break; } } if (iNewOCOOrders == 0) bLetGo = true; } else if (requestId.Equals(sRemoveFromOCORequestID)) { display.logger("Order removed from OCO"); bLetGo = true; } else if (requestId.Equals(sJoinExistingOCORequestID)) { display.logger("Order added to existing OCO"); bLetGo = true; } else if (requestId.Equals(sOrdersTableRefreshRequestID)) { sContingencyID = GetContingencyID(response); bLetGo = true; } if (bLetGo) { manualEvent.Set(); } CtrlTimer.getInstance().stopTimer("OCORequest"); } public void onRequestFailed(string requestId, string error) { bool bLetGo = false; if (iNewOCOOrders > 0) { foreach (string sCreateNewOCORequestID in lstCreateNewOCORequestID) { if (requestId.Equals(sCreateNewOCORequestID)) { display.logger("Cannot add order to new OCO, error=" + error); iNewOCOOrders--; break; } } if (iNewOCOOrders == 0) bLetGo = true; } else if (requestId.Equals(sJoinExistingOCORequestID)) { display.logger("Cannot join existing OCO, error=" + error); bLetGo = true; } else if (requestId.Equals(sRemoveFromOCORequestID)) { display.logger("Cannot remove from OCO, error=" + error); bLetGo = true; } else if (requestId.Equals(sOrdersTableRefreshRequestID)) { display.logger("Cannot get refreshed Orders table, error=" + error); bLetGo = true; } if (bLetGo) { manualEvent.Set(); } CtrlTimer.getInstance().stopTimer("OCORequest"); } public void onTablesUpdates(O2GResponse data) { } #endregion public void RemoveFromOCO(string sAccountID, string sOrderRemoveFromOCO) { O2GRequestFactory factory = session.getRequestFactory(); O2GValueMap valuemap = factory.createValueMap(); valuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.RemoveFromContingencyGroup); O2GValueMap valueRemove = createValueMapForExistingOrder(sOrderRemoveFromOCO, sAccountID); valueRemove.setString(O2GRequestParamsEnum.Command, Constants.Commands.RemoveFromContingencyGroup); valuemap.appendChild(valueRemove); // create request from valueMap O2GRequest request = factory.createOrderRequest(valuemap); if (request != null) { log.debug("Remove order {0} from OCO", sOrderRemoveFromOCO); sRemoveFromOCORequestID = request.getChildRequest(0).RequestID; // just one order to remove in this example session.sendRequest(request); manualEvent.Reset(); manualEvent.WaitOne(); } else { log.debug("Request in \'RemoveFromOCO\' is null, most likely some arguments are mssing or incorrect"); } } public void JoinExistingOCO(string sAccountID, string sOrderJoinToOCO) { if (String.IsNullOrEmpty(sContingencyID)) { log.debug("Cannot join existing OCO - ContingencyID is missing"); return; } O2GRequestFactory factory = session.getRequestFactory(); O2GValueMap valuemap = factory.createValueMap(); valuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.JoinToExistingContingencyGroup); valuemap.setInt(O2GRequestParamsEnum.ContingencyGroupType, 1); // 1 means OCO valuemap.setString(O2GRequestParamsEnum.ContingencyID, sContingencyID); valuemap.appendChild(createValueMapForExistingOrder(sOrderJoinToOCO, sAccountID)); // create request from valueMap O2GRequest request = factory.createOrderRequest(valuemap); if (request != null) { log.debug("Add order {0} to existing OCO", sOrderJoinToOCO); sJoinExistingOCORequestID = request.getChildRequest(0).RequestID; // only one order joins existing OCO in this sample session.sendRequest(request); manualEvent.Reset(); manualEvent.WaitOne(); } else { log.debug("Request in \'JoinExistingOCO\' is null, most likely some arguments are mssing or incorrect"); } } /// <summary> /// Create new OCO orders from entry orders /// </summary> /// <param name="sAccountID">Account ID</param> /// <param name="lstOrderIDsCreateNewOCO">list of entry orders to create OCO</param> /// <param name="sOrderIDsCreateNewOCO">string with all order IDs to create OCO (for log purposes)</param> public void JoinNewOCO(string sAccountID, List<string> lstOrderIDsCreateNewOCO) { lstOrdersInNewOCO = lstOrderIDsCreateNewOCO; O2GRequestFactory factory = session.getRequestFactory(); O2GValueMap valuemap = factory.createValueMap(); valuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.JoinToNewContingencyGroup); //set contingencyType for created group valuemap.setInt(O2GRequestParamsEnum.ContingencyGroupType, 1); string sOrderIDsCreateNewOCO = ""; int ji = 0; foreach (string sOrderID in lstOrderIDsCreateNewOCO) { valuemap.appendChild(createValueMapForExistingOrder(sOrderID, sAccountID)); if (ji++ > 0) sOrderIDsCreateNewOCO += ","; sOrderIDsCreateNewOCO += sOrderID; } // create request from valueMap O2GRequest request = factory.createOrderRequest(valuemap); if (request != null) { for (int i = 0; i < request.ChildrenCount; i++) { O2GRequest childRequest = request.getChildRequest(i); string sChildRequestID = childRequest.RequestID; lstCreateNewOCORequestID.Add(sChildRequestID); } iNewOCOOrders = request.ChildrenCount; log.debug("Create new OCO for orders {0}", sOrderIDsCreateNewOCO); CtrlTimer.getInstance().startTimer("OCORequest"); session.sendRequest(request); manualEvent.Reset(); manualEvent.WaitOne(); } else { log.debug("Request in \'JoinNewOCO\' is null, most likely some arguments are mssing or incorrect"); } } private O2GValueMap createValueMapForExistingOrder(string sOrderID, string sAccountID) { O2GRequestFactory factory = session.getRequestFactory(); O2GValueMap valuemap = factory.createValueMap(); valuemap.setString(O2GRequestParamsEnum.OrderID, sOrderID); valuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); return valuemap; } /// <summary> /// Used to get refreshed Orders table so we can extract Contingency ID for newly created OCO on response /// </summary> public void GetOrdersTable(string sAccountID) { O2GRequestFactory requestFactory = session.getRequestFactory(); O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Orders, sAccountID); if (request != null) { sOrdersTableRefreshRequestID = request.RequestID; session.sendRequest(request); manualEvent.Reset(); manualEvent.WaitOne(); } else { log.debug("Request in \'GetOrdersTable\' is null, most likely some arguments are mssing or incorrect"); } } /// <summary> /// Get Contingency ID for newly created OCO order /// </summary> private string GetContingencyID(O2GResponse response) { string sContingencyID = ""; O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GOrdersTableResponseReader reader = readerFactory.createOrdersTableReader(response); int i; bool bOrderFromNewOCOFound = false; for (i = 0; i < reader.Count; i++) { O2GOrderRow row = reader.getRow(i); string sOrderID = row.OrderID; foreach (string sOrderInNewOCO in lstOrdersInNewOCO) // find the order from the list and get ContingencyID for that order { if (sOrderID.Equals(sOrderInNewOCO)) { sContingencyID = row.ContingentOrderID; bOrderFromNewOCOFound = true; break; } } if (bOrderFromNewOCOFound) break; } } return sContingencyID; } public void Dispose() { manualEvent.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // // Purpose: This class represents the software preferences of a particular // culture or community. It includes information such as the // language, writing system, and a calendar used by the culture // as well as methods for common operations such as printing // dates and sorting strings. // // // // !!!! NOTE WHEN CHANGING THIS CLASS !!!! // // If adding or removing members to this class, please update CultureInfoBaseObject // in ndp/clr/src/vm/object.h. Note, the "actual" layout of the class may be // different than the order in which members are declared. For instance, all // reference types will come first in the class before value types (like ints, bools, etc) // regardless of the order in which they are declared. The best way to see the // actual order of the class is to do a !dumpobj on an instance of the managed // object inside of the debugger. // //////////////////////////////////////////////////////////////////////////// using System.Collections.Generic; using System.Diagnostics; using System.Threading; #if ENABLE_WINRT using Internal.Runtime.Augments; #endif namespace System.Globalization { /// <summary> /// This class represents the software preferences of a particular culture /// or community. It includes information such as the language, writing /// system and a calendar used by the culture as well as methods for /// common operations such as printing dates and sorting strings. /// </summary> /// <remarks> /// !!!! NOTE WHEN CHANGING THIS CLASS !!!! /// If adding or removing members to this class, please update /// CultureInfoBaseObject in ndp/clr/src/vm/object.h. Note, the "actual" /// layout of the class may be different than the order in which members /// are declared. For instance, all reference types will come first in the /// class before value types (like ints, bools, etc) regardless of the /// order in which they are declared. The best way to see the actual /// order of the class is to do a !dumpobj on an instance of the managed /// object inside of the debugger. /// </remarks> public partial class CultureInfo : IFormatProvider, ICloneable { // We use an RFC4646 type string to construct CultureInfo. // This string is stored in _name and is authoritative. // We use the _cultureData to get the data for our object private bool _isReadOnly; private CompareInfo? _compareInfo; private TextInfo? _textInfo; internal NumberFormatInfo? _numInfo; internal DateTimeFormatInfo? _dateTimeInfo; private Calendar? _calendar; // // The CultureData instance that we are going to read data from. // For supported culture, this will be the CultureData instance that read data from mscorlib assembly. // For customized culture, this will be the CultureData instance that read data from user customized culture binary file. // internal CultureData _cultureData; internal bool _isInherited; private CultureInfo? _consoleFallbackCulture; // Names are confusing. Here are 3 names we have: // // new CultureInfo() _name _nonSortName _sortName // en-US en-US en-US en-US // de-de_phoneb de-DE_phoneb de-DE de-DE_phoneb // fj-fj (custom) fj-FJ fj-FJ en-US (if specified sort is en-US) // en en // // Note that in Silverlight we ask the OS for the text and sort behavior, so the // textinfo and compareinfo names are the same as the name // This has a de-DE, de-DE_phoneb or fj-FJ style name internal string _name; // This will hold the non sorting name to be returned from CultureInfo.Name property. // This has a de-DE style name even for de-DE_phoneb type cultures private string? _nonSortName; // This will hold the sorting name to be returned from CultureInfo.SortName property. // This might be completely unrelated to the culture name if a custom culture. Ie en-US for fj-FJ. // Otherwise its the sort name, ie: de-DE or de-DE_phoneb private string? _sortName; // Get the current user default culture. This one is almost always used, so we create it by default. private static volatile CultureInfo? s_userDefaultCulture; //The culture used in the user interface. This is mostly used to load correct localized resources. private static volatile CultureInfo? s_userDefaultUICulture; // WARNING: We allow diagnostic tools to directly inspect these three members (s_InvariantCultureInfo, s_DefaultThreadCurrentUICulture and s_DefaultThreadCurrentCulture) // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. // The Invariant culture; private static readonly CultureInfo s_InvariantCultureInfo = new CultureInfo(CultureData.Invariant, isReadOnly: true); // These are defaults that we use if a thread has not opted into having an explicit culture private static volatile CultureInfo? s_DefaultThreadCurrentUICulture; private static volatile CultureInfo? s_DefaultThreadCurrentCulture; [ThreadStatic] private static CultureInfo? s_currentThreadCulture; [ThreadStatic] private static CultureInfo? s_currentThreadUICulture; private static AsyncLocal<CultureInfo>? s_asyncLocalCurrentCulture; private static AsyncLocal<CultureInfo>? s_asyncLocalCurrentUICulture; private static void AsyncLocalSetCurrentCulture(AsyncLocalValueChangedArgs<CultureInfo> args) { s_currentThreadCulture = args.CurrentValue; } private static void AsyncLocalSetCurrentUICulture(AsyncLocalValueChangedArgs<CultureInfo> args) { s_currentThreadUICulture = args.CurrentValue; } private static readonly object _lock = new object(); private static volatile Dictionary<string, CultureInfo>? s_NameCachedCultures; private static volatile Dictionary<int, CultureInfo>? s_LcidCachedCultures; // The parent culture. private CultureInfo? _parent; // LOCALE constants of interest to us internally and privately for LCID functions // (ie: avoid using these and use names if possible) internal const int LOCALE_NEUTRAL = 0x0000; private const int LOCALE_USER_DEFAULT = 0x0400; private const int LOCALE_SYSTEM_DEFAULT = 0x0800; internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000; internal const int LOCALE_CUSTOM_DEFAULT = 0x0c00; internal const int LOCALE_INVARIANT = 0x007F; private static CultureInfo InitializeUserDefaultCulture() { Interlocked.CompareExchange(ref s_userDefaultCulture, GetUserDefaultCulture(), null); return s_userDefaultCulture!; } private static CultureInfo InitializeUserDefaultUICulture() { Interlocked.CompareExchange(ref s_userDefaultUICulture, GetUserDefaultUICulture(), null); return s_userDefaultUICulture!; } public CultureInfo(string name) : this(name, true) { } public CultureInfo(string name, bool useUserOverride) { if (name == null) { throw new ArgumentNullException(nameof(name)); } // Get our data providing record CultureData? cultureData = CultureData.GetCultureData(name, useUserOverride); if (cultureData == null) { throw new CultureNotFoundException(nameof(name), name, SR.Argument_CultureNotSupported); } _cultureData = cultureData; _name = _cultureData.CultureName; _isInherited = GetType() != typeof(CultureInfo); } private CultureInfo(CultureData cultureData, bool isReadOnly = false) { Debug.Assert(cultureData != null); _cultureData = cultureData; _name = cultureData.CultureName; _isInherited = false; _isReadOnly = isReadOnly; } private static CultureInfo? CreateCultureInfoNoThrow(string name, bool useUserOverride) { Debug.Assert(name != null); CultureData? cultureData = CultureData.GetCultureData(name, useUserOverride); if (cultureData == null) { return null; } return new CultureInfo(cultureData); } public CultureInfo(int culture) : this(culture, true) { } public CultureInfo(int culture, bool useUserOverride) { // We don't check for other invalid LCIDS here... if (culture < 0) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } switch (culture) { case LOCALE_CUSTOM_DEFAULT: case LOCALE_SYSTEM_DEFAULT: case LOCALE_NEUTRAL: case LOCALE_USER_DEFAULT: case LOCALE_CUSTOM_UNSPECIFIED: // Can't support unknown custom cultures and we do not support neutral or // non-custom user locales. throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported); default: // Now see if this LCID is supported in the system default CultureData table. _cultureData = CultureData.GetCultureData(culture, useUserOverride); break; } _isInherited = GetType() != typeof(CultureInfo); _name = _cultureData.CultureName; } /// <summary> /// Constructor called by SQL Server's special munged culture - creates a culture with /// a TextInfo and CompareInfo that come from a supplied alternate source. This object /// is ALWAYS read-only. /// Note that we really cannot use an LCID version of this override as the cached /// name we create for it has to include both names, and the logic for this is in /// the GetCultureInfo override *only*. /// </summary> internal CultureInfo(string cultureName, string textAndCompareCultureName) { if (cultureName == null) { throw new ArgumentNullException(nameof(cultureName), SR.ArgumentNull_String); } CultureData? cultureData = CultureData.GetCultureData(cultureName, false); if (cultureData == null) { throw new CultureNotFoundException(nameof(cultureName), cultureName, SR.Argument_CultureNotSupported); } _cultureData = cultureData; _name = _cultureData.CultureName; CultureInfo altCulture = GetCultureInfo(textAndCompareCultureName); _compareInfo = altCulture.CompareInfo; _textInfo = altCulture.TextInfo; } /// <summary> /// We do this to try to return the system UI language and the default user languages /// This method will fallback if this fails (like Invariant) /// </summary> private static CultureInfo GetCultureByName(string name) { try { return new CultureInfo(name) { _isReadOnly = true }; } catch (ArgumentException) { return InvariantCulture; } } /// <summary> /// Return a specific culture. A tad irrelevent now since we always /// return valid data for neutral locales. /// /// Note that there's interesting behavior that tries to find a /// smaller name, ala RFC4647, if we can't find a bigger name. /// That doesn't help with things like "zh" though, so the approach /// is of questionable value /// </summary> public static CultureInfo CreateSpecificCulture(string name) { CultureInfo? culture; try { culture = new CultureInfo(name); } catch (ArgumentException) { // When CultureInfo throws this exception, it may be because someone passed the form // like "az-az" because it came out of an http accept lang. We should try a little // parsing to perhaps fall back to "az" here and use *it* to create the neutral. culture = null; for (int idx = 0; idx < name.Length; idx++) { if ('-' == name[idx]) { try { culture = new CultureInfo(name.Substring(0, idx)); break; } catch (ArgumentException) { // throw the original exception so the name in the string will be right throw; } } } if (culture == null) { // nothing to save here; throw the original exception throw; } } // In the most common case, they've given us a specific culture, so we'll just return that. if (!(culture.IsNeutralCulture)) { return culture; } return new CultureInfo(culture._cultureData.SpecificCultureName); } internal static bool VerifyCultureName(string cultureName, bool throwException) { // This function is used by ResourceManager.GetResourceFileName(). // ResourceManager searches for resource using CultureInfo.Name, // so we should check against CultureInfo.Name. for (int i = 0; i < cultureName.Length; i++) { char c = cultureName[i]; // TODO: Names can only be RFC4646 names (ie: a-zA-Z0-9) while this allows any unicode letter/digit if (char.IsLetterOrDigit(c) || c == '-' || c == '_') { continue; } if (throwException) { throw new ArgumentException(SR.Format(SR.Argument_InvalidResourceCultureName, cultureName)); } return false; } return true; } internal static bool VerifyCultureName(CultureInfo culture, bool throwException) { // If we have an instance of one of our CultureInfos, the user can't have changed the // name and we know that all names are valid in files. if (!culture._isInherited) { return true; } return VerifyCultureName(culture.Name, throwException); } /// <summary> /// This instance provides methods based on the current user settings. /// These settings are volatile and may change over the lifetime of the /// thread. /// </summary> /// <remarks> /// We use the following order to return CurrentCulture and CurrentUICulture /// o Use WinRT to return the current user profile language /// o use current thread culture if the user already set one using CurrentCulture/CurrentUICulture /// o use thread culture if the user already set one using DefaultThreadCurrentCulture /// or DefaultThreadCurrentUICulture /// o Use NLS default user culture /// o Use NLS default system culture /// o Use Invariant culture /// </remarks> public static CultureInfo CurrentCulture { get { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { return (CultureInfo)callbacks.GetUserDefaultCulture(); } #endif #if FEATURE_APPX if (ApplicationModel.IsUap) { CultureInfo? culture = GetCultureInfoForUserPreferredLanguageInAppX(); if (culture != null) return culture; } #endif return s_currentThreadCulture ?? s_DefaultThreadCurrentCulture ?? s_userDefaultCulture ?? InitializeUserDefaultCulture(); } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { callbacks.SetGlobalDefaultCulture(value); return; } #endif #if FEATURE_APPX if (ApplicationModel.IsUap) { if (SetCultureInfoForUserPreferredLanguageInAppX(value)) { // successfully set the culture, otherwise fallback to legacy path return; } } #endif if (s_asyncLocalCurrentCulture == null) { Interlocked.CompareExchange(ref s_asyncLocalCurrentCulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentCulture), null); } s_asyncLocalCurrentCulture!.Value = value; } } public static CultureInfo CurrentUICulture { get { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { return (CultureInfo)callbacks.GetUserDefaultCulture(); } #endif #if FEATURE_APPX if (ApplicationModel.IsUap) { CultureInfo? culture = GetCultureInfoForUserPreferredLanguageInAppX(); if (culture != null) return culture; } #endif return s_currentThreadUICulture ?? s_DefaultThreadCurrentUICulture ?? UserDefaultUICulture; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } CultureInfo.VerifyCultureName(value, true); #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { callbacks.SetGlobalDefaultCulture(value); return; } #endif #if FEATURE_APPX if (ApplicationModel.IsUap) { if (SetCultureInfoForUserPreferredLanguageInAppX(value)) { // successfully set the culture, otherwise fallback to legacy path return; } } #endif if (s_asyncLocalCurrentUICulture == null) { Interlocked.CompareExchange(ref s_asyncLocalCurrentUICulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentUICulture), null); } // this one will set s_currentThreadUICulture too s_asyncLocalCurrentUICulture!.Value = value; } } internal static CultureInfo UserDefaultUICulture => s_userDefaultUICulture ?? InitializeUserDefaultUICulture(); public static CultureInfo InstalledUICulture => s_userDefaultCulture ?? InitializeUserDefaultCulture(); public static CultureInfo? DefaultThreadCurrentCulture { get => s_DefaultThreadCurrentCulture; set { // If you add pre-conditions to this method, check to see if you also need to // add them to Thread.CurrentCulture.set. s_DefaultThreadCurrentCulture = value; } } public static CultureInfo? DefaultThreadCurrentUICulture { get => s_DefaultThreadCurrentUICulture; set { // If they're trying to use a Culture with a name that we can't use in resource lookup, // don't even let them set it on the thread. // If you add more pre-conditions to this method, check to see if you also need to // add them to Thread.CurrentUICulture.set. if (value != null) { CultureInfo.VerifyCultureName(value, true); } s_DefaultThreadCurrentUICulture = value; } } /// <summary> /// This instance provides methods, for example for casing and sorting, /// that are independent of the system and current user settings. It /// should be used only by processes such as some system services that /// require such invariant results (eg. file systems). In general, /// the results are not linguistically correct and do not match any /// culture info. /// </summary> public static CultureInfo InvariantCulture { get { Debug.Assert(s_InvariantCultureInfo != null); return s_InvariantCultureInfo; } } /// <summary> /// Return the parent CultureInfo for the current instance. /// </summary> public virtual CultureInfo Parent { get { if (_parent == null) { CultureInfo culture; string parentName = _cultureData.ParentName; if (string.IsNullOrEmpty(parentName)) { culture = InvariantCulture; } else { culture = CreateCultureInfoNoThrow(parentName, _cultureData.UseUserOverride) ?? // For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant // We can't allow ourselves to fail. In case of custom cultures the parent of the // current custom culture isn't installed. InvariantCulture; } Interlocked.CompareExchange<CultureInfo?>(ref _parent, culture, null); } return _parent!; } } public virtual int LCID => _cultureData.LCID; public virtual int KeyboardLayoutId => _cultureData.KeyboardLayoutId; public static CultureInfo[] GetCultures(CultureTypes types) { // internally we treat UserCustomCultures as Supplementals but v2 // treats as Supplementals and Replacements if ((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture) { types |= CultureTypes.ReplacementCultures; } return CultureData.GetCultures(types); } /// <summary> /// Returns the full name of the CultureInfo. The name is in format like /// "en-US" This version does NOT include sort information in the name. /// </summary> public virtual string Name { get { // We return non sorting name here. if (_nonSortName == null) { _nonSortName = _cultureData.Name ?? string.Empty; } return _nonSortName; } } /// <summary> /// This one has the sort information (ie: de-DE_phoneb) /// </summary> internal string SortName { get { if (_sortName == null) { _sortName = _cultureData.SortName; } return _sortName; } } public string IetfLanguageTag { get { // special case the compatibility cultures switch (this.Name) { case "zh-CHT": return "zh-Hant"; case "zh-CHS": return "zh-Hans"; default: return this.Name; } } } /// <summary> /// Returns the full name of the CultureInfo in the localized language. /// For example, if the localized language of the runtime is Spanish and the CultureInfo is /// US English, "Ingles (Estados Unidos)" will be returned. /// </summary> public virtual string DisplayName { get { Debug.Assert(_name != null, "[CultureInfo.DisplayName] Always expect _name to be set"); return _cultureData.DisplayName; } } /// <summary> /// Returns the full name of the CultureInfo in the native language. /// For example, if the CultureInfo is US English, "English /// (United States)" will be returned. /// </summary> public virtual string NativeName => _cultureData.NativeName; /// <summary> /// Returns the full name of the CultureInfo in English. /// For example, if the CultureInfo is US English, "English /// (United States)" will be returned. /// </summary> public virtual string EnglishName => _cultureData.EnglishName; /// <summary> /// ie: en /// </summary> public virtual string TwoLetterISOLanguageName => _cultureData.TwoLetterISOLanguageName; /// <summary> /// ie: eng /// </summary> public virtual string ThreeLetterISOLanguageName => _cultureData.ThreeLetterISOLanguageName; /// <summary> /// Returns the 3 letter windows language name for the current instance. eg: "ENU" /// The ISO names are much preferred /// </summary> public virtual string ThreeLetterWindowsLanguageName => _cultureData.ThreeLetterWindowsLanguageName; // CompareInfo Read-Only Property /// <summary> /// Gets the CompareInfo for this culture. /// </summary> public virtual CompareInfo CompareInfo { get { if (_compareInfo == null) { // Since CompareInfo's don't have any overrideable properties, get the CompareInfo from // the Non-Overridden CultureInfo so that we only create one CompareInfo per culture _compareInfo = UseUserOverride ? GetCultureInfo(_name).CompareInfo : new CompareInfo(this); } return _compareInfo; } } /// <summary> /// Gets the TextInfo for this culture. /// </summary> public virtual TextInfo TextInfo { get { if (_textInfo == null) { // Make a new textInfo TextInfo tempTextInfo = new TextInfo(_cultureData); tempTextInfo.SetReadOnlyState(_isReadOnly); _textInfo = tempTextInfo; } return _textInfo; } } public override bool Equals(object? value) { if (object.ReferenceEquals(this, value)) { return true; } if (value is CultureInfo that) { // using CompareInfo to verify the data passed through the constructor // CultureInfo(String cultureName, String textAndCompareCultureName) return Name.Equals(that.Name) && CompareInfo.Equals(that.CompareInfo); } return false; } public override int GetHashCode() { return Name.GetHashCode() + CompareInfo.GetHashCode(); } /// <summary> /// Implements object.ToString(). Returns the name of the CultureInfo, /// eg. "de-DE_phoneb", "en-US", or "fj-FJ". /// </summary> public override string ToString() => _name; public virtual object? GetFormat(Type? formatType) { if (formatType == typeof(NumberFormatInfo)) { return NumberFormat; } if (formatType == typeof(DateTimeFormatInfo)) { return DateTimeFormat; } return null; } public virtual bool IsNeutralCulture => _cultureData.IsNeutralCulture; public CultureTypes CultureTypes { get { CultureTypes types = 0; if (_cultureData.IsNeutralCulture) { types |= CultureTypes.NeutralCultures; } else { types |= CultureTypes.SpecificCultures; } types |= _cultureData.IsWin32Installed ? CultureTypes.InstalledWin32Cultures : 0; // Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete #pragma warning disable 618 types |= _cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0; #pragma warning restore 618 types |= _cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0; types |= _cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0; return types; } } public virtual NumberFormatInfo NumberFormat { get { if (_numInfo == null) { NumberFormatInfo temp = new NumberFormatInfo(_cultureData); temp._isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref _numInfo, temp, null); } return _numInfo!; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _numInfo = value; } } /// <summary> /// Create a DateTimeFormatInfo, and fill in the properties according to /// the CultureID. /// </summary> public virtual DateTimeFormatInfo DateTimeFormat { get { if (_dateTimeInfo == null) { // Change the calendar of DTFI to the specified calendar of this CultureInfo. DateTimeFormatInfo temp = new DateTimeFormatInfo(_cultureData, this.Calendar); temp._isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref _dateTimeInfo, temp, null); } return _dateTimeInfo!; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } VerifyWritable(); _dateTimeInfo = value; } } public void ClearCachedData() { // reset the default culture values s_userDefaultCulture = GetUserDefaultCulture(); s_userDefaultUICulture = GetUserDefaultUICulture(); RegionInfo.s_currentRegionInfo = null; #pragma warning disable 0618 // disable the obsolete warning TimeZone.ResetTimeZone(); #pragma warning restore 0618 TimeZoneInfo.ClearCachedData(); s_LcidCachedCultures = null; s_NameCachedCultures = null; CultureData.ClearCachedData(); } /// <summary> /// Map a Win32 CALID to an instance of supported calendar. /// </summary> /// <remarks> /// Shouldn't throw exception since the calType value is from our data /// table or from Win32 registry. /// If we are in trouble (like getting a weird value from Win32 /// registry), just return the GregorianCalendar. /// </remarks> internal static Calendar GetCalendarInstance(CalendarId calType) { if (calType == CalendarId.GREGORIAN) { return new GregorianCalendar(); } return GetCalendarInstanceRare(calType); } /// <summary> /// This function exists as a shortcut to prevent us from loading all of the non-gregorian /// calendars unless they're required. /// </summary> internal static Calendar GetCalendarInstanceRare(CalendarId calType) { Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN"); switch (calType) { case CalendarId.GREGORIAN_US: // Gregorian (U.S.) calendar case CalendarId.GREGORIAN_ME_FRENCH: // Gregorian Middle East French calendar case CalendarId.GREGORIAN_ARABIC: // Gregorian Arabic calendar case CalendarId.GREGORIAN_XLIT_ENGLISH: // Gregorian Transliterated English calendar case CalendarId.GREGORIAN_XLIT_FRENCH: // Gregorian Transliterated French calendar return new GregorianCalendar((GregorianCalendarTypes)calType); case CalendarId.TAIWAN: // Taiwan Era calendar return new TaiwanCalendar(); case CalendarId.JAPAN: // Japanese Emperor Era calendar return new JapaneseCalendar(); case CalendarId.KOREA: // Korean Tangun Era calendar return new KoreanCalendar(); case CalendarId.THAI: // Thai calendar return new ThaiBuddhistCalendar(); case CalendarId.HIJRI: // Hijri (Arabic Lunar) calendar return new HijriCalendar(); case CalendarId.HEBREW: // Hebrew (Lunar) calendar return new HebrewCalendar(); case CalendarId.UMALQURA: return new UmAlQuraCalendar(); case CalendarId.PERSIAN: return new PersianCalendar(); } return new GregorianCalendar(); } /// <summary> /// Return/set the default calendar used by this culture. /// This value can be overridden by regional option if this is a current culture. /// </summary> public virtual Calendar Calendar { get { if (_calendar == null) { Debug.Assert(_cultureData.CalendarIds.Length > 0, "_cultureData.CalendarIds.Length > 0"); // Get the default calendar for this culture. Note that the value can be // from registry if this is a user default culture. Calendar newObj = _cultureData.DefaultCalendar; Interlocked.MemoryBarrier(); newObj.SetReadOnlyState(_isReadOnly); _calendar = newObj; } return _calendar; } } /// <summary> /// Return an array of the optional calendar for this culture. /// </summary> public virtual Calendar[] OptionalCalendars { get { // This property always returns a new copy of the calendar array. CalendarId[] calID = _cultureData.CalendarIds; Calendar[] cals = new Calendar[calID.Length]; for (int i = 0; i < cals.Length; i++) { cals[i] = GetCalendarInstance(calID[i]); } return cals; } } public bool UseUserOverride => _cultureData.UseUserOverride; public CultureInfo GetConsoleFallbackUICulture() { CultureInfo? temp = _consoleFallbackCulture; if (temp == null) { temp = CreateSpecificCulture(_cultureData.SCONSOLEFALLBACKNAME); temp._isReadOnly = true; _consoleFallbackCulture = temp; } return temp; } public virtual object Clone() { CultureInfo ci = (CultureInfo)MemberwiseClone(); ci._isReadOnly = false; // If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless // they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!_isInherited) { if (_dateTimeInfo != null) { ci._dateTimeInfo = (DateTimeFormatInfo)_dateTimeInfo.Clone(); } if (_numInfo != null) { ci._numInfo = (NumberFormatInfo)_numInfo.Clone(); } } else { ci.DateTimeFormat = (DateTimeFormatInfo)this.DateTimeFormat.Clone(); ci.NumberFormat = (NumberFormatInfo)this.NumberFormat.Clone(); } if (_textInfo != null) { ci._textInfo = (TextInfo)_textInfo.Clone(); } if (_calendar != null) { ci._calendar = (Calendar)_calendar.Clone(); } return ci; } public static CultureInfo ReadOnly(CultureInfo ci) { if (ci == null) { throw new ArgumentNullException(nameof(ci)); } if (ci.IsReadOnly) { return ci; } CultureInfo newInfo = (CultureInfo)(ci.MemberwiseClone()); if (!ci.IsNeutralCulture) { // If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless // they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!ci._isInherited) { if (ci._dateTimeInfo != null) { newInfo._dateTimeInfo = DateTimeFormatInfo.ReadOnly(ci._dateTimeInfo); } if (ci._numInfo != null) { newInfo._numInfo = NumberFormatInfo.ReadOnly(ci._numInfo); } } else { newInfo.DateTimeFormat = DateTimeFormatInfo.ReadOnly(ci.DateTimeFormat); newInfo.NumberFormat = NumberFormatInfo.ReadOnly(ci.NumberFormat); } } if (ci._textInfo != null) { newInfo._textInfo = TextInfo.ReadOnly(ci._textInfo); } if (ci._calendar != null) { newInfo._calendar = Calendar.ReadOnly(ci._calendar); } // Don't set the read-only flag too early. // We should set the read-only flag here. Otherwise, info.DateTimeFormat will not be able to set. newInfo._isReadOnly = true; return newInfo; } public bool IsReadOnly => _isReadOnly; private void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } /// <summary> /// For resource lookup, we consider a culture the invariant culture by name equality. /// We perform this check frequently during resource lookup, so adding a property for /// improved readability. /// </summary> internal bool HasInvariantCultureName { get => Name == CultureInfo.InvariantCulture.Name; } /// <summary> /// Helper function overloads of GetCachedReadOnlyCulture. If lcid is 0, we use the name. /// If lcid is -1, use the altName and create one of those special SQL cultures. /// </summary> internal static CultureInfo? GetCultureInfoHelper(int lcid, string? name, string? altName) { // retval is our return value. CultureInfo? retval; // Temporary hashtable for the names. Dictionary<string, CultureInfo>? tempNameHT = s_NameCachedCultures; if (name != null) { name = CultureData.AnsiToLower(name); } if (altName != null) { altName = CultureData.AnsiToLower(altName); } // We expect the same result for both hashtables, but will test individually for added safety. if (tempNameHT == null) { tempNameHT = new Dictionary<string, CultureInfo>(); } else { // If we are called by name, check if the object exists in the hashtable. If so, return it. if (lcid == -1 || lcid == 0) { Debug.Assert(name != null && (lcid != -1 || altName != null)); bool ret; lock (_lock) { ret = tempNameHT.TryGetValue(lcid == 0 ? name! : name! + '\xfffd' + altName!, out retval); } if (ret && retval != null) { return retval; } } } // Next, the Lcid table. Dictionary<int, CultureInfo>? tempLcidHT = s_LcidCachedCultures; if (tempLcidHT == null) { // Case insensitive is not an issue here, save the constructor call. tempLcidHT = new Dictionary<int, CultureInfo>(); } else { // If we were called by Lcid, check if the object exists in the table. If so, return it. if (lcid > 0) { bool ret; lock (_lock) { ret = tempLcidHT.TryGetValue(lcid, out retval); } if (ret && retval != null) { return retval; } } } // We now have two temporary hashtables and the desired object was not found. // We'll construct it. We catch any exceptions from the constructor call and return null. try { switch (lcid) { case -1: // call the private constructor Debug.Assert(name != null && altName != null); retval = new CultureInfo(name!, altName!); break; case 0: Debug.Assert(name != null); retval = new CultureInfo(name!, false); break; default: retval = new CultureInfo(lcid, false); break; } } catch (ArgumentException) { return null; } // Set it to read-only retval._isReadOnly = true; if (lcid == -1) { lock (_lock) { // This new culture will be added only to the name hash table. tempNameHT[name + '\xfffd' + altName] = retval; } // when lcid == -1 then TextInfo object is already get created and we need to set it as read only. retval.TextInfo.SetReadOnlyState(true); } else if (lcid == 0) { // Remember our name (as constructed). Do NOT use alternate sort name versions because // we have internal state representing the sort. (So someone would get the wrong cached version) string newName = CultureData.AnsiToLower(retval._name); // We add this new culture info object to both tables. lock (_lock) { tempNameHT[newName] = retval; } } else { lock (_lock) { tempLcidHT[lcid] = retval; } } // Copy the two hashtables to the corresponding member variables. This will potentially overwrite // new tables simultaneously created by a new thread, but maximizes thread safety. if (-1 != lcid) { // Only when we modify the lcid hash table, is there a need to overwrite. s_LcidCachedCultures = tempLcidHT; } s_NameCachedCultures = tempNameHT; // Finally, return our new CultureInfo object. return retval; } /// <summary> /// Gets a cached copy of the specified culture from an internal /// hashtable (or creates it if not found). (LCID version) /// </summary> public static CultureInfo GetCultureInfo(int culture) { // Must check for -1 now since the helper function uses the value to signal // the altCulture code path for SQL Server. // Also check for zero as this would fail trying to add as a key to the hash. if (culture <= 0) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } CultureInfo? retval = GetCultureInfoHelper(culture, null, null); if (null == retval) { throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported); } return retval; } /// <summary> /// Gets a cached copy of the specified culture from an internal /// hashtable (or creates it if not found). (Named version) /// </summary> public static CultureInfo GetCultureInfo(string name) { // Make sure we have a valid, non-zero length string as name if (name == null) { throw new ArgumentNullException(nameof(name)); } CultureInfo? retval = GetCultureInfoHelper(0, name, null); if (retval == null) { throw new CultureNotFoundException( nameof(name), name, SR.Argument_CultureNotSupported); } return retval; } /// <summary> /// Gets a cached copy of the specified culture from an internal /// hashtable (or creates it if not found). /// </summary> public static CultureInfo GetCultureInfo(string name, string altName) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (altName == null) { throw new ArgumentNullException(nameof(altName)); } CultureInfo? retval = GetCultureInfoHelper(-1, name, altName); if (retval == null) { throw new CultureNotFoundException("name or altName", SR.Format(SR.Argument_OneOfCulturesNotSupported, name, altName)); } return retval; } public static CultureInfo GetCultureInfoByIetfLanguageTag(string name) { // Disallow old zh-CHT/zh-CHS names if (name == "zh-CHT" || name == "zh-CHS") { throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name)); } CultureInfo ci = GetCultureInfo(name); // Disallow alt sorts and es-es_TS if (ci.LCID > 0xffff || ci.LCID == 0x040a) { throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name)); } return ci; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmVATList { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmVATList() : base() { FormClosed += frmVATList_FormClosed; KeyPress += frmVATList_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.Button withEventsField_cmdNew; public System.Windows.Forms.Button cmdNew { get { return withEventsField_cmdNew; } set { if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click -= cmdNew_Click; } withEventsField_cmdNew = value; if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click += cmdNew_Click; } } } private myDataGridView withEventsField_DataList1; public myDataGridView DataList1 { get { return withEventsField_DataList1; } set { if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick -= DataList1_DblClick; withEventsField_DataList1.KeyPress -= DataList1_KeyPress; } withEventsField_DataList1 = value; if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick += DataList1_DblClick; withEventsField_DataList1.KeyPress += DataList1_KeyPress; } } } private System.Windows.Forms.TextBox withEventsField_txtSearch; public System.Windows.Forms.TextBox txtSearch { get { return withEventsField_txtSearch; } set { if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter -= txtSearch_Enter; withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown; withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress; } withEventsField_txtSearch = value; if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter += txtSearch_Enter; withEventsField_txtSearch.KeyDown += txtSearch_KeyDown; withEventsField_txtSearch.KeyPress += txtSearch_KeyPress; } } } private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.Label lbl; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmVATList)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.cmdNew = new System.Windows.Forms.Button(); this.DataList1 = new myDataGridView(); this.txtSearch = new System.Windows.Forms.TextBox(); this.cmdExit = new System.Windows.Forms.Button(); this.lbl = new System.Windows.Forms.Label(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Select a VAT Rate"; this.ClientSize = new System.Drawing.Size(259, 433); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmVATList"; this.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNew.Text = "&New"; this.cmdNew.Size = new System.Drawing.Size(97, 52); this.cmdNew.Location = new System.Drawing.Point(6, 375); this.cmdNew.TabIndex = 4; this.cmdNew.TabStop = false; this.cmdNew.BackColor = System.Drawing.SystemColors.Control; this.cmdNew.CausesValidation = true; this.cmdNew.Enabled = true; this.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNew.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNew.Name = "cmdNew"; //'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State) this.DataList1.Size = new System.Drawing.Size(244, 342); this.DataList1.Location = new System.Drawing.Point(6, 27); this.DataList1.TabIndex = 2; this.DataList1.Name = "DataList1"; this.txtSearch.AutoSize = false; this.txtSearch.Size = new System.Drawing.Size(199, 19); this.txtSearch.Location = new System.Drawing.Point(51, 3); this.txtSearch.TabIndex = 1; this.txtSearch.AcceptsReturn = true; this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch.BackColor = System.Drawing.SystemColors.Window; this.txtSearch.CausesValidation = true; this.txtSearch.Enabled = true; this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch.HideSelection = true; this.txtSearch.ReadOnly = false; this.txtSearch.MaxLength = 0; this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch.Multiline = false; this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch.TabStop = true; this.txtSearch.Visible = true; this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch.Name = "txtSearch"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(153, 375); this.cmdExit.TabIndex = 3; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lbl.Text = "&Search :"; this.lbl.Size = new System.Drawing.Size(40, 13); this.lbl.Location = new System.Drawing.Point(8, 6); this.lbl.TabIndex = 0; this.lbl.BackColor = System.Drawing.Color.Transparent; this.lbl.Enabled = true; this.lbl.ForeColor = System.Drawing.SystemColors.ControlText; this.lbl.Cursor = System.Windows.Forms.Cursors.Default; this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lbl.UseMnemonic = true; this.lbl.Visible = true; this.lbl.AutoSize = true; this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lbl.Name = "lbl"; this.Controls.Add(cmdNew); this.Controls.Add(DataList1); this.Controls.Add(txtSearch); this.Controls.Add(cmdExit); this.Controls.Add(lbl); ((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
namespace Mapack { using System; using System.IO; using System.Globalization; /// <summary>Matrix provides the fundamental operations of numerical linear algebra.</summary> public class Matrix { private double[][] data; private int rows; private int columns; private static Random random = new Random(); /// <summary>Constructs an empty matrix of the given size.</summary> /// <param name="rows">Number of rows.</param> /// <param name="columns">Number of columns.</param> public Matrix(int rows, int columns) { this.rows = rows; this.columns = columns; this.data = new double[rows][]; for (int i = 0; i < rows; i++) { this.data[i] = new double[columns]; } } /// <summary>Constructs a matrix of the given size and assigns a given value to all diagonal elements.</summary> /// <param name="rows">Number of rows.</param> /// <param name="columns">Number of columns.</param> /// <param name="value">Value to assign to the diagnoal elements.</param> public Matrix(int rows, int columns, double value) { this.rows = rows; this.columns = columns; this.data = new double[rows][]; for (int i = 0; i < rows; i++) { data[i] = new double[columns]; } for (int i = 0; i < rows; i++) { data[i][i] = value; } } /// <summary>Constructs a matrix from the given array.</summary> /// <param name="value">The array the matrix gets constructed from.</param> [CLSCompliant(false)] public Matrix(double[][] value) { this.rows = value.Length; this.columns = value[0].Length; for (int i = 0; i < rows; i++) { if (value[i].Length != columns) { throw new ArgumentException("Argument out of range."); } } this.data = value; } /// <summary>Determines weather two instances are equal.</summary> public override bool Equals(object obj) { return Equals(this, (Matrix) obj); } /// <summary>Determines weather two instances are equal.</summary> public static bool Equals(Matrix left, Matrix right) { if (((object) left) == ((object) right)) { return true; } if ((((object) left) == null) || (((object) right) == null)) { return false; } if ((left.Rows != right.Rows) || (left.Columns != right.Columns)) { return false; } for (int i = 0; i < left.Rows; i++) { for (int j = 0; j < left.Columns; j++) { if (left[i, j] != right[i, j]) { return false; } } } return true; } /// <summary>Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.</summary> public override int GetHashCode() { return (this.Rows + this.Columns); } internal double[][] Array { get { return this.data; } } /// <summary>Returns the number of columns.</summary> public int Rows { get { return this.rows; } } /// <summary>Returns the number of columns.</summary> public int Columns { get { return this.columns; } } /// <summary>Return <see langword="true"/> if the matrix is a square matrix.</summary> public bool Square { get { return (rows == columns); } } /// <summary>Returns <see langword="true"/> if the matrix is symmetric.</summary> public bool Symmetric { get { if (this.Square) { for (int i = 0; i < rows; i++) { for (int j = 0; j <= i; j++) { if (data[i][j] != data[j][i]) { return false; } } } return true; } return false; } } /// <summary>Access the value at the given location.</summary> public double this[int row, int column] { set { this.data[row][column] = value; } get { return this.data[row][column]; } } /// <summary>Returns a sub matrix extracted from the current matrix.</summary> /// <param name="startRow">Start row index</param> /// <param name="endRow">End row index</param> /// <param name="startColumn">Start column index</param> /// <param name="endColumn">End column index</param> public Matrix Submatrix(int startRow, int endRow, int startColumn, int endColumn) { if ((startRow > endRow) || (startColumn > endColumn) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) { throw new ArgumentException("Argument out of range."); } Matrix X = new Matrix(endRow - startRow + 1, endColumn - startColumn + 1); double[][] x = X.Array; for (int i = startRow; i <= endRow; i++) { for (int j = startColumn; j <= endColumn; j++) { x[i - startRow][j - startColumn] = data[i][j]; } } return X; } /// <summary>Returns a sub matrix extracted from the current matrix.</summary> /// <param name="rowIndexes">Array of row indices</param> /// <param name="columnIndexes">Array of column indices</param> public Matrix Submatrix(int[] rowIndexes, int[] columnIndexes) { Matrix X = new Matrix(rowIndexes.Length, columnIndexes.Length); double[][] x = X.Array; for (int i = 0; i < rowIndexes.Length; i++) { for (int j = 0; j < columnIndexes.Length; j++) { if ((rowIndexes[i] < 0) || (rowIndexes[i] >= rows) || (columnIndexes[j] < 0) || (columnIndexes[j] >= columns)) { throw new ArgumentException("Argument out of range."); } x[i][j] = data[rowIndexes[i]][columnIndexes[j]]; } } return X; } /// <summary>Returns a sub matrix extracted from the current matrix.</summary> /// <param name="i0">Starttial row index</param> /// <param name="i1">End row index</param> /// <param name="c">Array of row indices</param> public Matrix Submatrix(int i0, int i1, int[] c) { if ((i0 > i1) || (i0 < 0) || (i0 >= this.rows) || (i1 < 0) || (i1 >= this.rows)) { throw new ArgumentException("Argument out of range."); } Matrix X = new Matrix(i1 - i0 + 1, c.Length); double[][] x = X.Array; for (int i = i0; i <= i1; i++) { for (int j = 0; j < c.Length; j++) { if ((c[j] < 0) || (c[j] >= columns)) { throw new ArgumentException("Argument out of range."); } x[i - i0][j] = data[i][c[j]]; } } return X; } /// <summary>Returns a sub matrix extracted from the current matrix.</summary> /// <param name="r">Array of row indices</param> /// <param name="j0">Start column index</param> /// <param name="j1">End column index</param> public Matrix Submatrix(int[] r, int j0, int j1) { if ((j0 > j1) || (j0 < 0) || (j0 >= columns) || (j1 < 0) || (j1 >= columns)) { throw new ArgumentException("Argument out of range."); } Matrix X = new Matrix(r.Length, j1-j0+1); double[][] x = X.Array; for (int i = 0; i < r.Length; i++) { for (int j = j0; j <= j1; j++) { if ((r[i] < 0) || (r[i] >= this.rows)) { throw new ArgumentException("Argument out of range."); } x[i][j - j0] = data[r[i]][j]; } } return X; } /// <summary>Creates a copy of the matrix.</summary> public Matrix Clone() { Matrix X = new Matrix(rows, columns); double[][] x = X.Array; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { x[i][j] = data[i][j]; } } return X; } /// <summary>Returns the transposed matrix.</summary> public Matrix Transpose() { Matrix X = new Matrix(columns, rows); double[][] x = X.Array; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { x[j][i] = data[i][j]; } } return X; } /// <summary>Returns the One Norm for the matrix.</summary> /// <value>The maximum column sum.</value> public double Norm1 { get { double f = 0; for (int j = 0; j < columns; j++) { double s = 0; for (int i = 0; i < rows; i++) { s += Math.Abs(data[i][j]); } f = Math.Max(f, s); } return f; } } /// <summary>Returns the Infinity Norm for the matrix.</summary> /// <value>The maximum row sum.</value> public double InfinityNorm { get { double f = 0; for (int i = 0; i < rows; i++) { double s = 0; for (int j = 0; j < columns; j++) s += Math.Abs(data[i][j]); f = Math.Max(f, s); } return f; } } /// <summary>Returns the Frobenius Norm for the matrix.</summary> /// <value>The square root of sum of squares of all elements.</value> public double FrobeniusNorm { get { double f = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { f = Hypotenuse(f, data[i][j]); } } return f; } } /// <summary>Unary minus.</summary> public static Matrix Negate(Matrix value) { if (value == null) { throw new ArgumentNullException("value"); } int rows = value.Rows; int columns = value.Columns; double[][] data = value.Array; Matrix X = new Matrix(rows, columns); double[][] x = X.Array; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { x[i][j] = -data[i][j]; } } return X; } /// <summary>Unary minus.</summary> public static Matrix operator-(Matrix value) { if (value == null) { throw new ArgumentNullException("value"); } return Negate(value); } /// <summary>Matrix equality.</summary> public static bool operator==(Matrix left, Matrix right) { return Equals(left, right); } /// <summary>Matrix inequality.</summary> public static bool operator!=(Matrix left, Matrix right) { return !Equals(left, right); } /// <summary>Matrix addition.</summary> public static Matrix Add(Matrix left, Matrix right) { if (left == null) { throw new ArgumentNullException("left"); } if (right == null) { throw new ArgumentNullException("right"); } int rows = left.Rows; int columns = left.Columns; double[][] data = left.Array; if ((rows != right.Rows) || (columns != right.Columns)) { throw new ArgumentException("Matrix dimension do not match."); } Matrix X = new Matrix(rows, columns); double[][] x = X.Array; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { x[i][j] = data[i][j] + right[i,j]; } } return X; } /// <summary>Matrix addition.</summary> public static Matrix operator+(Matrix left, Matrix right) { if (left == null) { throw new ArgumentNullException("left"); } if (right == null) { throw new ArgumentNullException("right"); } return Add(left, right); } /// <summary>Matrix subtraction.</summary> public static Matrix Subtract(Matrix left, Matrix right) { if (left == null) { throw new ArgumentNullException("left"); } if (right == null) { throw new ArgumentNullException("right"); } int rows = left.Rows; int columns = left.Columns; double[][] data = left.Array; if ((rows != right.Rows) || (columns != right.Columns)) { throw new ArgumentException("Matrix dimension do not match."); } Matrix X = new Matrix(rows, columns); double[][] x = X.Array; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { x[i][j] = data[i][j] - right[i,j]; } } return X; } /// <summary>Matrix subtraction.</summary> public static Matrix operator-(Matrix left, Matrix right) { if (left == null) { throw new ArgumentNullException("left"); } if (right == null) { throw new ArgumentNullException("right"); } return Subtract(left, right); } /// <summary>Matrix-scalar multiplication.</summary> public static Matrix Multiply(Matrix left, double right) { if (left == null) { throw new ArgumentNullException("left"); } int rows = left.Rows; int columns = left.Columns; double[][] data = left.Array; Matrix X = new Matrix(rows, columns); double[][] x = X.Array; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { x[i][j] = data[i][j] * right; } } return X; } /// <summary>Matrix-scalar multiplication.</summary> public static Matrix operator*(Matrix left, double right) { if (left == null) { throw new ArgumentNullException("left"); } return Multiply(left, right); } /// <summary>Matrix-matrix multiplication.</summary> public static Matrix Multiply(Matrix left, Matrix right) { if (left == null) { throw new ArgumentNullException("left"); } if (right == null) { throw new ArgumentNullException("right"); } int rows = left.Rows; double[][] data = left.Array; if (right.Rows != left.columns) { throw new ArgumentException("Matrix dimensions are not valid."); } int columns = right.Columns; Matrix X = new Matrix(rows, columns); double[][] x = X.Array; int size = left.columns; double[] column = new double[size]; for (int j = 0; j < columns; j++) { for (int k = 0; k < size; k++) { column[k] = right[k,j]; } for (int i = 0; i < rows; i++) { double[] row = data[i]; double s = 0; for (int k = 0; k < size; k++) { s += row[k] * column[k]; } x[i][j] = s; } } return X; } /// <summary>Matrix-matrix multiplication.</summary> public static Matrix operator*(Matrix left, Matrix right) { if (left == null) { throw new ArgumentNullException("left"); } if (right == null) { throw new ArgumentNullException("right"); } return Multiply(left, right); } /// <summary>Returns the LHS solution vetor if the matrix is square or the least squares solution otherwise.</summary> public Matrix Solve(Matrix rightHandSide) { return (rows == columns) ? new LuDecomposition(this).Solve(rightHandSide) : new QrDecomposition(this).Solve(rightHandSide); } /// <summary>Inverse of the matrix if matrix is square, pseudoinverse otherwise.</summary> public Matrix Inverse { get { return this.Solve(Diagonal(rows, rows, 1.0)); } } /// <summary>Determinant if matrix is square.</summary> public double Determinant { get { return new LuDecomposition(this).Determinant; } } /// <summary>Returns the trace of the matrix.</summary> /// <returns>Sum of the diagonal elements.</returns> public double Trace { get { double trace = 0; for (int i = 0; i < Math.Min(rows, columns); i++) { trace += data[i][i]; } return trace; } } /// <summary>Returns a matrix filled with random values.</summary> public static Matrix Random(int rows, int columns) { Matrix X = new Matrix(rows, columns); double[][] x = X.Array; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { x[i][j] = random.NextDouble(); } } return X; } /// <summary>Returns a diagonal matrix of the given size.</summary> public static Matrix Diagonal(int rows, int columns, double value) { Matrix X = new Matrix(rows, columns); double[][] x = X.Array; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { x[i][j] = ((i == j) ? value : 0.0); } } return X; } /// <summary>Returns the matrix in a textual form.</summary> public override string ToString() { using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { writer.Write(this.data[i][j] + " "); } writer.WriteLine(); } return writer.ToString(); } } private static double Hypotenuse(double a, double b) { if (Math.Abs(a) > Math.Abs(b)) { double r = b / a; return Math.Abs(a) * Math.Sqrt(1 + r * r); } if (b != 0) { double r = a / b; return Math.Abs(b) * Math.Sqrt(1 + r * r); } return 0.0; } } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Collections; using System.Diagnostics; using System.Runtime.Serialization; using IServiceProvider = System.IServiceProvider; using Microsoft.VisualStudio.OLE.Interop; using EnvDTE; using Microsoft.VisualStudio.FSharp.ProjectSystem; namespace Microsoft.VisualStudio.FSharp.ProjectSystem.Automation { [ComVisible(true), CLSCompliant(false)] public class OAProjectItem<T> : EnvDTE.ProjectItem where T : HierarchyNode { private T node; private OAProject project; public T Node { get { return this.node; } } /// <summary> /// Returns the automation project /// </summary> public OAProject Project { get { return this.project; } } internal OAProjectItem(OAProject project, T node) { this.node = node; this.project = project; } /// <summary> /// Gets the requested Extender if it is available for this object /// </summary> /// <param name="extenderName">The name of the extender.</param> /// <returns>The extender object.</returns> public virtual object get_Extender(string extenderName) { return null; } /// <summary> /// Gets an object that can be accessed by name at run time. /// </summary> public virtual object Object { get { return this.node.Object; } } /// <summary> /// Gets the Document associated with the item, if one exists. /// </summary> public virtual EnvDTE.Document Document { get { return null; } } /// <summary> /// Gets the number of files associated with a ProjectItem. /// </summary> public virtual short FileCount { get { return (short)1; } } /// <summary> /// Gets a collection of all properties that pertain to the object. /// </summary> public virtual EnvDTE.Properties Properties { get { return UIThread.DoOnUIThread(delegate() { if (this.node.NodeProperties == null) { return null; } return new OAProperties(this.node.NodeProperties); }); } } /// <summary> /// Gets the FileCodeModel object for the project item. /// </summary> public virtual EnvDTE.FileCodeModel FileCodeModel { get { return null; } } /// <summary> /// Gets a ProjectItems for the object. /// </summary> public virtual EnvDTE.ProjectItems ProjectItems { get { return null; } } /// <summary> /// Gets a GUID string indicating the kind or type of the object. /// </summary> public virtual string Kind { get { Guid guid; ErrorHandler.ThrowOnFailure(this.node.GetGuidProperty((int)__VSHPROPID.VSHPROPID_TypeGuid, out guid)); return guid.ToString("B").ToUpperInvariant(); } } /// <summary> /// Saves the project item. /// </summary> /// <param name="fileName">The name with which to save the project or project item.</param> /// <remarks>Implemented by subclasses.</remarks> public virtual void Save(string fileName) { throw new NotImplementedException(); } /// <summary> /// Gets the top-level extensibility object. /// </summary> public virtual EnvDTE.DTE DTE { get { return (EnvDTE.DTE)this.project.DTE; } } /// <summary> /// Gets the ProjectItems collection containing the ProjectItem object supporting this property. /// </summary> public virtual EnvDTE.ProjectItems Collection { get { return UIThread.DoOnUIThread(delegate() { // Get the parent node HierarchyNode parentNode = this.node.Parent; Debug.Assert(parentNode != null, "Failed to get the parent node"); // Get the ProjectItems object for the parent node if (parentNode is ProjectNode) { // The root node for the project return ((OAProject)parentNode.GetAutomationObject()).ProjectItems; } else if (parentNode is FileNode && parentNode.FirstChild != null) { // The item has children return ((OAProjectItem<FileNode>)parentNode.GetAutomationObject()).ProjectItems; } else if (parentNode is FolderNode) { return ((OAProjectItem<FolderNode>)parentNode.GetAutomationObject()).ProjectItems; } else { // Not supported. Override this method in derived classes to return appropriate collection object throw new NotImplementedException(); } }); } } /// <summary> /// Gets a list of available Extenders for the object. /// </summary> public virtual object ExtenderNames { get { return null; } } /// <summary> /// Gets the ConfigurationManager object for this ProjectItem. /// </summary> /// <remarks>We do not support config management based per item.</remarks> public virtual EnvDTE.ConfigurationManager ConfigurationManager { get { return null; } } /// <summary> /// Gets the project hosting the ProjectItem. /// </summary> public virtual EnvDTE.Project ContainingProject { get { return this.project; } } /// <summary> /// Gets or sets a value indicating whether or not the object has been modified since last being saved or opened. /// </summary> public virtual bool Saved { get { return !this.IsDirty; } set { throw new NotImplementedException(); } } /// <summary> /// Gets the Extender category ID (CATID) for the object. /// </summary> public virtual string ExtenderCATID { get { return null; } } /// <summary> /// If the project item is the root of a subproject, then the SubProject property returns the Project object for the subproject. /// </summary> public virtual EnvDTE.Project SubProject { get { return null; } } /// <summary> /// For use by F# tooling only. Checks if the document associated to this item is dirty. /// </summary> public virtual bool IsDirty { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual string Name { get { return this.node.Caption; } set { UIThread.DoOnUIThread(delegate() { if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed || this.node.ProjectMgr.Site == null) { throw new InvalidOperationException(); } IVsExtensibility3 extensibility = this.Node.ProjectMgr.Site.GetService(typeof(IVsExtensibility)) as IVsExtensibility3; if (extensibility == null) { throw new InvalidOperationException(); } extensibility.EnterAutomationFunction(); try { this.node.SetEditLabel(value); // if it succeeded, this.node is now 'stale'. update it. var newItem = this.project.ProjectItems.Item(value) as OAProjectItem<T>; if (newItem != null) { this.node = newItem.node; } } finally { extensibility.ExitAutomationFunction(); } }); } } /// <summary> /// Removes the project item from hierarchy. /// </summary> public virtual void Remove() { if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed || this.node.ProjectMgr.Site == null) { throw new InvalidOperationException(); } UIThread.DoOnUIThread(delegate() { IVsExtensibility3 extensibility = this.Node.ProjectMgr.Site.GetService(typeof(IVsExtensibility)) as IVsExtensibility3; if (extensibility == null) { throw new InvalidOperationException(); } extensibility.EnterAutomationFunction(); try { this.node.Remove(removeFromStorage: false); } finally { extensibility.ExitAutomationFunction(); } }); } /// <summary> /// Removes the item from its project and its storage. /// </summary> public virtual void Delete() { if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed || this.node.ProjectMgr.Site == null) { throw new InvalidOperationException(); } UIThread.DoOnUIThread(delegate() { IVsExtensibility3 extensibility = this.Node.ProjectMgr.Site.GetService(typeof(IVsExtensibility)) as IVsExtensibility3; if (extensibility == null) { throw new InvalidOperationException(); } extensibility.EnterAutomationFunction(); try { this.node.Remove(removeFromStorage: true, promptSave: false); } finally { extensibility.ExitAutomationFunction(); } }); } /// <summary> /// Saves the project item. /// </summary> /// <param name="newFileName">The file name with which to save the solution, project, or project item. If the file exists, it is overwritten.</param> /// <returns>true if save was successful</returns> /// <remarks>This method is implemented on subclasses.</remarks> public virtual bool SaveAs(string newFileName) { throw new NotImplementedException(); } /// <summary> /// Gets a value indicating whether the project item is open in a particular view type. /// </summary> /// <param name="viewKind">A Constants.vsViewKind* indicating the type of view to check.</param> /// <returns>A Boolean value indicating true if the project is open in the given view type; false if not. </returns> public virtual bool get_IsOpen(string viewKind) { throw new NotImplementedException(); } /// <summary> /// Gets the full path and names of the files associated with a project item. /// </summary> /// <param name="index"> The index of the item</param> /// <returns>The full path of the associated item</returns> /// <exception cref="ArgumentOutOfRangeException">Is thrown if index is not one</exception> public virtual string get_FileNames(short index) { // This method should really only be called with 1 as the parameter, but // there used to be a bug in VB/C# that would work with 0. To avoid breaking // existing automation they are still accepting 0. To be compatible with them // we accept it as well. Debug.Assert(index > 0, "Index is 1 based."); if (index < 0) { throw new ArgumentOutOfRangeException("index"); } return this.node.Url; } /// <summary> /// Expands the view of Solution Explorer to show project items. /// </summary> public virtual void ExpandView() { if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed || this.node.ProjectMgr.Site == null) { throw new InvalidOperationException(); } UIThread.DoOnUIThread(delegate() { IVsExtensibility3 extensibility = this.Node.ProjectMgr.Site.GetService(typeof(IVsExtensibility)) as IVsExtensibility3; if (extensibility == null) { throw new InvalidOperationException(); } extensibility.EnterAutomationFunction(); try { IVsUIHierarchyWindow uiHierarchy = UIHierarchyUtilities.GetUIHierarchyWindow(this.node.ProjectMgr.Site, HierarchyNode.SolutionExplorer); if (uiHierarchy == null) { throw new InvalidOperationException(); } uiHierarchy.ExpandItem(node.ProjectMgr.InteropSafeIVsUIHierarchy, this.node.ID, EXPANDFLAGS.EXPF_ExpandFolder); } finally { extensibility.ExitAutomationFunction(); } }); } /// <summary> /// Opens the project item in the specified view. Not implemented because this abstract class dont know what to open /// </summary> /// <param name="ViewKind">Specifies the view kind in which to open the item</param> /// <returns>Window object</returns> public virtual EnvDTE.Window Open(string ViewKind) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Text; using com.calitha.goldparser; using System.Data; using VariableCollection = Epi.Collections.NamedObjectCollection<Epi.IVariable>; namespace Epi.Core.AnalysisInterpreter.Rules { /// <summary> /// Rule for the SELECT command /// </summary> public class Rule_Select : AnalysisRule { bool HasRun = false; AnalysisRule Expression = null; string SelectString = null; bool CancelExpresson = false; StringBuilder fieldnames = new StringBuilder(); /// <summary> /// Constructor for Rule_Select /// </summary> /// <param name="pToken">The token used to build the reduction.</param> public Rule_Select(Rule_Context pContext, NonterminalToken pToken) : base(pContext) { //<Select_Statement> ::= SELECT <Expression> | // | CANCEL SELECT | Select if(pToken.Tokens.Length == 1) { this.CancelExpresson = true; } else { if(pToken.Tokens[0].ToString().ToUpperInvariant() == "CANCEL") { this.CancelExpresson = true; } else { fieldnames.Append(this.GetFieldnames(pToken.Tokens, 1)); this.Expression = AnalysisRule.BuildStatments(pContext, (NonterminalToken)pToken.Tokens[1]); this.SelectString = this.GetCommandElement(pToken.Tokens, 1); } } } protected string GetFieldnames(Token[] tokens, int index) { if (tokens[index] is NonterminalToken) { return ExtractToken(((NonterminalToken)tokens[index]).Tokens).Trim(); } else { return (tokens[index]).ToString(); } } protected string ExtractToken(Token[] tokens) { string tokensInTree = ""; int max = tokens.GetUpperBound(0); for (int i = tokens.GetLowerBound(0); i <= max; i++) { if (tokens[i] is NonterminalToken) { if (tokens[i].ToString().Contains("<Qualified ID>")) tokensInTree += ExtractToken(((NonterminalToken)tokens[i]).Tokens); } else { if (((com.calitha.goldparser.TerminalToken)(tokens[i])).Symbol.ToString() == "Identifier") { if (tokens[i].ToString() != "false" & tokens[i].ToString() != "true") tokensInTree += tokens[i].ToString() + " "; } } } return tokensInTree; } public bool Checkvariablenames(StringBuilder fieldnames, out List<string> invalidfieldnames) { VariableType scopeWord = VariableType.DataSource | VariableType.Standard | VariableType.Global | VariableType.Permanent; VariableCollection vars = this.Context.MemoryRegion.GetVariablesInScope(scopeWord); string workingName = string.Empty; List<string> names = new List<string>(); bool isvalid = false; bool isInBracket = false; foreach (char ch in fieldnames.ToString()) { if (ch == '[') { isInBracket = true; } else if (ch == ']') { isInBracket = false; names.Add(workingName); workingName = string.Empty; } else if (ch == ' ' && isInBracket == false) { if (workingName != string.Empty) { names.Add(workingName); } workingName = string.Empty; } else { workingName = workingName + ch; } } if (workingName != string.Empty) { names.Add(workingName); } invalidfieldnames = new List<string>(); foreach (string name in names) { invalidfieldnames.Add(name); foreach (IVariable var in vars) { if (!(var is Epi.Fields.PredefinedDataField)) { if (var.Name.ToUpperInvariant() == name.ToUpperInvariant()) { isvalid = true; invalidfieldnames.Remove(name); break; } } } if (invalidfieldnames.Count > 0) { if (this.Context.VariableValueList.ContainsKey(name)) { isvalid = true; invalidfieldnames.Remove(name); break; } else if (Context.SelectCommandList.Contains(name.ToUpperInvariant())) { isvalid = true; invalidfieldnames.Remove(name); break; } } } return isvalid; } /// <summary> /// Method to execute the SELECT command /// </summary> /// <returns>Returns the result of executing the reduction.</returns> public override object Execute() { if (!this.HasRun) { if (this.CancelExpresson) { //this.Context.DataTableRefreshNeeded = true; this.Context.SelectExpression.Clear(); this.Context.SelectString.Length = 0; } else { List<string> invalidfieldnames = new List<string>(); bool isValid = Checkvariablenames(fieldnames, out invalidfieldnames); if (isValid & invalidfieldnames.Count == 0) { this.Context.SelectExpression.Add(this.Expression); if (this.Context.SelectString.Length > 0) { if (!this.Context.SelectString.ToString().StartsWith("(")) { this.Context.SelectString.Insert(0, '('); this.Context.SelectString.Append(") AND ("); } else { this.Context.SelectString.Append(" AND ("); } this.Context.SelectString.Append(this.ConvertToSQL(this.SelectString)); this.Context.SelectString.Append(")"); } else { this.Context.SelectString.Append(this.ConvertToSQL(this.SelectString)); } } else { throw new Exception(string.Join(",", invalidfieldnames.ToArray()) + " does not exist "); } } this.Context.GetOutput(); Dictionary<string, string> args = new Dictionary<string, string>(); args.Add("COMMANDNAME", CommandNames.SELECT); this.Context.AnalysisCheckCodeInterface.Display(args); this.HasRun = true; } return null; } private string ConvertToSQL(string pValue) { string result = pValue.Replace("\"", "\'").Replace("(.)", "NULL").Replace("(+)", "true").Replace("(-)", "false"); return result; } } }
using NHibernate.Dialect.Function; using NHibernate.SqlCommand; namespace NHibernateDialect { public class CustomMsSqlCe40Dialect : MsSqlCe40Dialect { public CustomMsSqlCe40Dialect() { RegisterKeywords(); RegisterFunctions(); } protected virtual void RegisterKeywords() { RegisterKeyword("@@IDENTITY"); RegisterKeyword("ADD"); RegisterKeyword("ALL"); RegisterKeyword("ALTER"); RegisterKeyword("AND"); RegisterKeyword("ANY"); RegisterKeyword("AS"); RegisterKeyword("ASC"); RegisterKeyword("AUTHORIZATION"); RegisterKeyword("AVG"); RegisterKeyword("BACKUP"); RegisterKeyword("BEGIN"); RegisterKeyword("BETWEEN"); RegisterKeyword("BREAK"); RegisterKeyword("BROWSE"); RegisterKeyword("BULK"); RegisterKeyword("BY"); RegisterKeyword("CASCADE"); RegisterKeyword("CASE"); RegisterKeyword("CHECK"); RegisterKeyword("CHECKPOINT"); RegisterKeyword("CLOSE"); RegisterKeyword("CLUSTERED"); RegisterKeyword("COALESCE"); RegisterKeyword("COLLATE"); RegisterKeyword("COLUMN"); RegisterKeyword("COMMIT"); RegisterKeyword("COMPUTE"); RegisterKeyword("CONSTRAINT"); RegisterKeyword("CONTAINS"); RegisterKeyword("CONTAINSTABLE"); RegisterKeyword("CONTINUE"); RegisterKeyword("CONVERT"); RegisterKeyword("COUNT"); RegisterKeyword("CREATE"); RegisterKeyword("CROSS"); RegisterKeyword("CURRENT"); RegisterKeyword("CURRENT_DATE"); RegisterKeyword("CURRENT_TIME"); RegisterKeyword("CURRENT_TIMESTAMP"); RegisterKeyword("CURRENT_USER"); RegisterKeyword("CURSOR"); RegisterKeyword("DATABASE"); RegisterKeyword("DATABASEPASSWORD"); RegisterKeyword("DATEADD"); RegisterKeyword("DATEDIFF"); RegisterKeyword("DATENAME"); RegisterKeyword("DATEPART"); RegisterKeyword("DBCC"); RegisterKeyword("DEALLOCATE"); RegisterKeyword("DECLARE"); RegisterKeyword("DEFAULT"); RegisterKeyword("DELETE"); RegisterKeyword("DENY"); RegisterKeyword("DESC"); RegisterKeyword("DISK"); RegisterKeyword("DISTINCT"); RegisterKeyword("DISTRIBUTED"); RegisterKeyword("DOUBLE"); RegisterKeyword("DROP"); RegisterKeyword("DUMP"); RegisterKeyword("ELSE"); RegisterKeyword("ENCRYPTION"); RegisterKeyword("END"); RegisterKeyword("ERRLVL"); RegisterKeyword("ESCAPE"); RegisterKeyword("EXCEPT"); RegisterKeyword("EXEC"); RegisterKeyword("EXECUTE"); RegisterKeyword("EXISTS"); RegisterKeyword("EXIT"); RegisterKeyword("EXPRESSION"); RegisterKeyword("FETCH"); RegisterKeyword("FILE"); RegisterKeyword("FILLFACTOR"); RegisterKeyword("FOR"); RegisterKeyword("FOREIGN"); RegisterKeyword("FREETEXT"); RegisterKeyword("FREETEXTTABLE"); RegisterKeyword("FROM"); RegisterKeyword("FULL"); RegisterKeyword("FUNCTION"); RegisterKeyword("GOTO"); RegisterKeyword("GRANT"); RegisterKeyword("GROUP"); RegisterKeyword("HAVING"); RegisterKeyword("HOLDLOCK"); RegisterKeyword("IDENTITY"); RegisterKeyword("IDENTITY_INSERT"); RegisterKeyword("IDENTITYCOL"); RegisterKeyword("IF"); RegisterKeyword("IN"); RegisterKeyword("INDEX"); RegisterKeyword("INNER"); RegisterKeyword("INSERT"); RegisterKeyword("INTERSECT"); RegisterKeyword("INTO"); RegisterKeyword("IS"); RegisterKeyword("JOIN"); RegisterKeyword("KEY"); RegisterKeyword("KILL"); RegisterKeyword("LEFT"); RegisterKeyword("LIKE"); RegisterKeyword("LINENO"); RegisterKeyword("LOAD"); RegisterKeyword("MAX"); RegisterKeyword("MIN"); RegisterKeyword("NATIONAL"); RegisterKeyword("NOCHECK"); RegisterKeyword("NONCLUSTERED"); RegisterKeyword("NOT"); RegisterKeyword("NULL"); RegisterKeyword("NULLIF"); RegisterKeyword("OF"); RegisterKeyword("OFF"); RegisterKeyword("OFFSETS"); RegisterKeyword("ON"); RegisterKeyword("OPEN"); RegisterKeyword("OPENDATASOURCE"); RegisterKeyword("OPENQUERY"); RegisterKeyword("OPENROWSET"); RegisterKeyword("OPENXML"); RegisterKeyword("OPTION"); RegisterKeyword("OR"); RegisterKeyword("ORDER"); RegisterKeyword("OUTER"); RegisterKeyword("OVER"); RegisterKeyword("PERCENT"); RegisterKeyword("PLAN"); RegisterKeyword("PRECISION"); RegisterKeyword("PRIMARY"); RegisterKeyword("PRINT"); RegisterKeyword("PROC"); RegisterKeyword("PROCEDURE"); RegisterKeyword("PUBLIC"); RegisterKeyword("RAISERROR"); RegisterKeyword("READ"); RegisterKeyword("READTEXT"); RegisterKeyword("RECONFIGURE"); RegisterKeyword("REFERENCES"); RegisterKeyword("REPLICATION"); RegisterKeyword("RESTORE"); RegisterKeyword("RESTRICT"); RegisterKeyword("RETURN"); RegisterKeyword("REVOKE"); RegisterKeyword("RIGHT"); RegisterKeyword("ROLLBACK"); RegisterKeyword("ROWCOUNT"); RegisterKeyword("ROWGUIDCOL"); RegisterKeyword("RULE"); RegisterKeyword("SAVE"); RegisterKeyword("SCHEMA"); RegisterKeyword("SELECT"); RegisterKeyword("SESSION_USER"); RegisterKeyword("SET"); RegisterKeyword("SETUSER"); RegisterKeyword("SHUTDOWN"); RegisterKeyword("SOME"); RegisterKeyword("STATISTICS"); RegisterKeyword("SUM"); RegisterKeyword("SYSTEM_USER"); RegisterKeyword("TABLE"); RegisterKeyword("TEXTSIZE"); RegisterKeyword("THEN"); RegisterKeyword("TO"); RegisterKeyword("TOP"); RegisterKeyword("TRAN"); RegisterKeyword("TRANSACTION"); RegisterKeyword("TRIGGER"); RegisterKeyword("TRUNCATE"); RegisterKeyword("TSEQUAL"); RegisterKeyword("UNION"); RegisterKeyword("UNIQUE"); RegisterKeyword("UPDATE"); RegisterKeyword("UPDATETEXT"); RegisterKeyword("USE"); RegisterKeyword("USER"); RegisterKeyword("VALUES"); RegisterKeyword("VARYING"); RegisterKeyword("VIEW"); RegisterKeyword("WAITFOR"); RegisterKeyword("WHEN"); RegisterKeyword("WHERE"); RegisterKeyword("WHILE"); RegisterKeyword("WITH"); RegisterKeyword("WRITETEXT"); RegisterKeyword("smallint"); RegisterKeyword("int"); RegisterKeyword("real"); RegisterKeyword("float"); RegisterKeyword("money"); RegisterKeyword("bit"); RegisterKeyword("tinyint"); RegisterKeyword("bigint"); RegisterKeyword("uniqueidentifier"); RegisterKeyword("varbinary"); RegisterKeyword("binary"); RegisterKeyword("image"); RegisterKeyword("nvarchar"); RegisterKeyword("nchar"); RegisterKeyword("ntext"); RegisterKeyword("numeric"); RegisterKeyword("datetime"); RegisterKeyword("rowversion"); RegisterKeyword("@@DBTS"); RegisterKeyword("@@SHOWPLAN"); RegisterKeyword("ABS"); RegisterKeyword("ACOS"); RegisterKeyword("ASIN"); RegisterKeyword("ATAN"); RegisterKeyword("ATN2"); RegisterKeyword("CEILING"); RegisterKeyword("CHARINDEX"); RegisterKeyword("CAST"); RegisterKeyword("COS"); RegisterKeyword("COT"); RegisterKeyword("DATALENGTH"); RegisterKeyword("DEGREES"); RegisterKeyword("EXP"); RegisterKeyword("FLOOR"); RegisterKeyword("GETDATE"); RegisterKeyword("LEN"); RegisterKeyword("LOG"); RegisterKeyword("LOG10"); RegisterKeyword("LOWER"); RegisterKeyword("LTRIM"); RegisterKeyword("NCHAR"); RegisterKeyword("NEWID"); RegisterKeyword("PATINDEX"); RegisterKeyword("PI"); RegisterKeyword("POWER"); RegisterKeyword("RADIANS"); RegisterKeyword("RAND"); RegisterKeyword("REPLACE"); RegisterKeyword("REPLICATE"); RegisterKeyword("RTRIM"); RegisterKeyword("SHOWPLAN"); RegisterKeyword("XML"); RegisterKeyword("SIGN"); RegisterKeyword("SIN"); RegisterKeyword("SPACE"); RegisterKeyword("SQRT"); RegisterKeyword("STR"); RegisterKeyword("STUFF"); RegisterKeyword("SUBSTRING"); RegisterKeyword("TAN"); RegisterKeyword("UNICODE"); RegisterKeyword("UPPER"); RegisterKeyword("FORCE"); RegisterKeyword("ROWLOCK"); RegisterKeyword("PAGLOCK"); RegisterKeyword("TABLOCK"); RegisterKeyword("DBLOCK"); RegisterKeyword("UPDLOCK"); RegisterKeyword("XLOCK"); RegisterKeyword("HOLDLOCK"); RegisterKeyword("NOLOCK"); RegisterKeyword("GO"); RegisterKeyword("NEXT"); RegisterKeyword("OFFSET"); RegisterKeyword("ONLY"); RegisterKeyword("ROWS"); } protected virtual void RegisterFunctions() { //Date and Time Functions RegisterFunction("second", new SQLFunctionTemplate(NHibernateUtil.Int32, "datepart(second, ?1)")); RegisterFunction("minute", new SQLFunctionTemplate(NHibernateUtil.Int32, "datepart(minute, ?1)")); RegisterFunction("hour", new SQLFunctionTemplate(NHibernateUtil.Int32, "datepart(hour, ?1)")); RegisterFunction("day", new SQLFunctionTemplate(NHibernateUtil.Int32, "datepart(day, ?1)")); RegisterFunction("month", new SQLFunctionTemplate(NHibernateUtil.Int32, "datepart(month, ?1)")); RegisterFunction("year", new SQLFunctionTemplate(NHibernateUtil.Int32, "datepart(year, ?1)")); RegisterFunction("date", new SQLFunctionTemplate(NHibernateUtil.Date, "dateadd(dd, 0, datediff(dd, 0, ?1))")); RegisterFunction("datename", new StandardSQLFunction("datename", NHibernateUtil.String)); RegisterFunction("current_timestamp", new NoArgSQLFunction("getdate", NHibernateUtil.DateTime, true)); RegisterFunction("datediff", new StandardSQLFunction("datediff", NHibernateUtil.Int32)); //Mathematical Functions RegisterFunction("abs", new StandardSQLFunction("abs")); RegisterFunction("acos", new StandardSQLFunction("acos", NHibernateUtil.Double)); RegisterFunction("asin", new StandardSQLFunction("asin", NHibernateUtil.Double)); RegisterFunction("atan", new StandardSQLFunction("atan", NHibernateUtil.Double)); RegisterFunction("atan2", new StandardSQLFunction("atan2", NHibernateUtil.Double)); RegisterFunction("ceiling", new StandardSQLFunction("ceiling")); RegisterFunction("cos", new StandardSQLFunction("cos", NHibernateUtil.Double)); RegisterFunction("cot", new StandardSQLFunction("cot", NHibernateUtil.Double)); RegisterFunction("degrees", new StandardSQLFunction("degrees", NHibernateUtil.Double)); RegisterFunction("exp", new StandardSQLFunction("exp", NHibernateUtil.Double)); RegisterFunction("floor", new StandardSQLFunction("floor")); RegisterFunction("log", new StandardSQLFunction("log", NHibernateUtil.Double)); RegisterFunction("log10", new StandardSQLFunction("log10", NHibernateUtil.Double)); RegisterFunction("pi", new NoArgSQLFunction("pi", NHibernateUtil.Double, true)); RegisterFunction("power", new StandardSQLFunction("power", NHibernateUtil.Double)); RegisterFunction("radians", new StandardSQLFunction("radians", NHibernateUtil.Double)); RegisterFunction("rand", new NoArgSQLFunction("rand", NHibernateUtil.Double)); RegisterFunction("round", new StandardSQLFunction("round")); RegisterFunction("sign", new StandardSQLFunction("sign", NHibernateUtil.Int32)); RegisterFunction("sin", new StandardSQLFunction("sin", NHibernateUtil.Double)); RegisterFunction("sqrt", new StandardSQLFunction("sqrt", NHibernateUtil.Double)); RegisterFunction("tan", new StandardSQLFunction("tan", NHibernateUtil.Double)); //String Functions RegisterFunction("locate", new StandardSQLFunction("charindex", NHibernateUtil.Int32)); RegisterFunction("length", new StandardSQLFunction("len", NHibernateUtil.Int32)); RegisterFunction("lower", new StandardSQLFunction("lower")); RegisterFunction("ltrim", new StandardSQLFunction("ltrim")); RegisterFunction("patindex", new StandardSQLFunction("patindex", NHibernateUtil.Int32)); RegisterFunction("replace", new StandardSafeSQLFunction("replace", NHibernateUtil.String, 3)); RegisterFunction("replicate", new StandardSQLFunction("replicate", NHibernateUtil.String)); RegisterFunction("rtrim", new StandardSQLFunction("rtrim", NHibernateUtil.String)); RegisterFunction("space", new StandardSQLFunction("space", NHibernateUtil.String)); RegisterFunction("str", new VarArgsSQLFunction(NHibernateUtil.String, "str(", ",", ")")); RegisterFunction("stuff", new StandardSQLFunction("stuff", NHibernateUtil.String)); RegisterFunction("substring", new AnsiSubstringFunction()); RegisterFunction("unicode", new StandardSQLFunction("unicode", NHibernateUtil.Int32)); RegisterFunction("upper", new StandardSQLFunction("upper")); RegisterFunction("trim", new AnsiTrimEmulationFunction()); RegisterFunction("concat", new VarArgsSQLFunction(NHibernateUtil.String, "(", "", ")")); //System Functions RegisterFunction("coalesce", new VarArgsSQLFunction("coalesce(", ",", ")")); RegisterFunction("newid", new NoArgSQLFunction("newid", NHibernateUtil.String, true)); } public override bool SupportsLimit { get { return true; } } public override bool SupportsLimitOffset { get { return true; } } public override string SelectGUIDString { get { return "select newid()"; } } public override bool SupportsIdentityColumns { get { return true; } } public override char CloseQuote { get { return ']'; } } public override char OpenQuote { get { return '['; } } /// <summary> /// Can parameters be used for a statement containing a LIMIT? /// </summary> public override bool SupportsVariableLimit { get { return false; } } /// <summary> /// Does the <c>LIMIT</c> clause take a "maximum" row number /// instead of a total number of returned rows? /// </summary> /// <returns>false, unless overridden</returns> public override bool UseMaxForLimit { get { return true; } } public override bool SupportsSqlBatches { get { return false; } } public override bool IsKnownToken(string currentToken, string nextToken) { return currentToken == "n" && nextToken == "'"; // unicode character } public override bool SupportsUnionAll { get { return true; } } public override bool SupportsCircularCascadeDeleteConstraints { get { return false; } } } }
//--------------------------------------------------------------------- // <copyright file="EntityObject.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Data; using System.Diagnostics; using System.Reflection; using System.ComponentModel; using System.Runtime.Serialization; namespace System.Data.Objects.DataClasses { /// <summary> /// This is the class is the basis for all perscribed EntityObject classes. /// </summary> [DataContract(IsReference=true)] [Serializable] public abstract class EntityObject : StructuralObject, IEntityWithKey, IEntityWithChangeTracker, IEntityWithRelationships { #region Privates // The following 2 fields are serialized. Adding or removing a serialized field is considered // a breaking change. This includes changing the field type or field name of existing // serialized fields. If you need to make this kind of change, it may be possible, but it // will require some custom serialization/deserialization code. private RelationshipManager _relationships; private EntityKey _entityKey; [NonSerialized] private IEntityChangeTracker _entityChangeTracker = s_detachedEntityChangeTracker; [NonSerialized] private static readonly DetachedEntityChangeTracker s_detachedEntityChangeTracker = new DetachedEntityChangeTracker(); /// <summary> /// Helper class used when we are not currently attached to a change tracker. /// Simplifies the code so we don't always have to check for null before using the change tracker /// </summary> private class DetachedEntityChangeTracker : IEntityChangeTracker { void IEntityChangeTracker.EntityMemberChanging(string entityMemberName) { } void IEntityChangeTracker.EntityMemberChanged(string entityMemberName) { } void IEntityChangeTracker.EntityComplexMemberChanging(string entityMemberName, object complexObject, string complexMemberName) { } void IEntityChangeTracker.EntityComplexMemberChanged(string entityMemberName, object complexObject, string complexMemberName) { } EntityState IEntityChangeTracker.EntityState { get { return EntityState.Detached; } } } private IEntityChangeTracker EntityChangeTracker { get { if (_entityChangeTracker == null) { _entityChangeTracker = s_detachedEntityChangeTracker; } return _entityChangeTracker; } set { _entityChangeTracker = value; } } #endregion #region Publics /// <summary> /// The storage state of this EntityObject /// </summary> /// <value> /// This property returns a value from the EntityState enum. /// </value> [System.ComponentModel.Browsable(false)] [System.Xml.Serialization.XmlIgnore] public EntityState EntityState { get { Debug.Assert(EntityChangeTracker != null, "EntityChangeTracker should never return null -- if detached should be set to s_detachedEntityChangeTracker"); Debug.Assert(EntityChangeTracker != s_detachedEntityChangeTracker ? EntityChangeTracker.EntityState != EntityState.Detached : true, "Should never get a detached state from an attached change tracker."); return EntityChangeTracker.EntityState; } } #region IEntityWithKey /// <summary> /// Returns the EntityKey for this EntityObject. /// </summary> [Browsable(false)] [DataMember] public EntityKey EntityKey { get { return _entityKey; } set { // Report the change to the change tracker // If we are not attached to a change tracker, we can do anything we want to the key // If we are attached, the change tracker should make sure the new value is valid for the current state Debug.Assert(EntityChangeTracker != null, "_entityChangeTracker should never be null -- if detached it should return s_detachedEntityChangeTracker"); EntityChangeTracker.EntityMemberChanging(StructuralObject.EntityKeyPropertyName); _entityKey = value; EntityChangeTracker.EntityMemberChanged(StructuralObject.EntityKeyPropertyName); } } #endregion #region IEntityWithChangeTracker /// <summary> /// Used by the ObjectStateManager to attach or detach this EntityObject to the cache. /// </summary> /// <param name="changeTracker"> /// Reference to the ObjectStateEntry that contains this entity /// </param> void IEntityWithChangeTracker.SetChangeTracker(IEntityChangeTracker changeTracker) { // Fail if the change tracker is already set for this EntityObject and it's being set to something different // If the original change tracker is associated with a disposed ObjectStateManager, then allow // the entity to be attached if (changeTracker != null && EntityChangeTracker != s_detachedEntityChangeTracker && !Object.ReferenceEquals(changeTracker, EntityChangeTracker)) { EntityEntry entry = EntityChangeTracker as EntityEntry; if (entry == null || !entry.ObjectStateManager.IsDisposed) { throw EntityUtil.EntityCantHaveMultipleChangeTrackers(); } } EntityChangeTracker = changeTracker; } #endregion IEntityWithChangeTracker #region IEntityWithRelationships /// <summary> /// Returns the container for the lazily created relationship /// navigation property objects, collections and refs. /// </summary> RelationshipManager IEntityWithRelationships.RelationshipManager { get { if (_relationships == null) { _relationships = RelationshipManager.Create(this); } return _relationships; } } #endregion #endregion #region Protected Change Tracking Methods /// <summary> /// This method is called whenever a change is going to be made to an EntityObject /// property. /// </summary> /// <param name="property"> /// The name of the changing property. /// </param> /// <exception cref="System.ArgumentNullException"> /// When parameter member is null (Nothing in Visual Basic). /// </exception> protected sealed override void ReportPropertyChanging( string property) { EntityUtil.CheckStringArgument(property, "property"); Debug.Assert(EntityChangeTracker != null, "_entityChangeTracker should never be null -- if detached it should return s_detachedEntityChangeTracker"); base.ReportPropertyChanging(property); EntityChangeTracker.EntityMemberChanging(property); } /// <summary> /// This method is called whenever a change is made to an EntityObject /// property. /// </summary> /// <param name="property"> /// The name of the changed property. /// </param> /// <exception cref="System.ArgumentNullException"> /// When parameter member is null (Nothing in Visual Basic). /// </exception> protected sealed override void ReportPropertyChanged( string property) { EntityUtil.CheckStringArgument(property, "property"); Debug.Assert(EntityChangeTracker != null, "EntityChangeTracker should never return null -- if detached it should be return s_detachedEntityChangeTracker"); EntityChangeTracker.EntityMemberChanged(property); base.ReportPropertyChanged(property); } #endregion #region Internal ComplexObject Change Tracking Methods and Properties internal sealed override bool IsChangeTracked { get { return EntityState != EntityState.Detached; } } /// <summary> /// This method is called by a ComplexObject contained in this Entity /// whenever a change is about to be made to a property of the /// ComplexObject so that the change can be forwarded to the change tracker. /// </summary> /// <param name="entityMemberName"> /// The name of the top-level entity property that contains the ComplexObject that is calling this method. /// </param> /// <param name="complexObject"> /// The instance of the ComplexObject on which the property is changing. /// </param> /// <param name="complexMemberName"> /// The name of the changing property on complexObject. /// </param> internal sealed override void ReportComplexPropertyChanging( string entityMemberName, ComplexObject complexObject, string complexMemberName) { Debug.Assert(complexObject != null, "invalid complexObject"); Debug.Assert(!String.IsNullOrEmpty(complexMemberName), "invalid complexMemberName"); EntityChangeTracker.EntityComplexMemberChanging(entityMemberName, complexObject, complexMemberName); } /// <summary> /// This method is called by a ComplexObject contained in this Entity /// whenever a change has been made to a property of the /// ComplexObject so that the change can be forwarded to the change tracker. /// </summary> /// <param name="entityMemberName"> /// The name of the top-level entity property that contains the ComplexObject that is calling this method. /// </param> /// <param name="complexObject"> /// The instance of the ComplexObject on which the property is changing. /// </param> /// <param name="complexMemberName"> /// The name of the changing property on complexObject. /// </param> internal sealed override void ReportComplexPropertyChanged( string entityMemberName, ComplexObject complexObject, string complexMemberName) { Debug.Assert(complexObject != null, "invalid complexObject"); Debug.Assert(!String.IsNullOrEmpty(complexMemberName), "invalid complexMemberName"); EntityChangeTracker.EntityComplexMemberChanged(entityMemberName, complexObject, complexMemberName); } #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.Immutable; using System.IO; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.PortableExecutable { /// <summary> /// An object used to read PE (Portable Executable) and COFF (Common Object File Format) headers from a stream. /// </summary> public sealed class PEHeaders { private readonly CoffHeader _coffHeader; private readonly PEHeader _peHeader; private readonly ImmutableArray<SectionHeader> _sectionHeaders; private readonly CorHeader _corHeader; private readonly int _metadataStartOffset = -1; private readonly int _metadataSize; private readonly int _coffHeaderStartOffset = -1; private readonly int _corHeaderStartOffset = -1; private readonly int _peHeaderStartOffset = -1; /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image starting at the stream's current position and ending at the end of the stream.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> public PEHeaders(Stream peStream) : this(peStream, null) { } /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param> /// <param name="size">Size of the PE image.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception> public PEHeaders(Stream peStream, int size) : this(peStream, (int?)size) { } private PEHeaders(Stream peStream, int? sizeOpt) { if (peStream == null) { throw new ArgumentNullException(nameof(peStream)); } if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream)); } int size = PEBinaryReader.GetAndValidateSize(peStream, sizeOpt); var reader = new PEBinaryReader(peStream, size); bool isCoffOnly; SkipDosHeader(ref reader, out isCoffOnly); _coffHeaderStartOffset = reader.CurrentOffset; _coffHeader = new CoffHeader(ref reader); if (!isCoffOnly) { _peHeaderStartOffset = reader.CurrentOffset; _peHeader = new PEHeader(ref reader); } _sectionHeaders = this.ReadSectionHeaders(ref reader); if (!isCoffOnly) { int offset; if (TryCalculateCorHeaderOffset(size, out offset)) { _corHeaderStartOffset = offset; reader.Seek(offset); _corHeader = new CorHeader(ref reader); } } CalculateMetadataLocation(size, out _metadataStartOffset, out _metadataSize); } /// <summary> /// Gets the offset (in bytes) from the start of the PE image to the start of the CLI metadata. /// or -1 if the image does not contain metadata. /// </summary> public int MetadataStartOffset { get { return _metadataStartOffset; } } /// <summary> /// Gets the size of the CLI metadata 0 if the image does not contain metadata.) /// </summary> public int MetadataSize { get { return _metadataSize; } } /// <summary> /// Gets the COFF header of the image. /// </summary> public CoffHeader CoffHeader { get { return _coffHeader; } } /// <summary> /// Gets the byte offset from the start of the PE image to the start of the COFF header. /// </summary> public int CoffHeaderStartOffset { get { return _coffHeaderStartOffset; } } /// <summary> /// Determines if the image is Coff only. /// </summary> public bool IsCoffOnly { get { return _peHeader == null; } } /// <summary> /// Gets the PE header of the image or null if the image is COFF only. /// </summary> public PEHeader PEHeader { get { return _peHeader; } } /// <summary> /// Gets the byte offset from the start of the image to /// </summary> public int PEHeaderStartOffset { get { return _peHeaderStartOffset; } } /// <summary> /// Gets the PE section headers. /// </summary> public ImmutableArray<SectionHeader> SectionHeaders { get { return _sectionHeaders; } } /// <summary> /// Gets the CLI header or null if the image does not have one. /// </summary> public CorHeader CorHeader { get { return _corHeader; } } /// <summary> /// Gets the byte offset from the start of the image to the COR header or -1 if the image does not have one. /// </summary> public int CorHeaderStartOffset { get { return _corHeaderStartOffset; } } /// <summary> /// Determines if the image represents a Windows console application. /// </summary> public bool IsConsoleApplication { get { return _peHeader != null && _peHeader.Subsystem == Subsystem.WindowsCui; } } /// <summary> /// Determines if the image represents a dynamically linked library. /// </summary> public bool IsDll { get { return (_coffHeader.Characteristics & Characteristics.Dll) != 0; } } /// <summary> /// Determines if the image represents an executable. /// </summary> public bool IsExe { get { return (_coffHeader.Characteristics & Characteristics.Dll) == 0; } } private bool TryCalculateCorHeaderOffset(long peStreamSize, out int startOffset) { if (!TryGetDirectoryOffset(_peHeader.CorHeaderTableDirectory, out startOffset)) { startOffset = -1; return false; } int length = _peHeader.CorHeaderTableDirectory.Size; if (length < COR20Constants.SizeOfCorHeader) { throw new BadImageFormatException(SR.InvalidCorHeaderSize); } return true; } private void SkipDosHeader(ref PEBinaryReader reader, out bool isCOFFOnly) { // Look for DOS Signature "MZ" ushort dosSig = reader.ReadUInt16(); if (dosSig != PEFileConstants.DosSignature) { // If image doesn't start with DOS signature, let's assume it is a // COFF (Common Object File Format), aka .OBJ file. // See CLiteWeightStgdbRW::FindObjMetaData in ndp\clr\src\MD\enc\peparse.cpp if (dosSig != 0 || reader.ReadUInt16() != 0xffff) { isCOFFOnly = true; reader.Seek(0); } else { // Might need to handle other formats. Anonymous or LTCG objects, for example. throw new BadImageFormatException(SR.UnknownFileFormat); } } else { isCOFFOnly = false; } if (!isCOFFOnly) { // Skip the DOS Header reader.Seek(PEFileConstants.PESignatureOffsetLocation); int ntHeaderOffset = reader.ReadInt32(); reader.Seek(ntHeaderOffset); // Look for PESignature "PE\0\0" uint ntSignature = reader.ReadUInt32(); if (ntSignature != PEFileConstants.PESignature) { throw new BadImageFormatException(SR.InvalidPESignature); } } } private ImmutableArray<SectionHeader> ReadSectionHeaders(ref PEBinaryReader reader) { int numberOfSections = _coffHeader.NumberOfSections; if (numberOfSections < 0) { throw new BadImageFormatException(SR.InvalidNumberOfSections); } var builder = ImmutableArray.CreateBuilder<SectionHeader>(numberOfSections); for (int i = 0; i < numberOfSections; i++) { builder.Add(new SectionHeader(ref reader)); } return builder.ToImmutable(); } /// <summary> /// Gets the offset (in bytes) from the start of the image to the given directory entry. /// </summary> /// <param name="directory"></param> /// <param name="offset"></param> /// <returns>The section containing the directory could not be found.</returns> /// <exception cref="BadImageFormatException">The section containing the</exception> public bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset) { int sectionIndex = GetContainingSectionIndex(directory.RelativeVirtualAddress); if (sectionIndex < 0) { offset = -1; return false; } int relativeOffset = directory.RelativeVirtualAddress - _sectionHeaders[sectionIndex].VirtualAddress; if (directory.Size > _sectionHeaders[sectionIndex].VirtualSize - relativeOffset) { throw new BadImageFormatException(SR.SectionTooSmall); } offset = _sectionHeaders[sectionIndex].PointerToRawData + relativeOffset; return true; } /// <summary> /// Searches sections of the PE image for the one that contains specified Relative Virtual Address. /// </summary> /// <param name="relativeVirtualAddress">Address.</param> /// <returns> /// Index of the section that contains <paramref name="relativeVirtualAddress"/>, /// or -1 if there is none. /// </returns> public int GetContainingSectionIndex(int relativeVirtualAddress) { for (int i = 0; i < _sectionHeaders.Length; i++) { if (_sectionHeaders[i].VirtualAddress <= relativeVirtualAddress && relativeVirtualAddress < _sectionHeaders[i].VirtualAddress + _sectionHeaders[i].VirtualSize) { return i; } } return -1; } private int IndexOfSection(string name) { for (int i = 0; i < SectionHeaders.Length; i++) { if (SectionHeaders[i].Name.Equals(name, StringComparison.Ordinal)) { return i; } } return -1; } private void CalculateMetadataLocation(long peImageSize, out int start, out int size) { if (IsCoffOnly) { int cormeta = IndexOfSection(".cormeta"); if (cormeta == -1) { start = -1; size = 0; return; } start = SectionHeaders[cormeta].PointerToRawData; size = SectionHeaders[cormeta].SizeOfRawData; } else if (_corHeader == null) { start = 0; size = 0; return; } else { if (!TryGetDirectoryOffset(_corHeader.MetadataDirectory, out start)) { throw new BadImageFormatException(SR.MissingDataDirectory); } size = _corHeader.MetadataDirectory.Size; } if (start < 0 || start >= peImageSize || size <= 0 || start > peImageSize - size) { throw new BadImageFormatException(SR.InvalidMetadataSectionSpan); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; namespace System.IO { /// <summary>Contains internal path helpers that are shared between many projects.</summary> internal static partial class PathInternal { // All paths in Win32 ultimately end up becoming a path to a File object in the Windows object manager. Passed in paths get mapped through // DosDevice symbolic links in the object tree to actual File objects under \Devices. To illustrate, this is what happens with a typical // path "Foo" passed as a filename to any Win32 API: // // 1. "Foo" is recognized as a relative path and is appended to the current directory (say, "C:\" in our example) // 2. "C:\Foo" is prepended with the DosDevice namespace "\??\" // 3. CreateFile tries to create an object handle to the requested file "\??\C:\Foo" // 4. The Object Manager recognizes the DosDevices prefix and looks // a. First in the current session DosDevices ("\Sessions\1\DosDevices\" for example, mapped network drives go here) // b. If not found in the session, it looks in the Global DosDevices ("\GLOBAL??\") // 5. "C:" is found in DosDevices (in our case "\GLOBAL??\C:", which is a symbolic link to "\Device\HarddiskVolume6") // 6. The full path is now "\Device\HarddiskVolume6\Foo", "\Device\HarddiskVolume6" is a File object and parsing is handed off // to the registered parsing method for Files // 7. The registered open method for File objects is invoked to create the file handle which is then returned // // There are multiple ways to directly specify a DosDevices path. The final format of "\??\" is one way. It can also be specified // as "\\.\" (the most commonly documented way) and "\\?\". If the question mark syntax is used the path will skip normalization // (essentially GetFullPathName()) and path length checks. // Windows Kernel-Mode Object Manager // https://msdn.microsoft.com/en-us/library/windows/hardware/ff565763.aspx // https://channel9.msdn.com/Shows/Going+Deep/Windows-NT-Object-Manager // // Introduction to MS-DOS Device Names // https://msdn.microsoft.com/en-us/library/windows/hardware/ff548088.aspx // // Local and Global MS-DOS Device Names // https://msdn.microsoft.com/en-us/library/windows/hardware/ff554302.aspx internal const string ExtendedPathPrefix = @"\\?\"; internal const string UncPathPrefix = @"\\"; internal const string UncExtendedPrefixToInsert = @"?\UNC\"; internal const string UncExtendedPathPrefix = @"\\?\UNC\"; internal const string DevicePathPrefix = @"\\.\"; internal const string ParentDirectoryPrefix = @"..\"; internal const int MaxShortPath = 260; internal const int MaxShortDirectoryPath = 248; internal const int MaxLongPath = short.MaxValue; // \\?\, \\.\, \??\ internal const int DevicePrefixLength = 4; // \\ internal const int UncPrefixLength = 2; // \\?\UNC\, \\.\UNC\ internal const int UncExtendedPrefixLength = 8; internal static readonly int MaxComponentLength = 255; internal static char[] GetInvalidPathChars() => new char[] { '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31 }; // [MS - FSA] 2.1.4.4 Algorithm for Determining if a FileName Is in an Expression // https://msdn.microsoft.com/en-us/library/ff469270.aspx private static readonly char[] s_wildcardChars = { '\"', '<', '>', '*', '?' }; /// <summary> /// Returns true if the given character is a valid drive letter /// </summary> internal static bool IsValidDriveChar(char value) { return ((value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z')); } /// <summary> /// Returns true if the path is too long /// </summary> internal static bool IsPathTooLong(string fullPath) { // We'll never know precisely what will fail as paths get changed internally in Windows and // may grow to exceed MaxLongPath. return fullPath.Length >= MaxLongPath; } /// <summary> /// Returns true if the directory is too long /// </summary> internal static bool IsDirectoryTooLong(string fullPath) { return IsPathTooLong(fullPath); } /// <summary> /// Adds the extended path prefix (\\?\) if not already a device path, IF the path is not relative, /// AND the path is more than 259 characters. (> MAX_PATH + null) /// </summary> internal static string EnsureExtendedPrefixOverMaxPath(string path) { if (path != null && path.Length >= MaxShortPath) { return EnsureExtendedPrefix(path); } else { return path; } } /// <summary> /// Adds the extended path prefix (\\?\) if not relative or already a device path. /// </summary> internal static string EnsureExtendedPrefix(string path) { // Putting the extended prefix on the path changes the processing of the path. It won't get normalized, which // means adding to relative paths will prevent them from getting the appropriate current directory inserted. // If it already has some variant of a device path (\??\, \\?\, \\.\, //./, etc.) we don't need to change it // as it is either correct or we will be changing the behavior. When/if Windows supports long paths implicitly // in the future we wouldn't want normalization to come back and break existing code. // In any case, all internal usages should be hitting normalize path (Path.GetFullPath) before they hit this // shimming method. (Or making a change that doesn't impact normalization, such as adding a filename to a // normalized base path.) if (IsPartiallyQualified(path) || IsDevice(path)) return path; // Given \\server\share in longpath becomes \\?\UNC\server\share if (path.StartsWith(UncPathPrefix, StringComparison.OrdinalIgnoreCase)) return path.Insert(2, PathInternal.UncExtendedPrefixToInsert); return PathInternal.ExtendedPathPrefix + path; } /// <summary> /// Returns true if the path uses any of the DOS device path syntaxes. ("\\.\", "\\?\", or "\??\") /// </summary> internal static bool IsDevice(string path) { // If the path begins with any two separators is will be recognized and normalized and prepped with // "\??\" for internal usage correctly. "\??\" is recognized and handled, "/??/" is not. return IsExtended(path) || ( path.Length >= DevicePrefixLength && IsDirectorySeparator(path[0]) && IsDirectorySeparator(path[1]) && (path[2] == '.' || path[2] == '?') && IsDirectorySeparator(path[3]) ); } /// <summary> /// Returns true if the path uses the canonical form of extended syntax ("\\?\" or "\??\"). If the /// path matches exactly (cannot use alternate directory separators) Windows will skip normalization /// and path length checks. /// </summary> internal static bool IsExtended(string path) { // While paths like "//?/C:/" will work, they're treated the same as "\\.\" paths. // Skipping of normalization will *only* occur if back slashes ('\') are used. return path.Length >= DevicePrefixLength && path[0] == '\\' && (path[1] == '\\' || path[1] == '?') && path[2] == '?' && path[3] == '\\'; } /// <summary> /// Returns a value indicating if the given path contains invalid characters (", &lt;, &gt;, | /// NUL, or any ASCII char whose integer representation is in the range of 1 through 31). /// Does not check for wild card characters ? and *. /// </summary> internal static bool HasIllegalCharacters(string path) { // This is equivalent to IndexOfAny(InvalidPathChars) >= 0, // except faster since IndexOfAny grows slower as the input // array grows larger. // Since we know that some of the characters we're looking // for are contiguous in the alphabet-- the path cannot contain // characters 0-31-- we can optimize this for our specific use // case and use simple comparison operations. for (int i = 0; i < path.Length; i++) { char c = path[i]; if (c <= '\u001f' || c == '|') { return true; } } return false; } /// <summary> /// Check for known wildcard characters. '*' and '?' are the most common ones. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static bool HasWildCardCharacters(string path) { // Question mark is part of dos device syntax so we have to skip if we are int startIndex = PathInternal.IsDevice(path) ? ExtendedPathPrefix.Length : 0; return path.IndexOfAny(s_wildcardChars, startIndex) >= 0; } /// <summary> /// Gets the length of the root of the path (drive, share, etc.). /// </summary> internal unsafe static int GetRootLength(string path) { fixed(char* value = path) { return (int)GetRootLength(value, (uint)path.Length); } } private unsafe static uint GetRootLength(char* path, uint pathLength) { uint i = 0; uint volumeSeparatorLength = 2; // Length to the colon "C:" uint uncRootLength = 2; // Length to the start of the server name "\\" bool extendedSyntax = StartsWithOrdinal(path, pathLength, ExtendedPathPrefix); bool extendedUncSyntax = StartsWithOrdinal(path, pathLength, UncExtendedPathPrefix); if (extendedSyntax) { // Shift the position we look for the root from to account for the extended prefix if (extendedUncSyntax) { // "\\" -> "\\?\UNC\" uncRootLength = (uint)UncExtendedPathPrefix.Length; } else { // "C:" -> "\\?\C:" volumeSeparatorLength += (uint)ExtendedPathPrefix.Length; } } if ((!extendedSyntax || extendedUncSyntax) && pathLength > 0 && IsDirectorySeparator(path[0])) { // UNC or simple rooted path (e.g. "\foo", NOT "\\?\C:\foo") i = 1; // Drive rooted (\foo) is one character if (extendedUncSyntax || (pathLength > 1 && IsDirectorySeparator(path[1]))) { // UNC (\\?\UNC\ or \\), scan past the next two directory separators at most // (e.g. to \\?\UNC\Server\Share or \\Server\Share\) i = uncRootLength; int n = 2; // Maximum separators to skip while (i < pathLength && (!IsDirectorySeparator(path[i]) || --n > 0)) i++; } } else if (pathLength >= volumeSeparatorLength && path[volumeSeparatorLength - 1] == Path.VolumeSeparatorChar) { // Path is at least longer than where we expect a colon, and has a colon (\\?\A:, A:) // If the colon is followed by a directory separator, move past it i = volumeSeparatorLength; if (pathLength >= volumeSeparatorLength + 1 && IsDirectorySeparator(path[volumeSeparatorLength])) i++; } return i; } private unsafe static bool StartsWithOrdinal(char* source, uint sourceLength, string value) { if (sourceLength < (uint)value.Length) return false; for (int i = 0; i < value.Length; i++) { if (value[i] != source[i]) return false; } return true; } /// <summary> /// Returns true if the path specified is relative to the current drive or working directory. /// Returns false if the path is fixed to a specific drive or UNC path. This method does no /// validation of the path (URIs will be returned as relative as a result). /// </summary> /// <remarks> /// Handles paths that use the alternate directory separator. It is a frequent mistake to /// assume that rooted paths (Path.IsPathRooted) are not relative. This isn't the case. /// "C:a" is drive relative- meaning that it will be resolved against the current directory /// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory /// will not be used to modify the path). /// </remarks> internal static bool IsPartiallyQualified(string path) { if (path.Length < 2) { // It isn't fixed, it must be relative. There is no way to specify a fixed // path with one character (or less). return true; } if (IsDirectorySeparator(path[0])) { // There is no valid way to specify a relative path with two initial slashes or // \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\ return !(path[1] == '?' || IsDirectorySeparator(path[1])); } // The only way to specify a fixed path that doesn't begin with two slashes // is the drive, colon, slash format- i.e. C:\ return !((path.Length >= 3) && (path[1] == Path.VolumeSeparatorChar) && IsDirectorySeparator(path[2]) // To match old behavior we'll check the drive character for validity as the path is technically // not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream. && IsValidDriveChar(path[0])); } /// <summary> /// Returns the characters to skip at the start of the path if it starts with space(s) and a drive or directory separator. /// (examples are " C:", " \") /// This is a legacy behavior of Path.GetFullPath(). /// </summary> /// <remarks> /// Note that this conflicts with IsPathRooted() which doesn't (and never did) such a skip. /// </remarks> internal static int PathStartSkip(string path) { int startIndex = 0; while (startIndex < path.Length && path[startIndex] == ' ') startIndex++; if (startIndex > 0 && (startIndex < path.Length && PathInternal.IsDirectorySeparator(path[startIndex])) || (startIndex + 1 < path.Length && path[startIndex + 1] == ':' && PathInternal.IsValidDriveChar(path[startIndex]))) { // Go ahead and skip spaces as we're either " C:" or " \" return startIndex; } return 0; } /// <summary> /// True if the given character is a directory separator. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsDirectorySeparator(char c) { return c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar; } /// <summary> /// Normalize separators in the given path. Converts forward slashes into back slashes and compresses slash runs, keeping initial 2 if present. /// Also trims initial whitespace in front of "rooted" paths (see PathStartSkip). /// /// This effectively replicates the behavior of the legacy NormalizePath when it was called with fullCheck=false and expandShortpaths=false. /// The current NormalizePath gets directory separator normalization from Win32's GetFullPathName(), which will resolve relative paths and as /// such can't be used here (and is overkill for our uses). /// /// Like the current NormalizePath this will not try and analyze periods/spaces within directory segments. /// </summary> /// <remarks> /// The only callers that used to use Path.Normalize(fullCheck=false) were Path.GetDirectoryName() and Path.GetPathRoot(). Both usages do /// not need trimming of trailing whitespace here. /// /// GetPathRoot() could technically skip normalizing separators after the second segment- consider as a future optimization. /// /// For legacy desktop behavior with ExpandShortPaths: /// - It has no impact on GetPathRoot() so doesn't need consideration. /// - It could impact GetDirectoryName(), but only if the path isn't relative (C:\ or \\Server\Share). /// /// In the case of GetDirectoryName() the ExpandShortPaths behavior was undocumented and provided inconsistent results if the path was /// fixed/relative. For example: "C:\PROGRA~1\A.TXT" would return "C:\Program Files" while ".\PROGRA~1\A.TXT" would return ".\PROGRA~1". If you /// ultimately call GetFullPath() this doesn't matter, but if you don't or have any intermediate string handling could easily be tripped up by /// this undocumented behavior. /// /// We won't match this old behavior because: /// /// 1. It was undocumented /// 2. It was costly (extremely so if it actually contained '~') /// 3. Doesn't play nice with string logic /// 4. Isn't a cross-plat friendly concept/behavior /// </remarks> internal static string NormalizeDirectorySeparators(string path) { if (string.IsNullOrEmpty(path)) return path; char current; int start = PathStartSkip(path); if (start == 0) { // Make a pass to see if we need to normalize so we can potentially skip allocating bool normalized = true; for (int i = 0; i < path.Length; i++) { current = path[i]; if (IsDirectorySeparator(current) && (current != Path.DirectorySeparatorChar // Check for sequential separators past the first position (we need to keep initial two for UNC/extended) || (i > 0 && i + 1 < path.Length && IsDirectorySeparator(path[i + 1])))) { normalized = false; break; } } if (normalized) return path; } StringBuilder builder = new StringBuilder(path.Length); if (IsDirectorySeparator(path[start])) { start++; builder.Append(Path.DirectorySeparatorChar); } for (int i = start; i < path.Length; i++) { current = path[i]; // If we have a separator if (IsDirectorySeparator(current)) { // If the next is a separator, skip adding this if (i + 1 < path.Length && IsDirectorySeparator(path[i + 1])) { continue; } // Ensure it is the primary separator current = Path.DirectorySeparatorChar; } builder.Append(current); } return builder.ToString(); } /// <summary> /// Returns true if the character is a directory or volume separator. /// </summary> /// <param name="ch">The character to test.</param> internal static bool IsDirectoryOrVolumeSeparator(char ch) { return PathInternal.IsDirectorySeparator(ch) || Path.VolumeSeparatorChar == ch; } } }
using NSubstitute; using NuKeeper.Abstractions; using NuKeeper.Abstractions.CollaborationModels; using NuKeeper.Abstractions.CollaborationPlatform; using NuKeeper.Abstractions.Configuration; using NuKeeper.Abstractions.Git; using NuKeeper.Abstractions.Logging; using NuKeeper.Collaboration; using NuKeeper.Engine; using NuKeeper.Inspection.Files; using NUnit.Framework; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace NuKeeper.Tests.Engine { [TestFixture] public class CollaborationEngineTests { private IGitRepositoryEngine _repoEngine; private ICollaborationFactory _collaborationFactory; private IFolderFactory _folderFactory; private INuKeeperLogger _logger; private List<RepositorySettings> _disoverableRepositories; [SetUp] public void Initialize() { _repoEngine = Substitute.For<IGitRepositoryEngine>(); _collaborationFactory = Substitute.For<ICollaborationFactory>(); _folderFactory = Substitute.For<IFolderFactory>(); _logger = Substitute.For<INuKeeperLogger>(); _disoverableRepositories = new List<RepositorySettings>(); _collaborationFactory.CollaborationPlatform.GetCurrentUser().Returns(new User("", "", "")); _collaborationFactory.Settings.Returns(new CollaborationPlatformSettings()); _collaborationFactory .RepositoryDiscovery .GetRepositories(Arg.Any<SourceControlServerSettings>()) .Returns(_disoverableRepositories); } [Test] public async Task Run_ExceptionWhenUpdatingRepository_StillTreatsOtherRepositories() { var settings = MakeSettings(); var repoSettingsOne = MakeRepositorySettingsAndAddAsDiscoverable(); var repoSettingsTwo = MakeRepositorySettingsAndAddAsDiscoverable(); _repoEngine .When( r => r.Run( repoSettingsOne, Arg.Any<GitUsernamePasswordCredentials>(), Arg.Any<SettingsContainer>(), Arg.Any<User>() ) ) .Do(r => throw new Exception()); var engine = MakeCollaborationEngine(); try { await engine.Run(settings); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception) { } #pragma warning restore CA1031 // Do not catch general exception types await _repoEngine .Received() .Run( repoSettingsTwo, Arg.Any<GitUsernamePasswordCredentials>(), Arg.Any<SettingsContainer>(), Arg.Any<User>() ); } [Test] public void Run_ExceptionWhenUpdatingRepository_RethrowsException() { var exceptionMessage = "Try again later"; var settings = MakeSettings(); var repoSettingsOne = MakeRepositorySettingsAndAddAsDiscoverable(); var repoSettingsTwo = MakeRepositorySettingsAndAddAsDiscoverable(); _repoEngine .When( r => r.Run( repoSettingsOne, Arg.Any<GitUsernamePasswordCredentials>(), Arg.Any<SettingsContainer>(), Arg.Any<User>() ) ) .Do(r => throw new NuKeeperException(exceptionMessage)); var engine = MakeCollaborationEngine(); var ex = Assert.ThrowsAsync<NuKeeperException>(() => engine.Run(settings)); var innerEx = ex.InnerException as NuKeeperException; Assert.IsNotNull(innerEx); Assert.AreEqual(exceptionMessage, innerEx.Message); } [Test] public void Run_MultipleExceptionsWhenUpdatingRepositories_AreFlattened() { var settings = MakeSettings(); var repoSettingsOne = MakeRepositorySettingsAndAddAsDiscoverable(); var repoSettingsTwo = MakeRepositorySettingsAndAddAsDiscoverable(); var repoSettingsThree = MakeRepositorySettingsAndAddAsDiscoverable(); _repoEngine .When( r => r.Run( repoSettingsOne, Arg.Any<GitUsernamePasswordCredentials>(), Arg.Any<SettingsContainer>(), Arg.Any<User>() ) ) .Do(r => throw new InvalidOperationException("Repo 1 failed!")); _repoEngine .When( r => r.Run( repoSettingsThree, Arg.Any<GitUsernamePasswordCredentials>(), Arg.Any<SettingsContainer>(), Arg.Any<User>() ) ) .Do(r => throw new TaskCanceledException("Repo 3 failed!")); var engine = MakeCollaborationEngine(); var ex = Assert.ThrowsAsync<NuKeeperException>(() => engine.Run(settings)); var aggregateEx = ex.InnerException as AggregateException; var exceptions = aggregateEx?.InnerExceptions; Assert.IsNotNull(aggregateEx); Assert.IsNotNull(exceptions); Assert.AreEqual(2, exceptions.Count); Assert.That(exceptions, Has.One.InstanceOf(typeof(InvalidOperationException))); Assert.That(exceptions, Has.One.InstanceOf(typeof(TaskCanceledException))); } [Test] public async Task SuccessCaseWithNoRepos() { var engine = MakeCollaborationEngine( new List<RepositorySettings>()); var count = await engine.Run(MakeSettings()); Assert.That(count, Is.EqualTo(0)); } [Test] public async Task SuccessCaseWithOneRepo() { var oneRepo = new List<RepositorySettings> { new RepositorySettings() }; var engine = MakeCollaborationEngine(oneRepo); var count = await engine.Run(MakeSettings()); Assert.That(count, Is.EqualTo(1)); } [Test] public async Task SuccessCaseWithTwoRepos() { var repos = new List<RepositorySettings> { new RepositorySettings(), new RepositorySettings() }; var engine = MakeCollaborationEngine(repos); var count = await engine.Run(MakeSettings()); Assert.That(count, Is.EqualTo(2)); } [Test] public async Task SuccessCaseWithTwoReposAndTwoPrsPerRepo() { var repos = new List<RepositorySettings> { new RepositorySettings(), new RepositorySettings() }; var engine = MakeCollaborationEngine(2, repos); var count = await engine.Run(MakeSettings()); Assert.That(count, Is.EqualTo(2)); } [Test] public async Task CountIsNotIncrementedWhenRepoEngineFails() { var repos = new List<RepositorySettings> { new RepositorySettings(), new RepositorySettings(), new RepositorySettings() }; var engine = MakeCollaborationEngine(0, repos); var count = await engine.Run(MakeSettings()); Assert.That(count, Is.EqualTo(0)); } [Test] public async Task WhenThereIsAMaxNumberOfRepos() { var repos = new List<RepositorySettings> { new RepositorySettings(), new RepositorySettings(), new RepositorySettings() }; var engine = MakeCollaborationEngine(1, repos); var settings = new SettingsContainer { UserSettings = new UserSettings { MaxRepositoriesChanged = 1 }, SourceControlServerSettings = MakeServerSettings() }; var count = await engine.Run(settings); Assert.That(count, Is.EqualTo(1)); } private ICollaborationEngine MakeCollaborationEngine() { return new CollaborationEngine( _collaborationFactory, _repoEngine, _folderFactory, _logger ); } private RepositorySettings MakeRepositorySettingsAndAddAsDiscoverable() { var repositorySettings = new RepositorySettings(); _disoverableRepositories.Add(repositorySettings); return repositorySettings; } private static CollaborationEngine MakeCollaborationEngine( List<RepositorySettings> repos) { return MakeCollaborationEngine(1, repos); } private static CollaborationEngine MakeCollaborationEngine( int repoEngineResult, List<RepositorySettings> repos) { var collaborationFactory = Substitute.For<ICollaborationFactory>(); var repoEngine = Substitute.For<IGitRepositoryEngine>(); var folders = Substitute.For<IFolderFactory>(); var user = new User("testUser", "Testy", "testuser@test.com"); collaborationFactory.CollaborationPlatform.GetCurrentUser().Returns(user); collaborationFactory.Settings.Returns(new CollaborationPlatformSettings()); collaborationFactory.RepositoryDiscovery.GetRepositories(Arg.Any<SourceControlServerSettings>()).Returns(repos); repoEngine.Run(null, null, null, null).ReturnsForAnyArgs(repoEngineResult); var engine = new CollaborationEngine(collaborationFactory, repoEngine, folders, Substitute.For<INuKeeperLogger>()); return engine; } private static SettingsContainer MakeSettings() { return new SettingsContainer { UserSettings = MakeUserSettings(), SourceControlServerSettings = MakeServerSettings() }; } private static SourceControlServerSettings MakeServerSettings() { return new SourceControlServerSettings { Scope = ServerScope.Repository }; } private static UserSettings MakeUserSettings() { return new UserSettings { MaxRepositoriesChanged = int.MaxValue }; } } }
using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Engines { /** * HC-128 is a software-efficient stream cipher created by Hongjun Wu. It * generates keystream from a 128-bit secret key and a 128-bit initialization * vector. * <p> * http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf * </p><p> * It is a third phase candidate in the eStream contest, and is patent-free. * No attacks are known as of today (April 2007). See * * http://www.ecrypt.eu.org/stream/hcp3.html * </p> */ public class HC128Engine : IStreamCipher { private uint[] p = new uint[512]; private uint[] q = new uint[512]; private uint cnt = 0; private static uint F1(uint x) { return RotateRight(x, 7) ^ RotateRight(x, 18) ^ (x >> 3); } private static uint F2(uint x) { return RotateRight(x, 17) ^ RotateRight(x, 19) ^ (x >> 10); } private uint G1(uint x, uint y, uint z) { return (RotateRight(x, 10) ^ RotateRight(z, 23)) + RotateRight(y, 8); } private uint G2(uint x, uint y, uint z) { return (RotateLeft(x, 10) ^ RotateLeft(z, 23)) + RotateLeft(y, 8); } private static uint RotateLeft(uint x, int bits) { return (x << bits) | (x >> -bits); } private static uint RotateRight(uint x, int bits) { return (x >> bits) | (x << -bits); } private uint H1(uint x) { return q[x & 0xFF] + q[((x >> 16) & 0xFF) + 256]; } private uint H2(uint x) { return p[x & 0xFF] + p[((x >> 16) & 0xFF) + 256]; } private static uint Mod1024(uint x) { return x & 0x3FF; } private static uint Mod512(uint x) { return x & 0x1FF; } private static uint Dim(uint x, uint y) { return Mod512(x - y); } private uint Step() { uint j = Mod512(cnt); uint ret; if (cnt < 512) { p[j] += G1(p[Dim(j, 3)], p[Dim(j, 10)], p[Dim(j, 511)]); ret = H1(p[Dim(j, 12)]) ^ p[j]; } else { q[j] += G2(q[Dim(j, 3)], q[Dim(j, 10)], q[Dim(j, 511)]); ret = H2(q[Dim(j, 12)]) ^ q[j]; } cnt = Mod1024(cnt + 1); return ret; } private byte[] key, iv; private bool initialised; private void Init() { if (key.Length != 16) throw new ArgumentException("The key must be 128 bits long"); cnt = 0; uint[] w = new uint[1280]; for (int i = 0; i < 16; i++) { w[i >> 2] |= ((uint)key[i] << (8 * (i & 0x3))); } Array.Copy(w, 0, w, 4, 4); for (int i = 0; i < iv.Length && i < 16; i++) { w[(i >> 2) + 8] |= ((uint)iv[i] << (8 * (i & 0x3))); } Array.Copy(w, 8, w, 12, 4); for (uint i = 16; i < 1280; i++) { w[i] = F2(w[i - 2]) + w[i - 7] + F1(w[i - 15]) + w[i - 16] + i; } Array.Copy(w, 256, p, 0, 512); Array.Copy(w, 768, q, 0, 512); for (int i = 0; i < 512; i++) { p[i] = Step(); } for (int i = 0; i < 512; i++) { q[i] = Step(); } cnt = 0; } public string AlgorithmName { get { return "HC-128"; } } /** * Initialise a HC-128 cipher. * * @param forEncryption whether or not we are for encryption. Irrelevant, as * encryption and decryption are the same. * @param params the parameters required to set up the cipher. * @throws ArgumentException if the params argument is * inappropriate (ie. the key is not 128 bit long). */ public void Init( bool forEncryption, ICipherParameters parameters) { ICipherParameters keyParam = parameters; if (parameters is ParametersWithIV) { iv = ((ParametersWithIV)parameters).GetIV(); keyParam = ((ParametersWithIV)parameters).Parameters; } else { iv = new byte[0]; } if (keyParam is KeyParameter) { key = ((KeyParameter)keyParam).GetKey(); Init(); } else { throw new ArgumentException( "Invalid parameter passed to HC128 init - " + parameters.GetType().Name, "parameters"); } initialised = true; } private byte[] buf = new byte[4]; private int idx = 0; private byte GetByte() { if (idx == 0) { Pack.UInt32_To_LE(Step(), buf); } byte ret = buf[idx]; idx = idx + 1 & 0x3; return ret; } public void ProcessBytes( byte[] input, int inOff, int len, byte[] output, int outOff) { if (!initialised) throw new InvalidOperationException(AlgorithmName + " not initialised"); if ((inOff + len) > input.Length) throw new DataLengthException("input buffer too short"); if ((outOff + len) > output.Length) throw new DataLengthException("output buffer too short"); for (int i = 0; i < len; i++) { output[outOff + i] = (byte)(input[inOff + i] ^ GetByte()); } } public void Reset() { idx = 0; Init(); } public byte ReturnByte(byte input) { return (byte)(input ^ GetByte()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using Microsoft.Win32.SafeHandles; namespace System { /// <summary>Provides access to and processing of a terminfo database.</summary> internal static class TermInfo { internal enum WellKnownNumbers { Columns = 0, Lines = 2, MaxColors = 13, } internal enum WellKnownStrings { Bell = 1, Clear = 5, CursorAddress = 10, CursorLeft = 14, CursorPositionReport = 294, OrigPairs = 297, OrigColors = 298, SetAnsiForeground = 359, SetAnsiBackground = 360, CursorInvisible = 13, CursorVisible = 16, FromStatusLine = 47, ToStatusLine = 135, KeyBackspace = 55, KeyClear = 57, KeyDelete = 59, KeyDown = 61, KeyF1 = 66, KeyF10 = 67, KeyF2 = 68, KeyF3 = 69, KeyF4 = 70, KeyF5 = 71, KeyF6 = 72, KeyF7 = 73, KeyF8 = 74, KeyF9 = 75, KeyHome = 76, KeyInsert = 77, KeyLeft = 79, KeyPageDown = 81, KeyPageUp = 82, KeyRight = 83, KeyScrollForward = 84, KeyScrollReverse = 85, KeyUp = 87, KeypadXmit = 89, KeyBackTab = 148, KeyBegin = 158, KeyEnd = 164, KeyEnter = 165, KeyHelp = 168, KeyPrint = 176, KeySBegin = 186, KeySDelete = 191, KeySelect = 193, KeySHelp = 198, KeySHome = 199, KeySLeft = 201, KeySPrint = 207, KeySRight = 210, KeyF11 = 216, KeyF12 = 217, KeyF13 = 218, KeyF14 = 219, KeyF15 = 220, KeyF16 = 221, KeyF17 = 222, KeyF18 = 223, KeyF19 = 224, KeyF20 = 225, KeyF21 = 226, KeyF22 = 227, KeyF23 = 228, KeyF24 = 229, } /// <summary>Provides a terminfo database.</summary> internal sealed class Database { /// <summary>The name of the terminfo file.</summary> private readonly string _term; /// <summary>Raw data of the database instance.</summary> private readonly byte[] _data; /// <summary>The number of bytes in the names section of the database.</summary> private readonly int _nameSectionNumBytes; /// <summary>The number of bytes in the Booleans section of the database.</summary> private readonly int _boolSectionNumBytes; /// <summary>The number of shorts in the numbers section of the database.</summary> private readonly int _numberSectionNumShorts; /// <summary>The number of offsets in the strings section of the database.</summary> private readonly int _stringSectionNumOffsets; /// <summary>The number of bytes in the strings table of the database.</summary> private readonly int _stringTableNumBytes; /// <summary>Extended / user-defined entries in the terminfo database.</summary> private readonly Dictionary<string, string> _extendedStrings; /// <summary>Initializes the database instance.</summary> /// <param name="term">The name of the terminal.</param> /// <param name="data">The data from the terminfo file.</param> private Database(string term, byte[] data) { _term = term; _data = data; // See "man term" for the file format. if (ReadInt16(data, 0) != 0x11A) // magic number octal 0432 { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } _nameSectionNumBytes = ReadInt16(data, 2); _boolSectionNumBytes = ReadInt16(data, 4); _numberSectionNumShorts = ReadInt16(data, 6); _stringSectionNumOffsets = ReadInt16(data, 8); _stringTableNumBytes = ReadInt16(data, 10); if (_nameSectionNumBytes < 0 || _boolSectionNumBytes < 0 || _numberSectionNumShorts < 0 || _stringSectionNumOffsets < 0 || _stringTableNumBytes < 0) { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } // In addition to the main section of bools, numbers, and strings, there is also // an "extended" section. This section contains additional entries that don't // have well-known indices, and are instead named mappings. As such, we parse // all of this data now rather than on each request, as the mapping is fairly complicated. // This function relies on the data stored above, so it's the last thing we run. // (Note that the extended section also includes other Booleans and numbers, but we don't // have any need for those now, so we don't parse them.) int extendedBeginning = RoundUpToEven(StringsTableOffset + _stringTableNumBytes); _extendedStrings = ParseExtendedStrings(data, extendedBeginning) ?? new Dictionary<string, string>(); } /// <summary>The name of the associated terminfo, if any.</summary> public string Term { get { return _term; } } /// <summary>Read the database for the current terminal as specified by the "TERM" environment variable.</summary> /// <returns>The database, or null if it could not be found.</returns> internal static Database ReadActiveDatabase() { string term = Environment.GetEnvironmentVariable("TERM"); return !string.IsNullOrEmpty(term) ? ReadDatabase(term) : null; } /// <summary> /// The default locations in which to search for terminfo databases. /// This is the ordering of well-known locations used by ncurses. /// </summary> private static readonly string[] _terminfoLocations = new string[] { "/etc/terminfo", "/lib/terminfo", "/usr/share/terminfo", }; /// <summary>Read the database for the specified terminal.</summary> /// <param name="term">The identifier for the terminal.</param> /// <returns>The database, or null if it could not be found.</returns> private static Database ReadDatabase(string term) { // This follows the same search order as prescribed by ncurses. Database db; // First try a location specified in the TERMINFO environment variable. string terminfo = Environment.GetEnvironmentVariable("TERMINFO"); if (!string.IsNullOrWhiteSpace(terminfo) && (db = ReadDatabase(term, terminfo)) != null) { return db; } // Then try in the user's home directory. string home = PersistedFiles.GetHomeDirectory(); if (!string.IsNullOrWhiteSpace(home) && (db = ReadDatabase(term, home + "/.terminfo")) != null) { return db; } // Then try a set of well-known locations. foreach (string terminfoLocation in _terminfoLocations) { if ((db = ReadDatabase(term, terminfoLocation)) != null) { return db; } } // Couldn't find one return null; } /// <summary>Attempt to open as readonly the specified file path.</summary> /// <param name="filePath">The path to the file to open.</param> /// <param name="fd">If successful, the opened file descriptor; otherwise, -1.</param> /// <returns>true if the file was successfully opened; otherwise, false.</returns> private static bool TryOpen(string filePath, out SafeFileHandle fd) { fd = Interop.Sys.Open(filePath, Interop.Sys.OpenFlags.O_RDONLY, 0); if (fd.IsInvalid) { // Don't throw in this case, as we'll be polling multiple locations looking for the file. fd = null; return false; } return true; } /// <summary>Read the database for the specified terminal from the specified directory.</summary> /// <param name="term">The identifier for the terminal.</param> /// <param name="directoryPath">The path to the directory containing terminfo database files.</param> /// <returns>The database, or null if it could not be found.</returns> private static Database ReadDatabase(string term, string directoryPath) { if (string.IsNullOrEmpty(term) || string.IsNullOrEmpty(directoryPath)) { return null; } SafeFileHandle fd; if (!TryOpen(directoryPath + "/" + term[0].ToString() + "/" + term, out fd) && // /directory/termFirstLetter/term (Linux) !TryOpen(directoryPath + "/" + ((int)term[0]).ToString("X") + "/" + term, out fd)) // /directory/termFirstLetterAsHex/term (Mac) { return null; } using (fd) { // Read in all of the terminfo data long termInfoLength = Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_END)); // jump to the end to get the file length Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_SET)); // reset back to beginning const int MaxTermInfoLength = 4096; // according to the term and tic man pages, 4096 is the terminfo file size max const int HeaderLength = 12; if (termInfoLength <= HeaderLength || termInfoLength > MaxTermInfoLength) { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } int fileLen = (int)termInfoLength; byte[] data = new byte[fileLen]; if (ConsolePal.Read(fd, data, 0, fileLen) != fileLen) { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } // Create the database from the data return new Database(term, data); } } /// <summary>The offset into data where the names section begins.</summary> private const int NamesOffset = 12; // comes right after the header, which is always 12 bytes /// <summary>The offset into data where the Booleans section begins.</summary> private int BooleansOffset { get { return NamesOffset + _nameSectionNumBytes; } } // after the names section /// <summary>The offset into data where the numbers section begins.</summary> private int NumbersOffset { get { return RoundUpToEven(BooleansOffset + _boolSectionNumBytes); } } // after the Booleans section, at an even position /// <summary> /// The offset into data where the string offsets section begins. We index into this section /// to find the location within the strings table where a string value exists. /// </summary> private int StringOffsetsOffset { get { return NumbersOffset + (_numberSectionNumShorts * 2); } } /// <summary>The offset into data where the string table exists.</summary> private int StringsTableOffset { get { return StringOffsetsOffset + (_stringSectionNumOffsets * 2); } } /// <summary>Gets a string from the strings section by the string's well-known index.</summary> /// <param name="stringTableIndex">The index of the string to find.</param> /// <returns>The string if it's in the database; otherwise, null.</returns> public string GetString(WellKnownStrings stringTableIndex) { int index = (int)stringTableIndex; Debug.Assert(index >= 0); if (index >= _stringSectionNumOffsets) { // Some terminfo files may not contain enough entries to actually // have the requested one. return null; } int tableIndex = ReadInt16(_data, StringOffsetsOffset + (index * 2)); if (tableIndex == -1) { // Some terminfo files may have enough entries, but may not actually // have it filled in for this particular string. return null; } return ReadString(_data, StringsTableOffset + tableIndex); } /// <summary>Gets a string from the extended strings section.</summary> /// <param name="name">The name of the string as contained in the extended names section.</param> /// <returns>The string if it's in the database; otherwise, null.</returns> public string GetExtendedString(string name) { Debug.Assert(name != null); string value; return _extendedStrings.TryGetValue(name, out value) ? value : null; } /// <summary>Gets a number from the numbers section by the number's well-known index.</summary> /// <param name="numberIndex">The index of the string to find.</param> /// <returns>The number if it's in the database; otherwise, -1.</returns> public int GetNumber(WellKnownNumbers numberIndex) { int index = (int)numberIndex; Debug.Assert(index >= 0); if (index >= _numberSectionNumShorts) { // Some terminfo files may not contain enough entries to actually // have the requested one. return -1; } return ReadInt16(_data, NumbersOffset + (index * 2)); } /// <summary>Parses the extended string information from the terminfo data.</summary> /// <returns> /// A dictionary of the name to value mapping. As this section of the terminfo isn't as well /// defined as the earlier portions, and may not even exist, the parsing is more lenient about /// errors, returning an empty collection rather than throwing. /// </returns> private static Dictionary<string, string> ParseExtendedStrings(byte[] data, int extendedBeginning) { const int ExtendedHeaderSize = 10; if (extendedBeginning + ExtendedHeaderSize >= data.Length) { // Exit out as there's no extended information. return null; } // Read in extended counts, and exit out if we got any incorrect info int extendedBoolCount = ReadInt16(data, extendedBeginning); int extendedNumberCount = ReadInt16(data, extendedBeginning + 2); int extendedStringCount = ReadInt16(data, extendedBeginning + 4); int extendedStringNumOffsets = ReadInt16(data, extendedBeginning + 6); int extendedStringTableByteSize = ReadInt16(data, extendedBeginning + 8); if (extendedBoolCount < 0 || extendedNumberCount < 0 || extendedStringCount < 0 || extendedStringNumOffsets < 0 || extendedStringTableByteSize < 0) { // The extended header contained invalid data. Bail. return null; } // Skip over the extended bools. We don't need them now and can add this in later // if needed. Also skip over extended numbers, for the same reason. // Get the location where the extended string offsets begin. These point into // the extended string table. int extendedOffsetsStart = extendedBeginning + // go past the normal data ExtendedHeaderSize + // and past the extended header RoundUpToEven(extendedBoolCount) + // and past all of the extended Booleans (extendedNumberCount * 2); // and past all of the extended numbers // Get the location where the extended string table begins. This area contains // null-terminated strings. int extendedStringTableStart = extendedOffsetsStart + (extendedStringCount * 2) + // and past all of the string offsets ((extendedBoolCount + extendedNumberCount + extendedStringCount) * 2); // and past all of the name offsets // Get the location where the extended string table ends. We shouldn't read past this. int extendedStringTableEnd = extendedStringTableStart + extendedStringTableByteSize; if (extendedStringTableEnd > data.Length) { // We don't have enough data to parse everything. Bail. return null; } // Now we need to parse all of the extended string values. These aren't necessarily // "in order", meaning the offsets aren't guaranteed to be increasing. Instead, we parse // the offsets in order, pulling out each string it references and storing them into our // results list in the order of the offsets. var values = new List<string>(extendedStringCount); int lastEnd = 0; for (int i = 0; i < extendedStringCount; i++) { int offset = extendedStringTableStart + ReadInt16(data, extendedOffsetsStart + (i * 2)); if (offset < 0 || offset >= data.Length) { // If the offset is invalid, bail. return null; } // Add the string int end = FindNullTerminator(data, offset); values.Add(Encoding.ASCII.GetString(data, offset, end - offset)); // Keep track of where the last string ends. The name strings will come after that. lastEnd = Math.Max(end, lastEnd); } // Now parse all of the names. var names = new List<string>(extendedBoolCount + extendedNumberCount + extendedStringCount); for (int pos = lastEnd + 1; pos < extendedStringTableEnd; pos++) { int end = FindNullTerminator(data, pos); names.Add(Encoding.ASCII.GetString(data, pos, end - pos)); pos = end; } // The names are in order for the Booleans, then the numbers, and then the strings. // Skip over the bools and numbers, and associate the names with the values. var extendedStrings = new Dictionary<string, string>(extendedStringCount); for (int iName = extendedBoolCount + extendedNumberCount, iValue = 0; iName < names.Count && iValue < values.Count; iName++, iValue++) { extendedStrings.Add(names[iName], values[iValue]); } return extendedStrings; } private static int RoundUpToEven(int i) { return i % 2 == 1 ? i + 1 : i; } /// <summary>Read a 16-bit value from the buffer starting at the specified position.</summary> /// <param name="buffer">The buffer from which to read.</param> /// <param name="pos">The position at which to read.</param> /// <returns>The 16-bit value read.</returns> private static short ReadInt16(byte[] buffer, int pos) { return (short) ((((int)buffer[pos + 1]) << 8) | ((int)buffer[pos] & 0xff)); } /// <summary>Reads a string from the buffer starting at the specified position.</summary> /// <param name="buffer">The buffer from which to read.</param> /// <param name="pos">The position at which to read.</param> /// <returns>The string read from the specified position.</returns> private static string ReadString(byte[] buffer, int pos) { int end = FindNullTerminator(buffer, pos); return Encoding.ASCII.GetString(buffer, pos, end - pos); } /// <summary>Finds the null-terminator for a string that begins at the specified position.</summary> private static int FindNullTerminator(byte[] buffer, int pos) { int termPos = pos; while (termPos < buffer.Length && buffer[termPos] != '\0') termPos++; return termPos; } } /// <summary>Provides support for evaluating parameterized terminfo database format strings.</summary> internal static class ParameterizedStrings { /// <summary>A cached stack to use to avoid allocating a new stack object for every evaluation.</summary> [ThreadStatic] private static LowLevelStack<FormatParam> t_cachedStack; /// <summary>A cached array of arguments to use to avoid allocating a new array object for every evaluation.</summary> [ThreadStatic] private static FormatParam[] t_cachedOneElementArgsArray; /// <summary>A cached array of arguments to use to avoid allocating a new array object for every evaluation.</summary> [ThreadStatic] private static FormatParam[] t_cachedTwoElementArgsArray; /// <summary>Evaluates a terminfo formatting string, using the supplied argument.</summary> /// <param name="format">The format string.</param> /// <param name="arg">The argument to the format string.</param> /// <returns>The formatted string.</returns> public static string Evaluate(string format, FormatParam arg) { FormatParam[] args = t_cachedOneElementArgsArray; if (args == null) { t_cachedOneElementArgsArray = args = new FormatParam[1]; } args[0] = arg; return Evaluate(format, args); } /// <summary>Evaluates a terminfo formatting string, using the supplied arguments.</summary> /// <param name="format">The format string.</param> /// <param name="arg1">The first argument to the format string.</param> /// <param name="arg2">The second argument to the format string.</param> /// <returns>The formatted string.</returns> public static string Evaluate(string format, FormatParam arg1, FormatParam arg2) { FormatParam[] args = t_cachedTwoElementArgsArray; if (args == null) { t_cachedTwoElementArgsArray = args = new FormatParam[2]; } args[0] = arg1; args[1] = arg2; return Evaluate(format, args); } /// <summary>Evaluates a terminfo formatting string, using the supplied arguments.</summary> /// <param name="format">The format string.</param> /// <param name="args">The arguments to the format string.</param> /// <returns>The formatted string.</returns> public static string Evaluate(string format, params FormatParam[] args) { if (format == null) { throw new ArgumentNullException(nameof(format)); } if (args == null) { throw new ArgumentNullException(nameof(args)); } // Initialize the stack to use for processing. LowLevelStack<FormatParam> stack = t_cachedStack; if (stack == null) { t_cachedStack = stack = new LowLevelStack<FormatParam>(); } else { stack.Clear(); } // "dynamic" and "static" variables are much less often used (the "dynamic" and "static" // terminology appears to just refer to two different collections rather than to any semantic // meaning). As such, we'll only initialize them if we really need them. FormatParam[] dynamicVars = null, staticVars = null; int pos = 0; return EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars); // EvaluateInternal may throw IndexOutOfRangeException and InvalidOperationException // if the format string is malformed or if it's inconsistent with the parameters provided. } /// <summary>Evaluates a terminfo formatting string, using the supplied arguments and processing data structures.</summary> /// <param name="format">The format string.</param> /// <param name="pos">The position in <paramref name="format"/> to start processing.</param> /// <param name="args">The arguments to the format string.</param> /// <param name="stack">The stack to use as the format string is evaluated.</param> /// <param name="dynamicVars">A lazily-initialized collection of variables.</param> /// <param name="staticVars">A lazily-initialized collection of variables.</param> /// <returns> /// The formatted string; this may be empty if the evaluation didn't yield any output. /// The evaluation stack will have a 1 at the top if all processing was completed at invoked level /// of recursion, and a 0 at the top if we're still inside of a conditional that requires more processing. /// </returns> private static string EvaluateInternal( string format, ref int pos, FormatParam[] args, LowLevelStack<FormatParam> stack, ref FormatParam[] dynamicVars, ref FormatParam[] staticVars) { // Create a StringBuilder to store the output of this processing. We use the format's length as an // approximation of an upper-bound for how large the output will be, though with parameter processing, // this is just an estimate, sometimes way over, sometimes under. StringBuilder output = StringBuilderCache.Acquire(format.Length); // Format strings support conditionals, including the equivalent of "if ... then ..." and // "if ... then ... else ...", as well as "if ... then ... else ... then ..." // and so on, where an else clause can not only be evaluated for string output but also // as a conditional used to determine whether to evaluate a subsequent then clause. // We use recursion to process these subsequent parts, and we track whether we're processing // at the same level of the initial if clause (or whether we're nested). bool sawIfConditional = false; // Process each character in the format string, starting from the position passed in. for (; pos < format.Length; pos++) { // '%' is the escape character for a special sequence to be evaluated. // Anything else just gets pushed to output. if (format[pos] != '%') { output.Append(format[pos]); continue; } // We have a special parameter sequence to process. Now we need // to look at what comes after the '%'. ++pos; switch (format[pos]) { // Output appending operations case '%': // Output the escaped '%' output.Append('%'); break; case 'c': // Pop the stack and output it as a char output.Append((char)stack.Pop().Int32); break; case 's': // Pop the stack and output it as a string output.Append(stack.Pop().String); break; case 'd': // Pop the stack and output it as an integer output.Append(stack.Pop().Int32); break; case 'o': case 'X': case 'x': case ':': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // printf strings of the format "%[[:]flags][width[.precision]][doxXs]" are allowed // (with a ':' used in front of flags to help differentiate from binary operations, as flags can // include '-' and '+'). While above we've special-cased common usage (e.g. %d, %s), // for more complicated expressions we delegate to printf. int printfEnd = pos; for (; printfEnd < format.Length; printfEnd++) // find the end of the printf format string { char ec = format[printfEnd]; if (ec == 'd' || ec == 'o' || ec == 'x' || ec == 'X' || ec == 's') { break; } } if (printfEnd >= format.Length) { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } string printfFormat = format.Substring(pos - 1, printfEnd - pos + 2); // extract the format string if (printfFormat.Length > 1 && printfFormat[1] == ':') { printfFormat = printfFormat.Remove(1, 1); } output.Append(FormatPrintF(printfFormat, stack.Pop().Object)); // do the printf formatting and append its output break; // Stack pushing operations case 'p': // Push the specified parameter (1-based) onto the stack pos++; Debug.Assert(format[pos] >= '0' && format[pos] <= '9'); stack.Push(args[format[pos] - '1']); break; case 'l': // Pop a string and push its length stack.Push(stack.Pop().String.Length); break; case '{': // Push integer literal, enclosed between braces pos++; int intLit = 0; while (format[pos] != '}') { Debug.Assert(format[pos] >= '0' && format[pos] <= '9'); intLit = (intLit * 10) + (format[pos] - '0'); pos++; } stack.Push(intLit); break; case '\'': // Push literal character, enclosed between single quotes stack.Push((int)format[pos + 1]); Debug.Assert(format[pos + 2] == '\''); pos += 2; break; // Storing and retrieving "static" and "dynamic" variables case 'P': // Pop a value and store it into either static or dynamic variables based on whether the a-z variable is capitalized pos++; int setIndex; FormatParam[] targetVars = GetDynamicOrStaticVariables(format[pos], ref dynamicVars, ref staticVars, out setIndex); targetVars[setIndex] = stack.Pop(); break; case 'g': // Push a static or dynamic variable; which is based on whether the a-z variable is capitalized pos++; int getIndex; FormatParam[] sourceVars = GetDynamicOrStaticVariables(format[pos], ref dynamicVars, ref staticVars, out getIndex); stack.Push(sourceVars[getIndex]); break; // Binary operations case '+': case '-': case '*': case '/': case 'm': case '^': // arithmetic case '&': case '|': // bitwise case '=': case '>': case '<': // comparison case 'A': case 'O': // logical int second = stack.Pop().Int32; // it's a stack... the second value was pushed last int first = stack.Pop().Int32; char c = format[pos]; stack.Push( c == '+' ? (first + second) : c == '-' ? (first - second) : c == '*' ? (first * second) : c == '/' ? (first / second) : c == 'm' ? (first % second) : c == '^' ? (first ^ second) : c == '&' ? (first & second) : c == '|' ? (first | second) : c == '=' ? AsInt(first == second) : c == '>' ? AsInt(first > second) : c == '<' ? AsInt(first < second) : c == 'A' ? AsInt(AsBool(first) && AsBool(second)) : c == 'O' ? AsInt(AsBool(first) || AsBool(second)) : 0); // not possible; we just validated above break; // Unary operations case '!': case '~': int value = stack.Pop().Int32; stack.Push( format[pos] == '!' ? AsInt(!AsBool(value)) : ~value); break; // Some terminfo files appear to have a fairly liberal interpretation of %i. The spec states that %i increments the first two arguments, // but some uses occur when there's only a single argument. To make sure we accomodate these files, we increment the values // of up to (but not requiring) two arguments. case 'i': if (args.Length > 0) { args[0] = 1 + args[0].Int32; if (args.Length > 1) args[1] = 1 + args[1].Int32; } break; // Conditional of the form %? if-part %t then-part %e else-part %; // The "%e else-part" is optional. case '?': sawIfConditional = true; break; case 't': // We hit the end of the if-part and are about to start the then-part. // The if-part left its result on the stack; pop and evaluate. bool conditionalResult = AsBool(stack.Pop().Int32); // Regardless of whether it's true, run the then-part to get past it. // If the conditional was true, output the then results. pos++; string thenResult = EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars); if (conditionalResult) { output.Append(thenResult); } Debug.Assert(format[pos] == 'e' || format[pos] == ';'); // We're past the then; the top of the stack should now be a Boolean // indicating whether this conditional has more to be processed (an else clause). if (!AsBool(stack.Pop().Int32)) { // Process the else clause, and if the conditional was false, output the else results. pos++; string elseResult = EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars); if (!conditionalResult) { output.Append(elseResult); } // Now we should be done (any subsequent elseif logic will have been handled in the recursive call). if (!AsBool(stack.Pop().Int32)) { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } } // If we're in a nested processing, return to our parent. if (!sawIfConditional) { stack.Push(1); return StringBuilderCache.GetStringAndRelease(output); } // Otherwise, we're done processing the conditional in its entirety. sawIfConditional = false; break; case 'e': case ';': // Let our caller know why we're exiting, whether due to the end of the conditional or an else branch. stack.Push(AsInt(format[pos] == ';')); return StringBuilderCache.GetStringAndRelease(output); // Anything else is an error default: throw new InvalidOperationException(SR.IO_TermInfoInvalid); } } stack.Push(1); return StringBuilderCache.GetStringAndRelease(output); } /// <summary>Converts an Int32 to a Boolean, with 0 meaning false and all non-zero values meaning true.</summary> /// <param name="i">The integer value to convert.</param> /// <returns>true if the integer was non-zero; otherwise, false.</returns> private static bool AsBool(Int32 i) { return i != 0; } /// <summary>Converts a Boolean to an Int32, with true meaning 1 and false meaning 0.</summary> /// <param name="b">The Boolean value to convert.</param> /// <returns>1 if the Boolean is true; otherwise, 0.</returns> private static int AsInt(bool b) { return b ? 1 : 0; } /// <summary>Formats an argument into a printf-style format string.</summary> /// <param name="format">The printf-style format string.</param> /// <param name="arg">The argument to format. This must be an Int32 or a String.</param> /// <returns>The formatted string.</returns> private static unsafe string FormatPrintF(string format, object arg) { Debug.Assert(arg is string || arg is Int32); // Determine how much space is needed to store the formatted string. string stringArg = arg as string; int neededLength = stringArg != null ? Interop.Sys.SNPrintF(null, 0, format, stringArg) : Interop.Sys.SNPrintF(null, 0, format, (int)arg); if (neededLength == 0) { return string.Empty; } if (neededLength < 0) { throw new InvalidOperationException(SR.InvalidOperation_PrintF); } // Allocate the needed space, format into it, and return the data as a string. byte[] bytes = new byte[neededLength + 1]; // extra byte for the null terminator fixed (byte* ptr = bytes) { int length = stringArg != null ? Interop.Sys.SNPrintF(ptr, bytes.Length, format, stringArg) : Interop.Sys.SNPrintF(ptr, bytes.Length, format, (int)arg); if (length != neededLength) { throw new InvalidOperationException(SR.InvalidOperation_PrintF); } } return Encoding.ASCII.GetString(bytes, 0, neededLength); } /// <summary>Gets the lazily-initialized dynamic or static variables collection, based on the supplied variable name.</summary> /// <param name="c">The name of the variable.</param> /// <param name="dynamicVars">The lazily-initialized dynamic variables collection.</param> /// <param name="staticVars">The lazily-initialized static variables collection.</param> /// <param name="index">The index to use to index into the variables.</param> /// <returns>The variables collection.</returns> private static FormatParam[] GetDynamicOrStaticVariables( char c, ref FormatParam[] dynamicVars, ref FormatParam[] staticVars, out int index) { if (c >= 'A' && c <= 'Z') { index = c - 'A'; return staticVars ?? (staticVars = new FormatParam[26]); // one slot for each letter of alphabet } else if (c >= 'a' && c <= 'z') { index = c - 'a'; return dynamicVars ?? (dynamicVars = new FormatParam[26]); // one slot for each letter of alphabet } else throw new InvalidOperationException(SR.IO_TermInfoInvalid); } /// <summary> /// Represents a parameter to a terminfo formatting string. /// It is a discriminated union of either an integer or a string, /// with characters represented as integers. /// </summary> public struct FormatParam { /// <summary>The integer stored in the parameter.</summary> private readonly int _int32; /// <summary>The string stored in the parameter.</summary> private readonly string _string; // null means an Int32 is stored /// <summary>Initializes the parameter with an integer value.</summary> /// <param name="value">The value to be stored in the parameter.</param> public FormatParam(Int32 value) : this(value, null) { } /// <summary>Initializes the parameter with a string value.</summary> /// <param name="value">The value to be stored in the parameter.</param> public FormatParam(String value) : this(0, value ?? string.Empty) { } /// <summary>Initializes the parameter.</summary> /// <param name="intValue">The integer value.</param> /// <param name="stringValue">The string value.</param> private FormatParam(Int32 intValue, String stringValue) { _int32 = intValue; _string = stringValue; } /// <summary>Implicit converts an integer into a parameter.</summary> public static implicit operator FormatParam(int value) { return new FormatParam(value); } /// <summary>Implicit converts a string into a parameter.</summary> public static implicit operator FormatParam(string value) { return new FormatParam(value); } /// <summary>Gets the integer value of the parameter. If a string was stored, 0 is returned.</summary> public int Int32 { get { return _int32; } } /// <summary>Gets the string value of the parameter. If an Int32 or a null String were stored, an empty string is returned.</summary> public string String { get { return _string ?? string.Empty; } } /// <summary>Gets the string or the integer value as an object.</summary> public object Object { get { return _string ?? (object)_int32; } } } /// <summary>Provides a basic stack data structure.</summary> /// <typeparam name="T">Specifies the type of data in the stack.</typeparam> private sealed class LowLevelStack<T> // System.Console.dll doesn't reference System.Collections.dll { private const int DefaultSize = 4; private T[] _arr; private int _count; public LowLevelStack() { _arr = new T[DefaultSize]; } public T Pop() { if (_count == 0) { throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); } T item = _arr[--_count]; _arr[_count] = default(T); return item; } public void Push(T item) { if (_arr.Length == _count) { T[] newArr = new T[_arr.Length * 2]; Array.Copy(_arr, 0, newArr, 0, _arr.Length); _arr = newArr; } _arr[_count++] = item; } public void Clear() { Array.Clear(_arr, 0, _count); _count = 0; } } } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Linq; namespace NLog { using System; using System.Collections.Generic; using Config; using Internal; /// <summary> /// Mapped Diagnostics Context - a thread-local structure that keeps a dictionary /// of strings and provides methods to output them in layouts. /// </summary> public static class MappedDiagnosticsContext { private static readonly object DataSlot = ThreadLocalStorageHelper.AllocateDataSlot(); private static readonly IDictionary<string, object> EmptyDefaultDictionary = new SortHelpers.ReadOnlySingleBucketDictionary<string, object>(); private sealed class ItemRemover : IDisposable { private readonly string _item; private bool _disposed; public ItemRemover(string item) { _item = item; } public void Dispose() { if (!_disposed) { _disposed = true; Remove(_item); } } } /// <summary> /// Gets the thread-local dictionary /// </summary> /// <param name="create">Must be true for any subsequent dictionary modification operation</param> /// <returns></returns> private static IDictionary<string, object> GetThreadDictionary(bool create = true) { var dictionary = ThreadLocalStorageHelper.GetDataForSlot<Dictionary<string, object>>(DataSlot, create); if (dictionary == null && !create) return EmptyDefaultDictionary; return dictionary; } /// <summary> /// Sets the current thread MDC item to the specified value. /// </summary> /// <param name="item">Item name.</param> /// <param name="value">Item value.</param> /// <returns>An <see cref="IDisposable"/> that can be used to remove the item from the current thread MDC.</returns> public static IDisposable SetScoped(string item, string value) { Set(item, value); return new ItemRemover(item); } /// <summary> /// Sets the current thread MDC item to the specified value. /// </summary> /// <param name="item">Item name.</param> /// <param name="value">Item value.</param> /// <returns>>An <see cref="IDisposable"/> that can be used to remove the item from the current thread MDC.</returns> public static IDisposable SetScoped(string item, object value) { Set(item, value); return new ItemRemover(item); } /// <summary> /// Sets the current thread MDC item to the specified value. /// </summary> /// <param name="item">Item name.</param> /// <param name="value">Item value.</param> public static void Set(string item, string value) { GetThreadDictionary(true)[item] = value; } /// <summary> /// Sets the current thread MDC item to the specified value. /// </summary> /// <param name="item">Item name.</param> /// <param name="value">Item value.</param> public static void Set(string item, object value) { GetThreadDictionary(true)[item] = value; } /// <summary> /// Gets the current thread MDC named item, as <see cref="string"/>. /// </summary> /// <param name="item">Item name.</param> /// <returns>The value of <paramref name="item"/>, if defined; otherwise <see cref="String.Empty"/>.</returns> /// <remarks>If the value isn't a <see cref="string"/> already, this call locks the <see cref="LogFactory"/> for reading the <see cref="LoggingConfiguration.DefaultCultureInfo"/> needed for converting to <see cref="string"/>. </remarks> public static string Get(string item) { return Get(item, null); } /// <summary> /// Gets the current thread MDC named item, as <see cref="string"/>. /// </summary> /// <param name="item">Item name.</param> /// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting a value to a <see cref="string"/>.</param> /// <returns>The value of <paramref name="item"/>, if defined; otherwise <see cref="String.Empty"/>.</returns> /// <remarks>If <paramref name="formatProvider"/> is <c>null</c> and the value isn't a <see cref="string"/> already, this call locks the <see cref="LogFactory"/> for reading the <see cref="LoggingConfiguration.DefaultCultureInfo"/> needed for converting to <see cref="string"/>. </remarks> public static string Get(string item, IFormatProvider formatProvider) { return FormatHelper.ConvertToString(GetObject(item), formatProvider); } /// <summary> /// Gets the current thread MDC named item, as <see cref="object"/>. /// </summary> /// <param name="item">Item name.</param> /// <returns>The value of <paramref name="item"/>, if defined; otherwise <c>null</c>.</returns> public static object GetObject(string item) { object o; if (!GetThreadDictionary(false).TryGetValue(item, out o)) o = null; return o; } /// <summary> /// Returns all item names /// </summary> /// <returns>A set of the names of all items in current thread-MDC.</returns> public static ICollection<string> GetNames() { return GetThreadDictionary(false).Keys; } /// <summary> /// Checks whether the specified item exists in current thread MDC. /// </summary> /// <param name="item">Item name.</param> /// <returns>A boolean indicating whether the specified <paramref name="item"/> exists in current thread MDC.</returns> public static bool Contains(string item) { return GetThreadDictionary(false).ContainsKey(item); } /// <summary> /// Removes the specified <paramref name="item"/> from current thread MDC. /// </summary> /// <param name="item">Item name.</param> public static void Remove(string item) { GetThreadDictionary(true).Remove(item); } /// <summary> /// Clears the content of current thread MDC. /// </summary> public static void Clear() { GetThreadDictionary(true).Clear(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using Xunit; namespace System.Collections.Tests { public partial class Dictionary_IDictionary_NonGeneric_Tests : IDictionary_NonGeneric_Tests { protected override IDictionary NonGenericIDictionaryFactory() { return new Dictionary<string, string>(); } protected override ModifyOperation ModifyEnumeratorThrows => PlatformDetection.IsFullFramework ? base.ModifyEnumeratorThrows : ModifyOperation.Add | ModifyOperation.Insert; protected override ModifyOperation ModifyEnumeratorAllowed => PlatformDetection.IsFullFramework ? base.ModifyEnumeratorAllowed : ModifyOperation.Remove | ModifyOperation.Clear; /// <summary> /// Creates an object that is dependent on the seed given. The object may be either /// a value type or a reference type, chosen based on the value of the seed. /// </summary> protected override object CreateTKey(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes = new byte[stringLength]; rand.NextBytes(bytes); return Convert.ToBase64String(bytes); } /// <summary> /// Creates an object that is dependent on the seed given. The object may be either /// a value type or a reference type, chosen based on the value of the seed. /// </summary> protected override object CreateTValue(int seed) => CreateTKey(seed); protected override Type ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentOutOfRangeException); #region IDictionary tests [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_NonGeneric_ItemSet_NullValueWhenDefaultValueIsNonNull(int count) { IDictionary dictionary = new Dictionary<string, int>(); Assert.Throws<ArgumentNullException>(() => dictionary[GetNewKey(dictionary)] = null); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_NonGeneric_ItemSet_KeyOfWrongType(int count) { if (!IsReadOnly) { IDictionary dictionary = new Dictionary<string, string>(); AssertExtensions.Throws<ArgumentException>("key", () => dictionary[23] = CreateTValue(12345)); Assert.Empty(dictionary); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_NonGeneric_ItemSet_ValueOfWrongType(int count) { if (!IsReadOnly) { IDictionary dictionary = new Dictionary<string, string>(); object missingKey = GetNewKey(dictionary); AssertExtensions.Throws<ArgumentException>("value", () => dictionary[missingKey] = 324); Assert.Empty(dictionary); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_NonGeneric_Add_KeyOfWrongType(int count) { if (!IsReadOnly) { IDictionary dictionary = new Dictionary<string, string>(); object missingKey = 23; AssertExtensions.Throws<ArgumentException>("key", () => dictionary.Add(missingKey, CreateTValue(12345))); Assert.Empty(dictionary); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_NonGeneric_Add_ValueOfWrongType(int count) { if (!IsReadOnly) { IDictionary dictionary = new Dictionary<string, string>(); object missingKey = GetNewKey(dictionary); AssertExtensions.Throws<ArgumentException>("value", () => dictionary.Add(missingKey, 324)); Assert.Empty(dictionary); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_NonGeneric_Add_NullValueWhenDefaultTValueIsNonNull(int count) { if (!IsReadOnly) { IDictionary dictionary = new Dictionary<string, int>(); object missingKey = GetNewKey(dictionary); Assert.Throws<ArgumentNullException>(() => dictionary.Add(missingKey, null)); Assert.Empty(dictionary); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_NonGeneric_Contains_KeyOfWrongType(int count) { if (!IsReadOnly) { IDictionary dictionary = new Dictionary<string, int>(); Assert.False(dictionary.Contains(1)); } } [Fact] public void Clear_OnEmptyCollection_DoesNotInvalidateEnumerator() { if (ModifyEnumeratorAllowed.HasFlag(ModifyOperation.Clear)) { IDictionary dictionary = new Dictionary<string, string>(); IEnumerator valuesEnum = dictionary.GetEnumerator(); dictionary.Clear(); Assert.Empty(dictionary); Assert.False(valuesEnum.MoveNext()); } } #endregion #region ICollection tests [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_NonGeneric_CopyTo_ArrayOfIncorrectKeyValuePairType(int count) { ICollection collection = NonGenericICollectionFactory(count); KeyValuePair<string, int>[] array = new KeyValuePair<string, int>[count * 3 / 2]; AssertExtensions.Throws<ArgumentException>(null, () => collection.CopyTo(array, 0)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_NonGeneric_CopyTo_ArrayOfCorrectKeyValuePairType(int count) { ICollection collection = NonGenericICollectionFactory(count); KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count]; collection.CopyTo(array, 0); int i = 0; foreach (object obj in collection) Assert.Equal(array[i++], obj); } #endregion } public class Dictionary_Tests { [Fact] public void CopyConstructorExceptions() { AssertExtensions.Throws<ArgumentNullException>("dictionary", () => new Dictionary<int, int>((IDictionary<int, int>)null)); AssertExtensions.Throws<ArgumentNullException>("dictionary", () => new Dictionary<int, int>((IDictionary<int, int>)null, null)); AssertExtensions.Throws<ArgumentNullException>("dictionary", () => new Dictionary<int, int>((IDictionary<int, int>)null, EqualityComparer<int>.Default)); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Dictionary<int, int>(new NegativeCountDictionary<int, int>())); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Dictionary<int, int>(new NegativeCountDictionary<int, int>(), null)); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Dictionary<int, int>(new NegativeCountDictionary<int, int>(), EqualityComparer<int>.Default)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(101)] public void ICollection_NonGeneric_CopyTo_NonContiguousDictionary(int count) { ICollection collection = (ICollection)CreateDictionary(count, k => k.ToString()); KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count]; collection.CopyTo(array, 0); int i = 0; foreach (object obj in collection) Assert.Equal(array[i++], obj); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(101)] public void ICollection_Generic_CopyTo_NonContiguousDictionary(int count) { ICollection<KeyValuePair<string, string>> collection = CreateDictionary(count, k => k.ToString()); KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count]; collection.CopyTo(array, 0); int i = 0; foreach (KeyValuePair<string, string> obj in collection) Assert.Equal(array[i++], obj); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(101)] public void IDictionary_Generic_CopyTo_NonContiguousDictionary(int count) { IDictionary<string, string> collection = CreateDictionary(count, k => k.ToString()); KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count]; collection.CopyTo(array, 0); int i = 0; foreach (KeyValuePair<string, string> obj in collection) Assert.Equal(array[i++], obj); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(101)] public void CopyTo_NonContiguousDictionary(int count) { Dictionary<string, string> collection = (Dictionary<string, string>)CreateDictionary(count, k => k.ToString()); string[] array = new string[count]; collection.Keys.CopyTo(array, 0); int i = 0; foreach (KeyValuePair<string, string> obj in collection) Assert.Equal(array[i++], obj.Key); collection.Values.CopyTo(array, 0); i = 0; foreach (KeyValuePair<string, string> obj in collection) Assert.Equal(array[i++], obj.Key); } [Fact] public void Remove_NonExistentEntries_DoesNotPreventEnumeration() { const string SubKey = "-sub-key"; var dictionary = new Dictionary<string, string>(); dictionary.Add("a", "b"); dictionary.Add("c", "d"); foreach (string key in dictionary.Keys) { if (dictionary.Remove(key + SubKey)) break; } dictionary.Add("c" + SubKey, "d"); foreach (string key in dictionary.Keys) { if (dictionary.Remove(key + SubKey)) break; } } [Fact] public void TryAdd_ItemAlreadyExists_DoesNotInvalidateEnumerator() { var dictionary = new Dictionary<string, string>(); dictionary.Add("a", "b"); IEnumerator valuesEnum = dictionary.GetEnumerator(); Assert.False(dictionary.TryAdd("a", "c")); Assert.True(valuesEnum.MoveNext()); } [Theory] [MemberData(nameof(CopyConstructorInt32Data))] public void CopyConstructorInt32(int size, Func<int, int> keyValueSelector, Func<IDictionary<int, int>, IDictionary<int, int>> dictionarySelector) { TestCopyConstructor(size, keyValueSelector, dictionarySelector); } public static IEnumerable<object[]> CopyConstructorInt32Data { get { return GetCopyConstructorData(i => i); } } [Theory] [MemberData(nameof(CopyConstructorStringData))] public void CopyConstructorString(int size, Func<int, string> keyValueSelector, Func<IDictionary<string, string>, IDictionary<string, string>> dictionarySelector) { TestCopyConstructor(size, keyValueSelector, dictionarySelector); } public static IEnumerable<object[]> CopyConstructorStringData { get { return GetCopyConstructorData(i => i.ToString()); } } private static void TestCopyConstructor<T>(int size, Func<int, T> keyValueSelector, Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector) { IDictionary<T, T> expected = CreateDictionary(size, keyValueSelector); IDictionary<T, T> input = dictionarySelector(CreateDictionary(size, keyValueSelector)); Assert.Equal(expected, new Dictionary<T, T>(input)); } [Theory] [MemberData(nameof(CopyConstructorInt32ComparerData))] public void CopyConstructorInt32Comparer(int size, Func<int, int> keyValueSelector, Func<IDictionary<int, int>, IDictionary<int, int>> dictionarySelector, IEqualityComparer<int> comparer) { TestCopyConstructor(size, keyValueSelector, dictionarySelector, comparer); } public static IEnumerable<object[]> CopyConstructorInt32ComparerData { get { var comparers = new IEqualityComparer<int>[] { null, EqualityComparer<int>.Default }; return GetCopyConstructorData(i => i, comparers); } } [Theory] [MemberData(nameof(CopyConstructorStringComparerData))] public void CopyConstructorStringComparer(int size, Func<int, string> keyValueSelector, Func<IDictionary<string, string>, IDictionary<string, string>> dictionarySelector, IEqualityComparer<string> comparer) { TestCopyConstructor(size, keyValueSelector, dictionarySelector, comparer); } [Fact] public void CantAcceptDuplicateKeysFromSourceDictionary() { Dictionary<string, int> source = new Dictionary<string, int> { { "a", 1 }, { "A", 1 } }; AssertExtensions.Throws<ArgumentException>(null, () => new Dictionary<string, int>(source, StringComparer.OrdinalIgnoreCase)); } public static IEnumerable<object[]> CopyConstructorStringComparerData { get { var comparers = new IEqualityComparer<string>[] { null, EqualityComparer<string>.Default, StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase }; return GetCopyConstructorData(i => i.ToString(), comparers); } } private static void TestCopyConstructor<T>(int size, Func<int, T> keyValueSelector, Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector, IEqualityComparer<T> comparer) { IDictionary<T, T> expected = CreateDictionary(size, keyValueSelector, comparer); IDictionary<T, T> input = dictionarySelector(CreateDictionary(size, keyValueSelector, comparer)); Assert.Equal(expected, new Dictionary<T, T>(input, comparer)); } private static IEnumerable<object[]> GetCopyConstructorData<T>(Func<int, T> keyValueSelector, IEqualityComparer<T>[] comparers = null) { var dictionarySelectors = new Func<IDictionary<T, T>, IDictionary<T, T>>[] { d => d, d => new DictionarySubclass<T, T>(d), d => new ReadOnlyDictionary<T, T>(d) }; var sizes = new int[] { 0, 1, 2, 3 }; foreach (Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector in dictionarySelectors) { foreach (int size in sizes) { if (comparers != null) { foreach (IEqualityComparer<T> comparer in comparers) { yield return new object[] { size, keyValueSelector, dictionarySelector, comparer }; } } else { yield return new object[] { size, keyValueSelector, dictionarySelector }; } } } } private static IDictionary<T, T> CreateDictionary<T>(int size, Func<int, T> keyValueSelector, IEqualityComparer<T> comparer = null) { Dictionary<T, T> dict = Enumerable.Range(0, size + 1).ToDictionary(keyValueSelector, keyValueSelector, comparer); // Remove first item to reduce Count to size and alter the contiguity of the dictionary dict.Remove(keyValueSelector(0)); return dict; } [Fact] public void ComparerSerialization() { // Strings switch between randomized and non-randomized comparers, // however this should never be observable externally. TestComparerSerialization(EqualityComparer<string>.Default); // OrdinalCaseSensitiveComparer is internal and (de)serializes as OrdinalComparer TestComparerSerialization(StringComparer.Ordinal, "System.OrdinalComparer"); // OrdinalIgnoreCaseComparer is internal and (de)serializes as OrdinalComparer TestComparerSerialization(StringComparer.OrdinalIgnoreCase, "System.OrdinalComparer"); TestComparerSerialization(StringComparer.CurrentCulture); TestComparerSerialization(StringComparer.CurrentCultureIgnoreCase); TestComparerSerialization(StringComparer.InvariantCulture); TestComparerSerialization(StringComparer.InvariantCultureIgnoreCase); // Check other types while here, IEquatable valuetype, nullable valuetype, and non IEquatable object TestComparerSerialization(EqualityComparer<int>.Default); TestComparerSerialization(EqualityComparer<int?>.Default); TestComparerSerialization(EqualityComparer<object>.Default); } private static void TestComparerSerialization<T>(IEqualityComparer<T> equalityComparer, string internalTypeName = null) { var bf = new BinaryFormatter(); var s = new MemoryStream(); var dict = new Dictionary<T, T>(equalityComparer); Assert.Same(equalityComparer, dict.Comparer); bf.Serialize(s, dict); s.Position = 0; dict = (Dictionary<T, T>)bf.Deserialize(s); if (internalTypeName == null) { Assert.IsType(equalityComparer.GetType(), dict.Comparer); } else { Assert.Equal(internalTypeName, dict.Comparer.GetType().ToString()); } Assert.True(equalityComparer.Equals(dict.Comparer)); } private sealed class DictionarySubclass<TKey, TValue> : Dictionary<TKey, TValue> { public DictionarySubclass(IDictionary<TKey, TValue> dictionary) { foreach (var pair in dictionary) { Add(pair.Key, pair.Value); } } } /// <summary> /// An incorrectly implemented dictionary that returns -1 from Count. /// </summary> private sealed class NegativeCountDictionary<TKey, TValue> : IDictionary<TKey, TValue> { public int Count { get { return -1; } } public TValue this[TKey key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public ICollection<TKey> Keys { get { throw new NotImplementedException(); } } public ICollection<TValue> Values { get { throw new NotImplementedException(); } } public void Add(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public void Add(TKey key, TValue value) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public bool ContainsKey(TKey key) { throw new NotImplementedException(); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new NotImplementedException(); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { throw new NotImplementedException(); } public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public bool Remove(TKey key) { throw new NotImplementedException(); } public bool TryGetValue(TKey key, out TValue value) { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } } }
// 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.StubHelpers; using System.Reflection; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Security; namespace System.Runtime.InteropServices.WindowsRuntime { // // ICustomProperty Implementation helpers // internal static class ICustomPropertyProviderImpl { // // Creates a ICustomProperty implementation for Jupiter // Called from ICustomPropertyProvider_GetProperty from within runtime // static internal ICustomProperty CreateProperty(object target, string propertyName) { Contract.Requires(target != null); Contract.Requires(propertyName != null); IGetProxyTarget proxy = target as IGetProxyTarget; if (proxy != null) target = proxy.GetTarget(); // Only return public instance/static properties PropertyInfo propertyInfo = target.GetType().GetProperty( propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); if (propertyInfo == null) return null; else return new CustomPropertyImpl(propertyInfo); } // // Creates a ICustomProperty implementation for Jupiter // Called from ICustomPropertyProvider_GetIndexedProperty from within runtime // static internal unsafe ICustomProperty CreateIndexedProperty(object target, string propertyName, TypeNameNative* pIndexedParamType) { Contract.Requires(target != null); Contract.Requires(propertyName != null); Type indexedParamType = null; SystemTypeMarshaler.ConvertToManaged(pIndexedParamType, ref indexedParamType); return CreateIndexedProperty(target, propertyName, indexedParamType); } static internal ICustomProperty CreateIndexedProperty(object target, string propertyName, Type indexedParamType) { Contract.Requires(target != null); Contract.Requires(propertyName != null); IGetProxyTarget proxy = target as IGetProxyTarget; if (proxy != null) target = proxy.GetTarget(); // Only return public instance/static properties PropertyInfo propertyInfo = target.GetType().GetProperty( propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, // default binder null, // ignore return type new Type[] { indexedParamType }, // indexed parameter type null // ignore type modifier ); if (propertyInfo == null) return null; else return new CustomPropertyImpl(propertyInfo); } static internal unsafe void GetType(object target, TypeNameNative* pIndexedParamType) { IGetProxyTarget proxy = target as IGetProxyTarget; if (proxy != null) target = proxy.GetTarget(); SystemTypeMarshaler.ConvertToNative(target.GetType(), pIndexedParamType); } } [Flags] internal enum InterfaceForwardingSupport { None = 0, IBindableVector = 0x1, // IBindableVector -> IBindableVector IVector = 0x2, // IBindableVector -> IVector<T> IBindableVectorView = 0x4, // IBindableVectorView -> IBindableVectorView IVectorView = 0x8, // IBindableVectorView -> IVectorView<T> IBindableIterableOrIIterable = 0x10 // IBindableIterable -> IBindableIterable/IIterable<T> } // // Interface for data binding code (CustomPropertyImpl) to retreive the target object // See CustomPropertyImpl.InvokeInternal for details // internal interface IGetProxyTarget { object GetTarget(); } // // Proxy that supports data binding on another object // // This serves two purposes: // // 1. Delegate data binding interfaces to another object // Note that this proxy implements the native interfaces directly to avoid unnecessary overhead // (such as the adapter code that addresses behavior differences between IBindableVector & List // as well as simplify forwarding code (except for IEnumerable) // // 2. ICLRServices.CreateManagedReference will hand out ICCW* of a new instance of this object // and will hold the other object alive // // internal class ICustomPropertyProviderProxy<T1, T2> : IGetProxyTarget, ICustomQueryInterface, IEnumerable, // IBindableIterable -> IBindableIterable/IIterable<T> IBindableVector, // IBindableVector -> IBindableVector/IVector<T> IBindableVectorView // IBindableVectorView -> IBindableVectorView/IVectorView<T> { private object _target; private InterfaceForwardingSupport _flags; internal ICustomPropertyProviderProxy(object target, InterfaceForwardingSupport flags) { _target = target; _flags = flags; } // // Creates a new instance of ICustomPropertyProviderProxy<T1, T2> and assign appropriate // flags // internal static object CreateInstance(object target) { InterfaceForwardingSupport supportFlags = InterfaceForwardingSupport.None; // // QI and figure out the right flags // if (target as IList != null) supportFlags |= InterfaceForwardingSupport.IBindableVector; // NOTE: We need to use the directed type here // If we use IVector_Raw<T1> here, it derives from a different IIterable<T> which the runtime // doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI if (target as IList<T1> != null) supportFlags |= InterfaceForwardingSupport.IVector; if (target as IBindableVectorView != null) supportFlags |= InterfaceForwardingSupport.IBindableVectorView; // NOTE: We need to use the redirected type here // If we use IVector_Raw<T1> here, it derives from a different IIterable<T> which the runtime // doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI if (target as IReadOnlyList<T2> != null) supportFlags |= InterfaceForwardingSupport.IVectorView; // Verify IEnumerable last because the first few QIs might succeed and we need // IEnumerable cast to use that cache (instead of having ICustomPropertyProvider to // forward it manually) // For example, if we try to shoot in the dark by trying IVector<IInspectable> and it // succeeded, IEnumerable needs to know that if (target as IEnumerable != null) supportFlags |= InterfaceForwardingSupport.IBindableIterableOrIIterable; return new ICustomPropertyProviderProxy<T1, T2>(target, supportFlags); } // // override ToString() to make sure callers get correct IStringable.ToString() behavior in native code // public override string ToString() { return WindowsRuntime.IStringableHelper.ToString(_target); } // // IGetProxyTarget - unwraps the target object and use it for data binding // object IGetProxyTarget.GetTarget() { return _target; } // // ICustomQueryInterface methods // public CustomQueryInterfaceResult GetInterface([In]ref Guid iid, out IntPtr ppv) { ppv = IntPtr.Zero; if (iid == typeof(IBindableIterable).GUID) { // Reject the QI if target doesn't implement IEnumerable if ((_flags & (InterfaceForwardingSupport.IBindableIterableOrIIterable)) == 0) return CustomQueryInterfaceResult.Failed; } if (iid == typeof(IBindableVector).GUID) { // Reject the QI if target doesn't implement IBindableVector/IVector if ((_flags & (InterfaceForwardingSupport.IBindableVector | InterfaceForwardingSupport.IVector)) == 0) return CustomQueryInterfaceResult.Failed; } if (iid == typeof(IBindableVectorView).GUID) { // Reject the QI if target doesn't implement IBindableVectorView/IVectorView if ((_flags & (InterfaceForwardingSupport.IBindableVectorView | InterfaceForwardingSupport.IVectorView)) == 0) return CustomQueryInterfaceResult.Failed; } return CustomQueryInterfaceResult.NotHandled; } // // IEnumerable methods // public IEnumerator GetEnumerator() { return ((IEnumerable)_target).GetEnumerator(); } // // IBindableVector implementation (forwards to IBindableVector / IVector<T>) // [Pure] object IBindableVector.GetAt(uint index) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector return bindableVector.GetAt(index); } else { // IBindableVector -> IVector<T> return GetVectorOfT().GetAt(index); } } [Pure] uint IBindableVector.Size { get { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector return bindableVector.Size; } else { // IBindableVector -> IVector<T> return GetVectorOfT().Size; } } } [Pure] IBindableVectorView IBindableVector.GetView() { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector return bindableVector.GetView(); } else { // IBindableVector -> IVector<T> return new IVectorViewToIBindableVectorViewAdapter<T1>(GetVectorOfT().GetView()); } } private sealed class IVectorViewToIBindableVectorViewAdapter<T> : IBindableVectorView { private IVectorView<T> _vectorView; public IVectorViewToIBindableVectorViewAdapter(IVectorView<T> vectorView) { _vectorView = vectorView; } [Pure] object IBindableVectorView.GetAt(uint index) { return _vectorView.GetAt(index); } [Pure] uint IBindableVectorView.Size { get { return _vectorView.Size; } } [Pure] bool IBindableVectorView.IndexOf(object value, out uint index) { return _vectorView.IndexOf(ConvertTo<T>(value), out index); } IBindableIterator IBindableIterable.First() { return new IteratorOfTToIteratorAdapter<T>(_vectorView.First()); } } [Pure] bool IBindableVector.IndexOf(object value, out uint index) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector return bindableVector.IndexOf(value, out index); } else { // IBindableVector -> IVector<T> return GetVectorOfT().IndexOf(ConvertTo<T1>(value), out index); } } void IBindableVector.SetAt(uint index, object value) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.SetAt(index, value); } else { // IBindableVector -> IVector<T> GetVectorOfT().SetAt(index, ConvertTo<T1>(value)); } } void IBindableVector.InsertAt(uint index, object value) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.InsertAt(index, value); } else { // IBindableVector -> IVector<T> GetVectorOfT().InsertAt(index, ConvertTo<T1>(value)); } } void IBindableVector.RemoveAt(uint index) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.RemoveAt(index); } else { // IBindableVector -> IVector<T> GetVectorOfT().RemoveAt(index); } } void IBindableVector.Append(object value) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.Append(value); } else { // IBindableVector -> IVector<T> GetVectorOfT().Append(ConvertTo<T1>(value)); } } void IBindableVector.RemoveAtEnd() { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.RemoveAtEnd(); } else { // IBindableVector -> IVector<T> GetVectorOfT().RemoveAtEnd(); } } void IBindableVector.Clear() { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector bindableVector.Clear(); } else { // IBindableVector -> IVector<T> GetVectorOfT().Clear(); } } private IBindableVector GetIBindableVectorNoThrow() { if ((_flags & InterfaceForwardingSupport.IBindableVector) != 0) return JitHelpers.UnsafeCast<IBindableVector>(_target); else return null; } private IVector_Raw<T1> GetVectorOfT() { if ((_flags & InterfaceForwardingSupport.IVector) != 0) return JitHelpers.UnsafeCast<IVector_Raw<T1>>(_target); else throw new InvalidOperationException(); // We should not go down this path, unless Jupiter pass this out to managed code // and managed code use reflection to do the cast } // // IBindableVectorView implementation (forwarding to IBindableVectorView or IVectorView<T>) // [Pure] object IBindableVectorView.GetAt(uint index) { IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.GetAt(index); else return GetVectorViewOfT().GetAt(index); } [Pure] uint IBindableVectorView.Size { get { IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.Size; else return GetVectorViewOfT().Size; } } [Pure] bool IBindableVectorView.IndexOf(object value, out uint index) { IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.IndexOf(value, out index); else return GetVectorViewOfT().IndexOf(ConvertTo<T2>(value), out index); } IBindableIterator IBindableIterable.First() { IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.First(); else return new IteratorOfTToIteratorAdapter<T2>(GetVectorViewOfT().First()); } private sealed class IteratorOfTToIteratorAdapter<T> : IBindableIterator { private IIterator<T> _iterator; public IteratorOfTToIteratorAdapter(IIterator<T> iterator) { _iterator = iterator; } public bool HasCurrent { get { return _iterator.HasCurrent; } } public object Current { get { return (object)_iterator.Current; } } public bool MoveNext() { return _iterator.MoveNext(); } } private IBindableVectorView GetIBindableVectorViewNoThrow() { if ((_flags & InterfaceForwardingSupport.IBindableVectorView) != 0) return JitHelpers.UnsafeCast<IBindableVectorView>(_target); else return null; } private IVectorView<T2> GetVectorViewOfT() { if ((_flags & InterfaceForwardingSupport.IVectorView) != 0) return JitHelpers.UnsafeCast<IVectorView<T2>>(_target); else throw new InvalidOperationException(); // We should not go down this path, unless Jupiter pass this out to managed code // and managed code use reflection to do the cast } // // Convert to type T // private static T ConvertTo<T>(object value) { // Throw ArgumentNullException if value is null (otherwise we'll throw NullReferenceException // when casting value to T) ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); // No coersion support needed. If we need coersion later, this is the place return (T)value; } } }
using System; namespace WindowsUtilities { public enum ColorConstants: uint { CLR_NONE = 0xFFFFFFFFU, CLR_DEFAULT = 0xFF000000U } public enum InitWindowsCommonControlsConstants: int { ICC_LISTVIEW_CLASSES = 0x00000001, // listview, header ICC_TREEVIEW_CLASSES = 0x00000002, // treeview, tooltips ICC_BAR_CLASSES = 0x00000004, // toolbar, statusbar, trackbar, tooltips ICC_TAB_CLASSES = 0x00000008, // tab, tooltips ICC_UPDOWN_CLASS = 0x00000010, // updown ICC_PROGRESS_CLASS = 0x00000020, // progress ICC_HOTKEY_CLASS = 0x00000040, // hotkey ICC_ANIMATE_CLASS = 0x00000080, // animate ICC_WIN95_CLASSES = 0x000000FF, ICC_DATE_CLASSES = 0x00000100, // month picker, date picker, time picker, updown ICC_USEREX_CLASSES = 0x00000200, // comboex ICC_COOL_CLASSES = 0x00000400, // rebar (coolbar) control ICC_INTERNET_CLASSES = 0x00000800, ICC_PAGESCROLLER_CLASS = 0x00001000, // page scroller ICC_NATIVEFNTCTL_CLASS = 0x00002000, // native font control ICC_STANDARD_CLASSES = 0x00004000, ICC_LINK_CLASS = 0x00008000, } [Flags] public enum RebarBandStyleConstants: uint { RBBS_BREAK = 0x00000001, // break to new line RBBS_FIXEDSIZE = 0x00000002, // band can't be sized RBBS_CHILDEDGE = 0x00000004, // edge around top & bottom of child window RBBS_HIDDEN = 0x00000008, // don't show RBBS_NOVERT = 0x00000010, // don't show when vertical RBBS_FIXEDBMP = 0x00000020, // bitmap doesn't move during band resize RBBS_VARIABLEHEIGHT = 0x00000040, // allow autosizing of this child vertically RBBS_GRIPPERALWAYS = 0x00000080, // always show the gripper RBBS_NOGRIPPER = 0x00000100, // never show the gripper RBBS_USECHEVRON = 0x00000200, // display drop-down button for this band if it's sized smaller than ideal width RBBS_HIDETITLE = 0x00000400, // keep band title hidden RBBS_TOPALIGN = 0x00000800 // keep band title hidden } [Flags]public enum RebarBandInfoConstants: uint { RBBIM_STYLE = 0x00000001, RBBIM_COLORS = 0x00000002, RBBIM_TEXT = 0x00000004, RBBIM_IMAGE = 0x00000008, RBBIM_CHILD = 0x00000010, RBBIM_CHILDSIZE = 0x00000020, RBBIM_SIZE = 0x00000040, RBBIM_BACKGROUND = 0x00000080, RBBIM_ID = 0x00000100, RBBIM_IDEALSIZE = 0x00000200, RBBIM_LPARAM = 0x00000400, RBBIM_HEADERSIZE = 0x00000800 // control the size of the header } [Flags]public enum RebarImageListConstants: uint { RBIM_IMAGELIST = 0x00000001 } [Flags]public enum RebarSizeToRectConstants: uint { RBSTR_CHANGERECT = 0x0001 // flags for RB_SIZETORECT } [Flags] public enum RedrawWindowConstants: uint { RDW_INVALIDATE = 0x0001, RDW_INTERNALPAINT = 0x0002, RDW_ERASE = 0x0004, RDW_VALIDATE = 0x0008, RDW_NOINTERNALPAINT = 0x0010, RDW_NOERASE = 0x0020, RDW_NOCHILDREN = 0x0040, RDW_ALLCHILDREN = 0x0080, RDW_UPDATENOW = 0x0100, RDW_ERASENOW = 0x0200, RDW_FRAME = 0x0400, RDW_NOFRAME = 0x0800 } [Flags] public enum SetWindowPosConstants: uint { SWP_NOSIZE = 0x0001U, SWP_NOMOVE = 0x0002U, SWP_NOZORDER = 0x0004U, SWP_NOREDRAW = 0x0008U, SWP_NOACTIVATE = 0x0010U, SWP_FRAMECHANGED = 0x0020U, /* The frame changed: send WM_NCCALCSIZE */ SWP_SHOWWINDOW = 0x0040U, SWP_HIDEWINDOW = 0x0080U, SWP_NOCOPYBITS = 0x0100U, SWP_NOOWNERZORDER = 0x0200U, /* Don't do owner Z ordering */ SWP_NOSENDCHANGING = 0x0400U, /* Don't send WM_WINDOWPOSCHANGING */ SWP_DRAWFRAME = SWP_FRAMECHANGED, SWP_NOREPOSITION = SWP_NOOWNERZORDER, SWP_DEFERERASE = 0x2000U, SWP_ASYNCWINDOWPOS = 0x4000U, SWP_REDRAWONLY = (SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING) } public enum WindowsHitTestConstants: int { HTERROR = (-2), HTTRANSPARENT = (-1), HTNOWHERE = 0, HTCLIENT = 1, HTCAPTION = 2, HTSYSMENU = 3, HTGROWBOX = 4, HTSIZE = HTGROWBOX, HTMENU = 5, HTHSCROLL = 6, HTVSCROLL = 7, HTMINBUTTON = 8, HTMAXBUTTON = 9, HTLEFT = 10, HTRIGHT = 11, HTTOP = 12, HTTOPLEFT = 13, HTTOPRIGHT = 14, HTBOTTOM = 15, HTBOTTOMLEFT = 16, HTBOTTOMRIGHT = 17, HTBORDER = 18, HTREDUCE = HTMINBUTTON, HTZOOM = HTMAXBUTTON, HTSIZEFIRST = HTLEFT, HTSIZELAST = HTBOTTOMRIGHT, HTOBJECT = 19, HTCLOSE = 20, HTHELP = 21, } public enum WindowLongConstants: int { GWL_WNDPROC = (-4), GWL_HINSTANCE = (-6), GWL_HWNDPARENT = (-8), GWL_STYLE = (-16), GWL_EXSTYLE = (-20), GWL_USERDATA = (-21), GWL_ID = (-12), GWLP_WNDPROC = (-4), GWLP_HINSTANCE = (-6), GWLP_HWNDPARENT = (-8), GWLP_USERDATA = (-21), GWLP_ID = (-12), } public enum WindowsNotifyConstants: int { NM_FIRST = (0- 0), // generic to all controls NM_LAST = (0- 99), LVN_FIRST = (0-100), // listview LVN_LAST = (0-199), HDN_FIRST = (0-300), // header HDN_LAST = (0-399), TVN_FIRST = (0-400), // treeview TVN_LAST = (0-499), TTN_FIRST = (0-520), // tooltips TTN_LAST = (0-549), TCN_FIRST = (0-550), // tab control TCN_LAST = (0-580), CDN_FIRST = (0-601), // common dialog (new) CDN_LAST = (0-699), TBN_FIRST = (0-700), // toolbar TBN_LAST = (0-720), UDN_FIRST = (0-721), // updown UDN_LAST = (0-740), MCN_FIRST = (0-750), // monthcal MCN_LAST = (0-759), DTN_FIRST = (0-760), // datetimepick DTN_LAST = (0-799), CBEN_FIRST = (0-800), // combo box ex CBEN_LAST = (0-830), RBN_FIRST = (0-831), // rebar RBN_LAST = (0-859), IPN_FIRST = (0-860), // internet address IPN_LAST = (0-879), // internet address SBN_FIRST = (0-880), // status bar SBN_LAST = (0-899), PGN_FIRST = (0-900), // Pager Control PGN_LAST = (0-950), WMN_FIRST = (0-1000), WMN_LAST = (0-1200), BCN_FIRST = (0-1250), BCN_LAST = (0-1350), NM_OUTOFMEMORY = (NM_FIRST-1), NM_CLICK = (NM_FIRST-2), // uses NMCLICK struct NM_DBLCLK = (NM_FIRST-3), NM_RETURN = (NM_FIRST-4), NM_RCLICK = (NM_FIRST-5), // uses NMCLICK struct NM_RDBLCLK = (NM_FIRST-6), NM_SETFOCUS = (NM_FIRST-7), NM_KILLFOCUS = (NM_FIRST-8), NM_CUSTOMDRAW = (NM_FIRST-12), NM_HOVER = (NM_FIRST-13), NM_NCHITTEST = (NM_FIRST-14), // uses NMMOUSE struct NM_KEYDOWN = (NM_FIRST-15), // uses NMKEY struct NM_RELEASEDCAPTURE = (NM_FIRST-16), NM_SETCURSOR = (NM_FIRST-17), // uses NMMOUSE struct NM_CHAR = (NM_FIRST-18), // uses NMCHAR struct NM_TOOLTIPSCREATED = (NM_FIRST-19), // notify of when the tooltips window is create NM_LDOWN = (NM_FIRST-20), NM_RDOWN = (NM_FIRST-21), NM_THEMECHANGED = (NM_FIRST-22), RBN_HEIGHTCHANGE = (RBN_FIRST - 0), RBN_GETOBJECT = (RBN_FIRST - 1), RBN_LAYOUTCHANGED = (RBN_FIRST - 2), RBN_AUTOSIZE = (RBN_FIRST - 3), RBN_BEGINDRAG = (RBN_FIRST - 4), RBN_ENDDRAG = (RBN_FIRST - 5), RBN_DELETINGBAND = (RBN_FIRST - 6), // Uses NMREBAR RBN_DELETEDBAND = (RBN_FIRST - 7), // Uses NMREBAR RBN_CHILDSIZE = (RBN_FIRST - 8), RBN_CHEVRONPUSHED = (RBN_FIRST - 10), RBN_MINMAX = (RBN_FIRST - 21), RBN_AUTOBREAK = (RBN_FIRST - 22), } /* public enum blah: int { ODT_HEADER = 100, ODT_TAB = 101, ODT_LISTVIEW = 102, } */ [Flags]public enum WindowsStyleConstants: uint { CCS_TOP = 0x00000001U, CCS_NOMOVEY = 0x00000002U, CCS_BOTTOM = 0x00000003U, CCS_NORESIZE = 0x00000004U, CCS_NOPARENTALIGN = 0x00000008U, CCS_ADJUSTABLE = 0x00000020U, CCS_NODIVIDER = 0x00000040U, CCS_VERT = 0x00000080U, CCS_LEFT = (CCS_VERT | CCS_TOP), CCS_RIGHT = (CCS_VERT | CCS_BOTTOM), CCS_NOMOVEX = (CCS_VERT | CCS_NOMOVEY), RBS_TOOLTIPS = 0x0100, RBS_VARHEIGHT = 0x0200, RBS_BANDBORDERS = 0x0400, RBS_FIXEDORDER = 0x0800, RBS_REGISTERDROP = 0x1000, RBS_AUTOSIZE = 0x2000, RBS_VERTICALGRIPPER = 0x4000, // this always has the vertical gripper (default for horizontal mode) RBS_DBLCLKTOGGLE = 0x8000, WS_OVERLAPPED = 0x00000000U, WS_POPUP = 0x80000000U, WS_CHILD = 0x40000000U, WS_MINIMIZE = 0x20000000U, WS_VISIBLE = 0x10000000U, WS_DISABLED = 0x08000000U, WS_CLIPSIBLINGS = 0x04000000U, WS_CLIPCHILDREN = 0x02000000U, WS_MAXIMIZE = 0x01000000U, WS_CAPTION = 0x00C00000U, /* WS_BORDER | WS_DLGFRAME */ WS_BORDER = 0x00800000U, WS_DLGFRAME = 0x00400000U, WS_VSCROLL = 0x00200000U, WS_HSCROLL = 0x00100000U, WS_SYSMENU = 0x00080000U, WS_THICKFRAME = 0x00040000U, WS_GROUP = 0x00020000U, WS_TABSTOP = 0x00010000U, WS_MINIMIZEBOX = 0x00020000U, WS_MAXIMIZEBOX = 0x00010000U, WS_TILED = WS_OVERLAPPED, WS_ICONIC = WS_MINIMIZE, WS_SIZEBOX = WS_THICKFRAME, WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW, WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX), WS_POPUPWINDOW = (WS_POPUP | WS_BORDER | WS_SYSMENU), WS_CHILDWINDOW = (WS_CHILD) } public enum WindowZOrderConstants: int { HWND_TOP = 0, HWND_BOTTOM = 1, HWND_TOPMOST = -1, HWND_NOTOPMOST = -2 } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.ComIntegration { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime; using System.Runtime.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.ServiceModel.Diagnostics; using System.Threading; using Microsoft.Win32; class TypeCacheManager : ITypeCacheManager { enum RegKind { Default = 0, Register = 1, None = 2 } // TypeCacheManager.Provider will give access to the static instance of the TypeCache static Guid clrAssemblyCustomID = new Guid("90883F05-3D28-11D2-8F17-00A0C9A6186D"); static object instanceLock = new object(); static public ITypeCacheManager Provider { get { lock (instanceLock) { if (instance == null) { ITypeCacheManager localInstance = new TypeCacheManager(); Thread.MemoryBarrier(); instance = localInstance; } } return instance; } } static internal ITypeCacheManager instance; // Convert to typeLibrary ID (GUID) private Dictionary<Guid, Assembly> assemblyTable; private Dictionary<Guid, Type> typeTable; private object typeTableLock; private object assemblyTableLock; internal TypeCacheManager() { assemblyTable = new Dictionary<Guid, Assembly>(); typeTable = new Dictionary<Guid, Type>(); typeTableLock = new object(); assemblyTableLock = new object(); } private Guid GettypeLibraryIDFromIID(Guid iid, bool isServer, out String version) { // In server we need to open the the User hive for the Process User. RegistryKey interfaceKey = null; try { string keyName = null; if (isServer) { keyName = String.Concat("software\\classes\\interface\\{", iid.ToString(), "}\\typelib"); interfaceKey = Registry.LocalMachine.OpenSubKey(keyName, false); } else { keyName = String.Concat("interface\\{", iid.ToString(), "}\\typelib"); interfaceKey = Registry.ClassesRoot.OpenSubKey(keyName, false); } if (interfaceKey == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InterfaceNotRegistered))); string typeLibID = interfaceKey.GetValue("").ToString(); if (string.IsNullOrEmpty(typeLibID)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NoTypeLibraryFoundForInterface))); version = interfaceKey.GetValue("Version").ToString(); if (string.IsNullOrEmpty(version)) version = "1.0"; Guid typeLibraryID; if (!DiagnosticUtility.Utility.TryCreateGuid(typeLibID, out typeLibraryID)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.BadInterfaceRegistration))); } return typeLibraryID; } finally { if (interfaceKey != null) interfaceKey.Close(); } } private void ParseVersion(string version, bool parseVersionAsHex, out ushort major, out ushort minor) { NumberStyles numberStyle = (parseVersionAsHex) ? NumberStyles.HexNumber : NumberStyles.None; major = 0; minor = 0; if (String.IsNullOrEmpty(version)) return; int indexOfDot = version.IndexOf(".", StringComparison.Ordinal); try { if (indexOfDot == -1) { major = ushort.Parse(version, numberStyle, NumberFormatInfo.InvariantInfo); minor = 0; } else { major = ushort.Parse(version.Substring(0, indexOfDot), numberStyle, NumberFormatInfo.InvariantInfo); string minorVersion = version.Substring(indexOfDot + 1); int indexOfDot2 = minorVersion.IndexOf(".", StringComparison.Ordinal); if (indexOfDot2 != -1) // Ignore anything beyond the first minor version. minorVersion = minorVersion.Substring(0, indexOfDot2); minor = ushort.Parse(minorVersion, numberStyle, NumberFormatInfo.InvariantInfo); } } catch (FormatException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.BadInterfaceVersion))); } catch (OverflowException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.BadInterfaceVersion))); } } private ITypeLib2 GettypeLibrary(Guid typeLibraryID, string version, bool parseVersionAsHex) { ushort major = 0; ushort minor = 0; const int lcidLocalIndependent = 0; ParseVersion(version, parseVersionAsHex, out major, out minor); object otlb; int hr = SafeNativeMethods.LoadRegTypeLib(ref typeLibraryID, major, minor, lcidLocalIndependent, out otlb); if (hr != 0 || null == otlb) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new COMException(SR.GetString(SR.FailedToLoadTypeLibrary), hr)); return otlb as ITypeLib2; } private Assembly ResolveAssemblyFromIID(Guid iid, bool noAssemblyGeneration, bool isServer) { String version; Guid typeLibraryID = GettypeLibraryIDFromIID(iid, isServer, out version); return ResolveAssemblyFromTypeLibID(iid, typeLibraryID, version, true, noAssemblyGeneration); } private Assembly ResolveAssemblyFromTypeLibID(Guid iid, Guid typeLibraryID, string version, bool parseVersionAsHex, bool noAssemblyGeneration) { ComPlusTLBImportTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationTLBImportStarting, SR.TraceCodeComIntegrationTLBImportStarting, iid, typeLibraryID); Assembly asm; bool generateNativeAssembly = false; ITypeLib2 typeLibrary = null; try { lock (assemblyTableLock) { assemblyTable.TryGetValue(typeLibraryID, out asm); if (asm == null) { typeLibrary = GettypeLibrary(typeLibraryID, version, parseVersionAsHex); object opaqueData = null; typeLibrary.GetCustData(ref clrAssemblyCustomID, out opaqueData); if (opaqueData == null) generateNativeAssembly = true; // No custom data for this IID this is not a CLR typeLibrary String assembly = opaqueData as String; if (String.IsNullOrEmpty(assembly)) generateNativeAssembly = true; // No custom data for this IID this is not a CLR typeLibrary if (noAssemblyGeneration && generateNativeAssembly) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NativeTypeLibraryNotAllowed, typeLibraryID))); else if (!generateNativeAssembly) { ComPlusTLBImportTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationTLBImportFromAssembly, SR.TraceCodeComIntegrationTLBImportFromAssembly, iid, typeLibraryID, assembly); asm = Assembly.Load(assembly); // Assembly.Load will get a full assembly name } else { ComPlusTLBImportTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationTLBImportFromTypelib, SR.TraceCodeComIntegrationTLBImportFromTypelib, iid, typeLibraryID); asm = TypeLibraryHelper.GenerateAssemblyFromNativeTypeLibrary(iid, typeLibraryID, typeLibrary as ITypeLib); } assemblyTable[typeLibraryID] = asm; } } } catch (Exception e) { DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, (ushort)System.Runtime.Diagnostics.EventLogCategory.ComPlus, (uint)System.Runtime.Diagnostics.EventLogEventId.ComPlusTLBImportError, iid.ToString(), typeLibraryID.ToString(), e.ToString()); throw; } finally { // Add Try Finally to cleanup typeLibrary if (typeLibrary != null) Marshal.ReleaseComObject((object)typeLibrary); } if (null == asm) { throw Fx.AssertAndThrow("Assembly should not be null"); } ComPlusTLBImportTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationTLBImportFinished, SR.TraceCodeComIntegrationTLBImportFinished, iid, typeLibraryID); return asm; } private bool NoCoClassAttributeOnType(ICustomAttributeProvider attrProvider) { object[] attrs = System.ServiceModel.Description.ServiceReflector.GetCustomAttributes(attrProvider, typeof(CoClassAttribute), false); if (attrs.Length == 0) return true; else return false; } Assembly ITypeCacheManager.ResolveAssembly(Guid assembly) { Assembly ret = null; lock (assemblyTableLock) { this.assemblyTable.TryGetValue(assembly, out ret); } return ret; } void ITypeCacheManager.FindOrCreateType(Guid typeLibId, string typeLibVersion, Guid typeDefId, out Type userDefinedType, bool noAssemblyGeneration) { lock (typeTableLock) { typeTable.TryGetValue(typeDefId, out userDefinedType); if (userDefinedType == null) { Assembly asm = ResolveAssemblyFromTypeLibID(Guid.Empty, typeLibId, typeLibVersion, false, noAssemblyGeneration); foreach (Type t in asm.GetTypes()) { if (t.GUID == typeDefId) { if (t.IsValueType) { userDefinedType = t; break; } } } if (userDefinedType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UdtNotFoundInAssembly, typeDefId))); typeTable[typeDefId] = userDefinedType; } } } public void FindOrCreateType(Guid iid, out Type interfaceType, bool noAssemblyGeneration, bool isServer) { lock (typeTableLock) { typeTable.TryGetValue(iid, out interfaceType); if (interfaceType == null) { Type coClassInterface = null; Assembly asm = ResolveAssemblyFromIID(iid, noAssemblyGeneration, isServer); foreach (Type t in asm.GetTypes()) { if (t.GUID == iid) { if (t.IsInterface && NoCoClassAttributeOnType(t)) { interfaceType = t; break; } else if (t.IsInterface && !NoCoClassAttributeOnType(t)) { coClassInterface = t; } } } if ((interfaceType == null) && (coClassInterface != null)) interfaceType = coClassInterface; else if (interfaceType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InterfaceNotFoundInAssembly))); typeTable[iid] = interfaceType; } } } void ITypeCacheManager.FindOrCreateType(Type serverType, Guid iid, out Type interfaceType, bool noAssemblyGeneration, bool isServer) { interfaceType = null; if (serverType == null) FindOrCreateType(iid, out interfaceType, noAssemblyGeneration, isServer); else { if (!serverType.IsClass) { throw Fx.AssertAndThrow("This should be a class"); } foreach (Type interfaceInType in serverType.GetInterfaces()) { if (interfaceInType.GUID == iid) { interfaceType = interfaceInType; break; } } if (interfaceType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InterfaceNotFoundInAssembly))); } } public static Type ResolveClsidToType(Guid clsid) { string keyName = String.Concat("software\\classes\\clsid\\{", clsid.ToString(), "}\\InprocServer32"); using (RegistryKey clsidKey = Registry.LocalMachine.OpenSubKey(keyName, false)) { if (clsidKey != null) { using (RegistryKey assemblyKey = clsidKey.OpenSubKey(typeof(TypeCacheManager).Assembly.ImageRuntimeVersion)) { string assemblyName = null; if (assemblyKey == null) { keyName = null; foreach (string subKeyName in clsidKey.GetSubKeyNames()) { keyName = subKeyName; if (String.IsNullOrEmpty(keyName)) continue; using (RegistryKey assemblyKeyAny = clsidKey.OpenSubKey(keyName)) { assemblyName = (string)assemblyKeyAny.GetValue("Assembly"); if (String.IsNullOrEmpty(assemblyName)) continue; else break; } } } else { assemblyName = (string)assemblyKey.GetValue("Assembly"); } if (String.IsNullOrEmpty(assemblyName)) return null; Assembly asm = Assembly.Load(assemblyName); foreach (Type type in asm.GetTypes()) { if (type.IsClass && (type.GUID == clsid)) return type; } return null; } } } // We failed to get the hive information from a native process hive lets go for the alternative bitness using (RegistryHandle hkcr = RegistryHandle.GetBitnessHKCR(IntPtr.Size == 8 ? false : true)) { if (hkcr != null) { using (RegistryHandle clsidKey = hkcr.OpenSubKey(String.Concat("CLSID\\{", clsid.ToString(), "}\\InprocServer32"))) { using (RegistryHandle assemblyKey = clsidKey.OpenSubKey(typeof(TypeCacheManager).Assembly.ImageRuntimeVersion)) { string assemblyName = null; if (assemblyKey == null) { keyName = null; foreach (string subKeyName in clsidKey.GetSubKeyNames()) { keyName = subKeyName; if (String.IsNullOrEmpty(keyName)) continue; using (RegistryHandle assemblyKeyAny = clsidKey.OpenSubKey(keyName)) { assemblyName = (string)assemblyKeyAny.GetStringValue("Assembly"); if (String.IsNullOrEmpty(assemblyName)) continue; else break; } } } else { assemblyName = assemblyKey.GetStringValue("Assembly"); } if (String.IsNullOrEmpty(assemblyName)) return null; Assembly asm = Assembly.Load(assemblyName); foreach (Type type in asm.GetTypes()) { if (type.IsClass && (type.GUID == clsid)) return type; } return null; } } } } return null; } internal Type VerifyType(Guid iid) { Type interfaceType; ((ITypeCacheManager)(this)).FindOrCreateType(iid, out interfaceType, false, true); return interfaceType; } } }
namespace SHET { using System; using System.Collections.Generic; using System.Linq; using Helpers; using Statistics; using static global::SHET.TreeNode; public class SHET { public static readonly int[] Vertices = new int[] { 1000, 2500, 5000, 10000, 50000 , 100000 }; public static readonly double[][] KFactor = new double[][]{ new double[] {0.02, 0.05, 0.08, 0.18, 0.33}, // 1000 new double[] {0.01, 0.04, 0.07, 0.13, 0.36}, // 2500 new double[] {0.01, 0.04, 0.07, 0.1, 0.36}, // 5000 new double[] {0.009, 0.03, 0.06, 0.09, 0.33}, // 10000 new double[] {0.007, 0.01, 0.036, 0.082, 0.12}, // 50000 new double[] { 0.004, 0.01, 0.02, 0.03, 0.04 } // 100000 }; // public static readonly int[] Vertices = new int[] { 5 }; // public static readonly double[][] KFactor = new double[][]{ // new double[] {0.57}, // 50 // }; private Stats InitializeRunStats(int n, int k) { var stats = new Stats(); stats.Parameters["Algorithm"] = "Shet"; stats.Parameters["n"] = n.ToString(System.Globalization.CultureInfo.InvariantCulture); stats.Parameters["k"] = k.ToString(System.Globalization.CultureInfo.InvariantCulture); stats.Parameters["n/k"] = ((float)n / k).ToString(System.Globalization.CultureInfo.InvariantCulture); stats.Times["treeTime"] = new List<double>(); stats.Times["subTreesTime"] = new List<double>(); stats.Times["ctreeTime"] = new List<double>(); stats.Times["Total"] = new List<double>(); stats.Output["edgeDensity"] = new List<double>(); stats.Output["CC"] = new List<double>(); stats.Output["Mem"] = new List<double>(); return stats; } public TreeStatistics SHETBFSStatistics(long edges, IEnumerable<TreeNode> tree) { var count = tree.Count(); var avgDegree = 2.0 * (count - 1) / count; var tStats = new TreeStatistics(); var visited = new HashSet<TreeNode>(); var stack = new Stack<TreeNode>(); var root = tree.First(); var farthestNode = root; stack.Push(root); while (stack.Count > 0) { var clique = stack.Pop(); visited.Add(clique); var degree = 0; foreach (var child in clique.Adjoint.Where(c => (c.State == NodeState.Valid || c.State == NodeState.NewCC) && !visited.Contains(c))) { child.Height = clique.Height + 1; degree++; stack.Push(child); // calculate for each edge tStats.NumEdges++; var seperatorCount = clique.CliqueList.Intersect(child.CliqueList).Count(); tStats.SumWeight += seperatorCount; tStats.MaxWeight = Math.Max(tStats.MaxWeight, seperatorCount); tStats.MinWeight = tStats.MinWeight == 0 ? seperatorCount : Math.Min(tStats.MinWeight, seperatorCount); if (!tStats.DistributionWeight.ContainsKey(seperatorCount)) { tStats.DistributionWeight[seperatorCount] = 1; } else { tStats.DistributionWeight[seperatorCount] += 1; } } var size = clique.CliqueList.Count; tStats.Num++; tStats.Width = Math.Max(tStats.Width, degree); tStats.Height = Math.Max(tStats.Height, clique.Height); tStats.DegreesVar += (degree - avgDegree) * (degree - avgDegree); tStats.MaxSize = Math.Max(tStats.MaxSize, size); tStats.MinSize = tStats.MinSize == 0 ? clique.CliqueList.Count : Math.Min(tStats.MinSize, clique.CliqueList.Count); tStats.SumSize += clique.CliqueList.Count; if (!tStats.DistributionSize.ContainsKey(size)) { tStats.DistributionSize[size] = 1; } else { tStats.DistributionSize[size] += 1; } if (clique.Height > farthestNode.Height) { farthestNode = clique; } } tStats.MaxCliqueDistribution = ((tStats.MaxSize * (tStats.MaxSize - 1)) / 2.0) / edges; tStats.AvgSize = tStats.SumSize / (double)tStats.Num; tStats.AvgWeight = tStats.SumWeight / (double)tStats.NumEdges; // run a second bfs from farthest vertex to get the diameter farthestNode.Height = 0; visited = new HashSet<TreeNode>(); stack = new Stack<TreeNode>(); stack.Push(farthestNode); while (stack.Count > 0) { var clique = stack.Pop(); visited.Add(clique); foreach (var child in clique.Adjoint.Where(c => (c.State == NodeState.Valid || c.State == NodeState.NewCC) && !visited.Contains(c))) { child.Height = clique.Height + 1; stack.Push(child); } tStats.Diameter = Math.Max(tStats.Diameter, clique.Height); } return tStats; } private void CalculateRunStatistics(long n, long edges, List<TreeNode> tree, Stats stats) { long maxEdges = ((long)n * (n - 1)) / 2L; var validCliques = tree.Where(x => x.State == NodeState.Valid || x.State == NodeState.NewCC); stats.Edges.Add(edges); stats.Output["edgeDensity"].Add(Convert.ToDouble(Decimal.Divide((decimal)edges, (decimal)maxEdges))); stats.Output["CC"].Add(validCliques.Where(x => x.State == NodeState.NewCC).Count()); stats.CliqueTrees.Add(this.SHETBFSStatistics(edges, validCliques)); var proc = System.Diagnostics.Process.GetCurrentProcess(); stats.Output["Mem"].Add(proc.WorkingSet64 / (1024.0 * 1024.0)); } public void PrintRunStatistics(Stats stats) { Console.WriteLine($"Edges: {stats.Edges.Last()} - {stats.Output["edgeDensity"].Last()}"); Console.WriteLine($"CC: {stats.Output["CC"].Last()}"); Console.WriteLine($"Clique tree:"); Console.WriteLine($"\tMax clique distr.: {stats.CliqueTrees.Last().MaxCliqueDistribution}"); Console.WriteLine($"\tNum: {stats.CliqueTrees.Last().Num}"); Console.WriteLine($"\tMin: {stats.CliqueTrees.Last().MinSize}"); Console.WriteLine($"\tMax: {stats.CliqueTrees.Last().MaxSize}"); } public List<Stats> MergeStatistics(List<Stats> stats) { var allStats = new List<Stats>(); foreach (var stat in stats) { var finalStats = new Stats() { Parameters = stat.Parameters }; allStats.Add(finalStats); foreach (var key in stat.Times.Keys) { finalStats.Times[key] = TreeStatistics.AverageStd(stat.Times[key]); } finalStats.Edges = TreeStatistics.AverageStd(stat.Edges); foreach (var key in stat.Output.Keys) { finalStats.Output[key] = TreeStatistics.AverageStd(stat.Output[key]); } finalStats.CliqueTrees = TreeStatistics.AvgStdTreeStats(stat.CliqueTrees); } return allStats; } public List<Stats> RunSHET(int runs) { var allStats = new List<Stats>(); for (int nIndex = 0; nIndex < Vertices.Length; nIndex++) { var n = Vertices[nIndex]; foreach (var kfactor in KFactor[nIndex]) { var k = (int)(n * kfactor); k = Math.Max(1, k); k = Math.Min((int)(n / 2), k); var stats = this.InitializeRunStats(n, k); allStats.Add(stats); for (int r = 0; r < runs; r++) { if ((2 * k) - 1 > n) { throw new Exception("chordal gen parameter k must be lower than n/2"); } Console.WriteLine("------------------ Begin Run --------------------"); Console.WriteLine($"n:{n} \t k:{k} \t"); var random = new Random(); var tree = new List<TreeNode>(); using (var sw = new Watch(stats.Times["treeTime"])) { tree = TreeNode.GenerateTree(n, random); } using (var sw = new Watch(stats.Times["subTreesTime"])) { for (int i = 0; i < n; i++) { TreeNode.SubTreeGeneration(tree, k, i, random); } } long edges = 0; using (var sw = new Watch(stats.Times["ctreeTime"])) { edges = CliqueTree.ConvertToGraph(tree, n); } stats.Times["Total"].Add(stats.Times["treeTime"].Last() + stats.Times["subTreesTime"].Last() + stats.Times["ctreeTime"].Last()); Console.WriteLine($"Generate tree time: {stats.Times["treeTime"].Last()} s"); Console.WriteLine($"Subtrees time: {stats.Times["subTreesTime"].Last()} s"); Console.WriteLine($"Convert clique tree time: {stats.Times["ctreeTime"].Last()} s"); this.CalculateRunStatistics(n, edges, tree, stats); this.PrintRunStatistics(stats); Console.WriteLine("------------------ End Run --------------------"); } var runStats = this.MergeStatistics(new List<Stats>() { stats }); ExcelReporter.ExcelReporter.CreateSpreadsheetWorkbook($"ShetMem_{n}_{kfactor}", runStats); } } return this.MergeStatistics(allStats); } } }